在 Python 中运行外部程序(可执行文件)?

发布于 2024-08-12 16:08:46 字数 617 浏览 4 评论 0原文

我刚刚开始使用 Python,并一直尝试从 Python 运行外部可执行文件。

我有一个用 Fortran 编写的程序的可执行文件。假设可执行文件的名称是 flow.exe,我的可执行文件位于 C:\Documents and Settings\flow_model。我尝试了 os.systempopen 命令,但到目前为止,我还无法让它发挥作用。以下代码似乎打开了命令窗口,但它不会执行模型。

# 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

喜爱纠缠 2024-08-19 16:08:47

对于上述问题,该解决方案有效。

只需更改可执行文件所在的路径即可。

import sys, string, os

os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')

os.system("C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\flowwork.exe")


'''import sys, string, os

os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')

os.system(r"C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\pdftopng.exe test1.pdf rootimage")'''

这里 test1.pdf rootimage 用于我的代码。

for the above question this solution works.

just change the path to where your executable file is located.

import sys, string, os

os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')

os.system("C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\flowwork.exe")


'''import sys, string, os

os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')

os.system(r"C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\pdftopng.exe test1.pdf rootimage")'''

Here test1.pdf rootimage is for my code .

比忠 2024-08-19 16:08:46

如果使用 Python 2.7 或更高版本(尤其是 Python 3.5 之前的版本),您可以使用以下

import subprocess
  • 命令:subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
    运行 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"] )

在常规 Python 字符串中,\U 字符组合表示
扩展 Unicode 代码点转义。

以下是文档的链接: 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:

import subprocess
  • 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"])

In regular Python strings, the \U character combination signals a
extended Unicode code point escape.

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

薯片软お妹 2024-08-19 16:08:46

最简单的方法是:

import os
os.startfile("C:\Documents and Settings\flow_model\flow.exe")

有效;我试过了。

The simplest way is:

import os
os.startfile("C:\Documents and Settings\flow_model\flow.exe")

It works; I tried it.

白馒头 2024-08-19 16:08:46

这些空格确实很麻烦。尝试 os.chdir('C:/Documents\ and\ Settings/') 后跟 os.systemsubprocess 方法的相对路径,或者其他什么......

如果尽力尝试绕过路径中的空白障碍仍然失败,那么我的下一个最佳建议是避免在关键路径中出现空白。您不能创建一个无空白的目录,将关键的 .exe 文件复制到那里,然后尝试那个吗?那些破坏性的空间对你的幸福绝对重要吗……?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.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...?

愿得七秒忆 2024-08-19 16:08:46

如果我是你,我会尝试在你的路径前面插入一个“r”,以表明它是一个原始字符串 - 然后你就不必使用正斜杠。例如:

os.system(r"C:\Documents and Settings\flow_model\flow.exe")

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:

os.system(r"C:\Documents and Settings\flow_model\flow.exe")
地狱即天堂 2024-08-19 16:08:46

您的用法是正确的。我敢打赌,您的外部程序 flow.exe 需要在其目录中执行,因为它访问存储在那里的一些外部文件。

所以你可以尝试:(

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\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:

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')

(Beware of the double quotes inside the single quotes...)

留蓝 2024-08-19 16:08:46

使用子进程,它是一个较小的模块,因此它可以更快地运行.exe

import subprocess
subprocess.Popen([r"U:\Year 8\kerbal space program\KSP.exe"])

Use subprocess, it is a smaller module so it runs the .exe quicker.

import subprocess
subprocess.Popen([r"U:\Year 8\kerbal space program\KSP.exe"])
静赏你的温柔 2024-08-19 16:08:46

通过使用 os.system

import os
os.system(r'"C:/Documents and Settings/flow_model/flow.exe"')

By using os.system:

import os
os.system(r'"C:/Documents and Settings/flow_model/flow.exe"')
挽心 2024-08-19 16:08:46

尝试

import subprocess
subprocess.call(["C:/Documents and Settings/flow_model/flow.exe"])

Try

import subprocess
subprocess.call(["C:/Documents and Settings/flow_model/flow.exe"])
吹梦到西洲 2024-08-19 16:08:46

如果是我,我会将 EXE 文件放在根目录(C:)中,看看是否可以这样工作。如果是这样,则可能是目录名称中(已经提到的)空格。如果不是的话,可能是一些环境变量的问题。

另外,尝试检查你的stderr(使用int3的早期答案):

import subprocess
process = subprocess.Popen(["C:/Documents and Settings/flow_model/flow.exe"], \
                           stderr = subprocess.PIPE)
if process.stderr:
    print process.stderr.readlines()

代码可能不完全正确,因为我通常不使用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):

import subprocess
process = subprocess.Popen(["C:/Documents and Settings/flow_model/flow.exe"], \
                           stderr = subprocess.PIPE)
if process.stderr:
    print process.stderr.readlines()

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.

¢蛋碎的人ぎ生 2024-08-19 16:08:46
import os
path = "C:/Documents and Settings/flow_model/"
os.chdir(path)
os.system("flow.exe")

由 barlop 添加的注释

评论者询问为什么这样做有效。这就是原因。

OP的问题是当路径中有空格时 os.system("...") 无法正常工作。 (注意 os.system 可以使用 ('"...."') 但无论如何)

如果 OP 从 cmd 提示符尝试他们的程序,他们就会清楚地看到错误。

    C:\carp>type blah.py
    import  os
    os.system(R"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
    
    C:\carp>python blah.py
    'C:\Program' is not recognized as an internal or external command,
    operable program or batch file.
    
    C:\carp>

所以对于 os.system("calc.exe") 来说没问题(其中 calc.exe 在路径环境变量中)。或者对于 os.system(R"c:\windows\system32\calc.exe")。那条路上没有空间。

C:\>md "aa bb cc"

C:\>copy c:\windows\system32\calc.exe "c:\aa bb cc\cccalc.exe"
        1 file(s) copied.

这有效(给定文件“c:\aa bb cc\cccalc.exe”)

import  os 
os.chdir(R"c:\aa bb cc")
os.system("cccalc.exe")

其他选项是 subprocess.run 和 subprocess.popen。

import os
path = "C:/Documents and Settings/flow_model/"
os.chdir(path)
os.system("flow.exe")

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.

    C:\carp>type blah.py
    import  os
    os.system(R"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
    
    C:\carp>python blah.py
    'C:\Program' is not recognized as an internal or external command,
    operable program or batch file.
    
    C:\carp>

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.

C:\>md "aa bb cc"

C:\>copy c:\windows\system32\calc.exe "c:\aa bb cc\cccalc.exe"
        1 file(s) copied.

This works (Given file "c:\aa bb cc\cccalc.exe" )

import  os 
os.chdir(R"c:\aa bb cc")
os.system("cccalc.exe")

Other options are subprocess.run and subprocess.popen.

娇妻 2024-08-19 16:08:46

在 python 2.6 中,使用引号 " 和撇号 ' 标记内的字符串。还将单 / 更改为双 //。
您的工作示例将如下所示:

import os
os.system("'C://Documents and Settings//flow_model//flow.exe'") 

此外,如果您的程序摄取了任何参数,您也可以使用它们。

os.system('C://"Program Files (x86)"//Maxima-gcl-5.37.3//gnuplot//bin//gnuplot -e "plot [-10:10] sin(x),atan(x),cos(atan(x)); pause mouse"')

最后你可以使用字符串变量,例如直接从 python 使用 gnuplot 进行绘图:

this_program='C://"Program Files (x86)"//Maxima-gcl-5.37.3//gnuplot//bin//gnuplot'

this_par='-e "set polar; plot [-2*pi:2*pi] [-3:3] [-3:3] t*sin(t); pause -1"'
os.system(this_program+" "+this_par)

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:

import os
os.system("'C://Documents and Settings//flow_model//flow.exe'") 

Also You can use any parameters if Your program ingest them.

os.system('C://"Program Files (x86)"//Maxima-gcl-5.37.3//gnuplot//bin//gnuplot -e "plot [-10:10] sin(x),atan(x),cos(atan(x)); pause mouse"')

finally You can use string variable, as an example is plotting using gnuplot directly from python:

this_program='C://"Program Files (x86)"//Maxima-gcl-5.37.3//gnuplot//bin//gnuplot'

this_par='-e "set polar; plot [-2*pi:2*pi] [-3:3] [-3:3] t*sin(t); pause -1"'
os.system(this_program+" "+this_par)
蓝眼泪 2024-08-19 16:08:46

是否尝试使用 "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().

江心雾 2024-08-19 16:08:46

有很多不同的解决方案,结果很大程度上取决于:

  • 您正在使用的操作系统:Windows、Cygwin、Linux、MacOS
  • 您正在使用的 Python 版本:Python2 或 Python3x

正如我发现的一些那些声称只能在 Windows 中工作的东西,实际上并不适用,可能是因为我碰巧使用 Cygwin,它比操作系统处理 Windows 路径的方式更聪明。其他的东西只能在纯基于 *nix 的操作系统或 Python2 或 3 中工作。

以下是我的发现:

  • 一般来说,os.system() 是最宽容的方法。
  • os.startfile() 是最不宽容的。 (仅限 Windows,如果幸运的话)
  • subprocess.Popen([...]) 推荐
  • subprocess.run(winView, shell=是的) 推荐的方式!
  • 请记住,对任何事情使用subprocess都可能带来安全风险

尝试以下操作:

import os, subprocess
...
winView = '/cygdrive/c/Windows/explorer.exe %s' % somefile
...
# chose one of these:
os.system(winView)
subprocess.Popen(['/cygdrive/c/Windows/explorer.exe', 'somefile.png'])
subprocess.run(winView, shell=True)

问:为什么要在 Windows 中使用 explorer

答:因为如果您只想查看某个新文件的结果,资源管理器将自动使用您为该文件类型设置的任何默认 Windows 程序打开该文件。因此无需重新指定要使用的默认程序。

There are loads of different solutions, and the results will strongly depend on:

  • the OS you are using: Windows, Cygwin, Linux, MacOS
  • the python version you are using: Python2 or Python3x

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:

  • Generally speaking, os.system() is the most forgiving method.
  • os.startfile() is the least forgiving. (Windows only && if you're lucky)
  • subprocess.Popen([...]) not recommended
  • subprocess.run(winView, shell=True) the recommended way!
  • Remembering that using subprocess for anything may pose a security risk.

Try these:

import os, subprocess
...
winView = '/cygdrive/c/Windows/explorer.exe %s' % somefile
...
# chose one of these:
os.system(winView)
subprocess.Popen(['/cygdrive/c/Windows/explorer.exe', 'somefile.png'])
subprocess.run(winView, shell=True)

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.

⒈起吃苦の倖褔 2024-08-19 16:08:46

这是正确的用法,但也许路径名中的空格由于某种原因把事情弄乱了。

您可能还想在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文