Python调用外部软件命令

时间:2015-01-09 14:30:47

标签: python

我有一个小问题。我有一个软件,它有一个带两个输入的命令。命令是:maf2hal inputfile outputfile.

我需要从Python脚本中调用此命令。 Python脚本询问用户输入文件的路径和输出文件的路径,并将它们存储在两个变量中。问题是当我调用命令maf2hal给出两个变量名作为参数时,我得到的错误是无法找到文件。

有解决方法吗?这是我的代码:

folderfound = "n" # looping condition
while (folderfound == "n"):
    path = raw_input("Enter path of file to convert (with the extension) > ")
    if not os.path.exists(path):
        print "\tERROR! file not found. Maybe file doesn't exist or no extension was provided. Try again!\n"
    else:
        print "\tFile found\n"
        folderfound = "y"

folderfound = "y" # looping condition
while (folderfound == "y"):
    outName = raw_input("Enter path of output file to be created > ")
    if os.path.exists(outName):
        print "\tERROR! File already exists \n\tEither delete the existing file or enter a new file name\n\n"
    else:
        print "Creating output file....\n"
        outputName = outName + ".maf"
        print "Done\n"
        folderfound = "n"
hal_input = outputName #inputfilename, 1st argument
hal_output = outName + ".hal" #outputfilename, 2nd argument

call("maf2hal hal_input hal_output", shell=True)

4 个答案:

答案 0 :(得分:6)

这是错误的:

call("maf2hal hal_input hal_output", shell=True)

应该是:

call(["maf2hal", hal_input, hal_output])

否则你会给予" hal_input"作为实际的文件名,而不是使用变量。

除非绝对必要,否则不应使用shell=True,在这种情况下,它不仅是不必要的,而且毫无意义。只需直接调用可执行文件,如上所述。

对于奖励积分,请使用check_call()而不是call(),因为前者实际上会检查返回值并在程序失败时引发异常。使用call()并非如此,因此错误可能会被忽视。

答案 1 :(得分:4)

有一些问题。您首次报告的错误是对shell的调用无法找到maf2hal程序 - 这听起来像路径问题。您需要验证该命令是否在正在创建的shell的路径中。

其次,您的call正在传递" hal_input"和" hal_output"。您需要首先构建该命令以传递这些变量的值;

cmd = "maf2hal {0} {1}".format(hal_input, hal_output)
call(cmd, shell=True)

答案 2 :(得分:3)

您的代码实际上是在尝试打开名为hal_input的文件,而不是使用具有相同名称的变量内容。看起来您正在使用subprocess模块执行,因此您只需将其更改为call(["maf2hal", hal_input, hal_output], shell=True)即可使用内容。

答案 3 :(得分:2)

代码末尾的

call("maf2hal hal_input hal_output", shell=True)

你实际上是在调用那个字符串,而不是可执行文件,然后是那些路径,你需要首先将你的字符串连接在一起,或者通过添加它们来使用.join
例如:

call("maf2hal " + hal_input + " " + hal_output", shell=True)

call("maf2hal ".join(hal_input, " ", hal_output), shell=True)