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

我正在编写一个需要在Linux和Windows上运行的程序,并使用路径中存在的可执行文件(带参数). (假定)目前,我在使用Subprocess.Call和Subprocess.Popen在Windows中运行可执行文件时遇到问题.对于像这样的代码,在Window...

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

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

对于像这样的代码,在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环境变量中,我是如何运行命令的任何想法?谢谢

解决方法:

您可以通过使用env关键字参数传递映射来控制生成的子流程中可用的环境变量.例如.

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

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

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

但是,使用绝对路径可能更容易/更简单.

本文标题为:python – Subprocess.call或Subprocess.Popen不能使用PATH中的可执行文件(Linux / Windows)

基础教程推荐