Subprocess.call或Subprocess.Popen不能使用路径(Linux/Windows)中的可执行文件

2024-10-02 16:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,需要在Linux和Windows上运行,并使用路径中存在的可执行文件(带参数)。(假设)

目前,我在windows中使用Subprocess.Call和Subprocess.Popen运行可执行文件时遇到问题。

对于这样的代码,在windows 8中

def makeBlastDB(inFile, inputType, dbType, title, outDir):
    strProg = 'makeblastdb'
    strInput = '-in ' + inFile
    strInputType = '-input_type ' + inputType
    strDBType = '-dbtype ' + dbType
    strTitle = '-title ' + title
    strOut = '-out ' + os.path.join(os.sep, outDir, title)
    cmd = [strProg, strInput, strInputType, strDBType, strTitle, strOut]
    result = Popen(cmd, shell=True)

我在控制台中收到错误消息

'makeblastdb' is not recognized as an internal or external command,
operable program or batch file.

即使我可以使用cmd.exe运行相同的命令 我得到了与shell=False相同的响应。

如果可执行文件位于PATH环境变量中,我可以如何运行该命令?谢谢


Tags: cmd可执行文件titlewindowsinfilesubprocesspopenoutdir
3条回答

通过传递带env关键字参数的映射,可以控制派生子流程中可用的环境变量。E、 g

proc = subprocess.Popen(args, env={'PATH': '/some/path'})

或者从系统环境变量继承PATH,而不必从系统环境中删除其他内容:

proc = subprocess.Popen(args, env={'PATH': os.getenv('PATH')})

不过,仅仅使用绝对路径可能更容易/更简单。

好吧,这就是我的工作方法。

env = os.environ
proc = subprocess.Popen(args, env=env)

我自己一直在挣扎,直到找到this python bug report

“如果将目录添加到Windows上的路径中,使目录用引号括起来,则子进程在其中找不到可执行文件。”因为Windows不需要引号,删除引号可以解决我的问题(在2.7中)。

相关问题 更多 >