简体   繁体   English

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

[英]Running an outside program (executable) in Python?

I just started working on Python, and I have been trying to run an outside executable from Python.我刚刚开始研究 Python,我一直在尝试从 Python 运行外部可执行文件。

I have an executable for a program written in Fortran.我有一个用 Fortran 编写的程序的可执行文件。 Let's say the name for the executable is flow.exe.假设可执行文件的名称是 flow.exe。 And my executable is located in C:\\Documents and Settings\\flow_model .我的可执行文件位于C:\\Documents and Settings\\flow_model I tried both os.system and popen commands, but so far I couldn't make it work.我尝试了 os.system 和 popen 命令,但到目前为止我无法让它工作。 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?我怎样才能解决这个问题?

If using Python 2.7 or higher (especially prior to Python 3.5) you can use the following:如果使用 Python 2.7 或更高版本(尤其是在 Python 3.5 之前),您可以使用以下内容:

import subprocess
  • subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Runs the command described by args. subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)运行由 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. subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)运行带参数的命令。 Waits for command to complete.等待命令完成。 If the return code was zero then returns, otherwise raises CalledProcessError.如果返回码为零则返回,否则引发 CalledProcessError。 The CalledProcessError object will have the return code in the returncode attribute CalledProcessError 对象将在 returncode 属性中包含返回代码

Example: subprocess.check_call([r"C:\\pathToYourProgram\\yourProgram.exe", "your", "arguments", "comma", "separated"])示例: 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.在常规 Python 字符串中,\\U 字符组合表示扩展的 Unicode 代码点转义。

Here is the link to the documentation: http://docs.python.org/3.2/library/subprocess.html这是文档的链接: 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对于 Python 3.5+,您现在可以在许多情况下使用 run(): https : //docs.python.org/3.5/library/subprocess.html#subprocess.run

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...尝试os.chdir('C:/Documents\\ and\\ Settings/')后跟os.system的相对路径、 subprocess os.system方法或其他任何...

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 ?您不能创建一个无空白目录,将关键的.exe文件复制到那里,然后尝试一下吗? Are those havoc-wrecking space absolutely essential to your well-being...?那些破坏破坏的空间对你的幸福绝对重要吗......?

The simplest way is:最简单的方法是:

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

It works;它有效; I tried it.我试过了。

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.如果我是你,我会尝试在你的路径前面插入一个 'r',以表明它是一个原始字符串 - 然后你就不必使用正斜杠了。 For example:例如:

os.system(r"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.我敢打赌,您的外部程序 flow.exe 需要在其目录中执行,因为它访问存储在那里的一些外部文件。

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...) (注意单引号内的双引号...)

Use subprocess , it is a smaller module so it runs the .exe quicker.使用subprocess ,它是一个较小的模块,因此可以更快地运行.exe

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

By using os.system :通过使用os.system

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

Try尝试

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

If it were me, I'd put the EXE file in the root directory (C:) and see if it works like that.如果是我,我会将 EXE 文件放在根目录 (C:) 中,看看它是否像那样工作。 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):另外,尝试检查您的 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()

The code might not be entirely correct as I usually don't use Popen or Windows, but should give the idea.代码可能不完全正确,因为我通常不使用 Popen 或 Windows,但应该给出想法。 It might well be that the error message is on the error stream.错误消息很可能在错误流中。

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

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:在 python 2.6 中,使用引号括起来的字符串 " 和撇号 ' 标记。还将单 / 更改为双 //。您的工作示例将如下所示:

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:最后您可以使用字符串变量,例如直接从 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)

Is that trying to execute C:\\Documents with arguments of "and", "Settings/flow_model/flow.exe" ?是否试图用"and", "Settings/flow_model/flow.exe"参数执行C:\\Documents

Also, you might consider subprocess.call() .此外,您可能会考虑subprocess.call()

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.您可能还想在 cmd.exe 下运行该程序,以便您可以看到 flow.exe 的任何可能指示错误的输出。

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 .这里 test1.pdf rootimage 用于我的代码。

There are loads of different solutions, and the results will strongly depend on:有很多不同的解决方案,结果将在很大程度上取决于:

  • the OS you are using: Windows, Cygwin, Linux, MacOS您使用的操作系统: Windows、Cygwin、Linux、MacOS
  • the python version you are using: Python2 or Python3x您使用的 python 版本:Python2 或 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.因为我发现了一些声称只能在 Windows 中工作的东西,但实际上并没有,可能是因为我碰巧使用了 Cygwin,它比操作系统处理 Windows 路径的方式更聪明。 Other things only work in pure *nix based OS's or in Python2 or 3.其他东西只能在基于 *nix 的纯操作系统或 Python2 或 3 中工作。

Here are my findings:以下是我的发现:

  • Generally speaking, os.system() is the most forgiving method.一般来说, os.system()是最宽容的方法。
  • os.startfile() is the least forgiving. os.startfile()是最不宽容的。 (Windows only && if you're lucky) (仅限 Windows && 如果你幸运的话)
  • subprocess.Popen([...]) not recommended subprocess.Popen([...])推荐
  • subprocess.run(winView, shell=True) the recommended way! subprocess.run(winView, shell=True)推荐的方式!
  • Remembering that using subprocess for anything may pose a security risk .请记住,将subprocess用于任何事情都可能带来安全风险

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?问:为什么要在 Windows 中使用explorer器?

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.答:因为如果您只想查看某个新文件的结果,资源管理器将使用您为该文件类型设置的任何默认 Windows 程序自动打开该文件。 So no need to re-specify the default program to use.因此无需重新指定要使用的默认程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM