在 Python 中运行外部程序(可执行文件)?
我刚刚开始使用 Python,并一直尝试从 Python 运行外部可执行文件。
我有一个用 Fortran 编写的程序的可执行文件。假设可执行文件的名称是 flow.exe
,我的可执行文件位于 C:\Documents and Settings\flow_model
。我尝试了 os.system
和 popen
命令,但到目前为止,我还无法让它发挥作用。以下代码似乎打开了命令窗口,但它不会执行模型。
# Import system modules
import sys, string, os, arcgisscripting
os.system("C:/Documents and Settings/flow_model/flow.exe")
我该如何解决这个问题?
I just started working on Python and have been trying to run an outside executable from Python.
I have an executable for a program written in Fortran. Let’s say the name for the executable is flow.exe
, and my executable is located in C:\Documents and Settings\flow_model
. I tried both os.system
and popen
commands, but so far, I couldn't make it work. The following code seems like it opens the command window, but it wouldn't execute the model.
# Import system modules
import sys, string, os, arcgisscripting
os.system("C:/Documents and Settings/flow_model/flow.exe")
How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
对于上述问题,该解决方案有效。
只需更改可执行文件所在的路径即可。
这里 test1.pdf rootimage 用于我的代码。
for the above question this solution works.
just change the path to where your executable file is located.
Here test1.pdf rootimage is for my code .
如果使用 Python 2.7 或更高版本(尤其是 Python 3.5 之前的版本),您可以使用以下
运行 args 描述的命令。等待命令完成,然后返回 returncode 属性。
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
运行带参数的命令。等待命令完成。如果返回码为零则返回,否则引发 CalledProcessError。 CalledProcessError 对象将在 returncode 属性中包含返回代码
示例:
subprocess.check_call([r"C:\pathToYourProgram\yourProgram.exe", "your", "arguments", "comma", "separated"] )
以下是文档的链接: http://docs.python.org/3.2/library /subprocess.html
对于 Python 3.5+,您现在可以在许多情况下使用 run(): https://docs.python.org/3.5/library/subprocess.html#subprocess.run
If using Python 2.7 or higher (especially prior to Python 3.5) you can use the following:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Runs the command described by args. Waits for command to complete, then returns the returncode attribute.
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Runs command with arguments. Waits for command to complete. If the return code was zero then returns, otherwise raises CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute
Example:
subprocess.check_call([r"C:\pathToYourProgram\yourProgram.exe", "your", "arguments", "comma", "separated"])
Here is the link to the documentation: http://docs.python.org/3.2/library/subprocess.html
For Python 3.5+ you can now use run() in many cases: https://docs.python.org/3.5/library/subprocess.html#subprocess.run
最简单的方法是:
有效;我试过了。
The simplest way is:
It works; I tried it.
这些空格确实很麻烦。尝试 os.chdir('C:/Documents\ and\ Settings/') 后跟
os.system
、subprocess
方法的相对路径,或者其他什么......如果尽力尝试绕过路径中的空白障碍仍然失败,那么我的下一个最佳建议是避免在关键路径中出现空白。您不能创建一个无空白的目录,将关键的
.exe
文件复制到那里,然后尝试那个吗?那些破坏性的空间对你的幸福绝对重要吗……?Those whitespaces can really be a bother. Try
os.chdir('C:/Documents\ and\ Settings/')
followed by relative paths foros.system
,subprocess
methods, or whatever...If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial
.exe
file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?如果我是你,我会尝试在你的路径前面插入一个“r”,以表明它是一个原始字符串 - 然后你就不必使用正斜杠。例如:
I'd try inserting an 'r' in front of your path if I were you, to indicate that it's a raw string - and then you won't have to use forward slashes. For example:
您的用法是正确的。我敢打赌,您的外部程序 flow.exe 需要在其目录中执行,因为它访问存储在那里的一些外部文件。
所以你可以尝试:(
注意单引号内的双引号......)
Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.
So you might try:
(Beware of the double quotes inside the single quotes...)
使用子进程,它是一个较小的模块,因此它可以更快地运行
.exe
。Use subprocess, it is a smaller module so it runs the
.exe
quicker.通过使用 os.system:
By using os.system:
尝试
Try
如果是我,我会将 EXE 文件放在根目录(C:)中,看看是否可以这样工作。如果是这样,则可能是目录名称中(已经提到的)空格。如果不是的话,可能是一些环境变量的问题。
另外,尝试检查你的stderr(使用int3的早期答案):
代码可能不完全正确,因为我通常不使用Popen或Windows,但应该给出这个想法。错误消息很可能位于错误流上。
If it were me, I'd put the EXE file in the root directory (C:) and see if it works like that. If so, it's probably the (already mentioned) spaces in the directory name. If not, it may be some environment variables.
Also, try to check you stderr (using an earlier answer by int3):
The code might not be entirely correct as I usually don't use Popen or Windows, but should give the idea. It might well be that the error message is on the error stream.
由 barlop 添加的注释
评论者询问为什么这样做有效。这就是原因。
OP的问题是当路径中有空格时 os.system("...") 无法正常工作。 (注意 os.system 可以使用 ('"...."') 但无论如何)
如果 OP 从 cmd 提示符尝试他们的程序,他们就会清楚地看到错误。
所以对于 os.system("calc.exe") 来说没问题(其中 calc.exe 在路径环境变量中)。或者对于 os.system(R"c:\windows\system32\calc.exe")。那条路上没有空间。
这有效(给定文件“c:\aa bb cc\cccalc.exe”)
其他选项是 subprocess.run 和 subprocess.popen。
Note added by barlop
A commenter asked why this works. Here is why.
The OP's problem is os.system("...") doesn't work properly when there is a space in the path. (Note os.system can work with ('"...."') but anyhow)
Had the OP tried their program from a cmd prompt they'd have seen the error clearly.
So it's fine for os.system("calc.exe") (there calc.exe is in the path environment variable). Or for os.system(R"c:\windows\system32\calc.exe"). There's no space in that path.
This works (Given file "c:\aa bb cc\cccalc.exe" )
Other options are subprocess.run and subprocess.popen.
在 python 2.6 中,使用引号 " 和撇号 ' 标记内的字符串。还将单 / 更改为双 //。
您的工作示例将如下所示:
此外,如果您的程序摄取了任何参数,您也可以使用它们。
最后你可以使用字符串变量,例如直接从 python 使用 gnuplot 进行绘图:
in python 2.6 use string enclosed inside quotation " and apostrophe ' marks. Also a change single / to double //.
Your working example will look like this:
Also You can use any parameters if Your program ingest them.
finally You can use string variable, as an example is plotting using gnuplot directly from python:
是否尝试使用
"and", "Settings/flow_model/flow.exe"
参数执行C:\Documents
?另外,您可能会考虑
subprocess.call()
。Is that trying to execute
C:\Documents
with arguments of"and", "Settings/flow_model/flow.exe"
?Also, you might consider
subprocess.call()
.有很多不同的解决方案,结果很大程度上取决于:
正如我发现的一些那些声称只能在 Windows 中工作的东西,实际上并不适用,可能是因为我碰巧使用 Cygwin,它比操作系统处理 Windows 路径的方式更聪明。其他的东西只能在纯基于 *nix 的操作系统或 Python2 或 3 中工作。
以下是我的发现:
os.system()
是最宽容的方法。subprocess.Popen([...])
不推荐subprocess.run(winView, shell=是的)
推荐的方式!subprocess
都可能带来安全风险。尝试以下操作:
问:为什么要在 Windows 中使用
explorer
?答:因为如果您只想查看某个新文件的结果,资源管理器将自动使用您为该文件类型设置的任何默认 Windows 程序打开该文件。因此无需重新指定要使用的默认程序。
There are loads of different solutions, and the results will strongly depend on:
As I have discovered some things that are claimed to work only in Windows, doesn't, probably because I happen to use Cygwin which is outsmarting the OS way to deal with Windows paths. Other things only work in pure *nix based OS's or in Python2 or 3.
Here are my findings:
os.system()
is the most forgiving method.os.startfile()
is the least forgiving. (Windows only && if you're lucky)subprocess.Popen([...])
not recommendedsubprocess.run(winView, shell=True)
the recommended way!subprocess
for anything may pose a security risk.Try these:
Q: Why would you want to use
explorer
in Windows?A: Because if you just want to look at the results of some new file, explorer will automatically open the file with whatever default windows program you have set for that file type. So no need to re-specify the default program to use.
这是正确的用法,但也许路径名中的空格由于某种原因把事情弄乱了。
您可能还想在 cmd.exe 下运行该程序,以便可以看到 flow.exe 中可能指示错误的任何输出。
That's the correct usage, but perhaps the spaces in the path name are messing things up for some reason.
You may want to run the program under cmd.exe as well so you can see any output from flow.exe that might be indicating an error.