Python调用外部软件命令

2024-04-25 09:51:07 发布

您现在位置: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)

Tags: 文件path命令路径脚本inputoutputexists
3条回答

您的代码实际上是试图打开一个名为hal_input的文件,而不是使用同名变量的内容。看起来您正在使用subprocess模块来执行,所以您可以将其更改为call(["maf2hal", hal_input, hal_output], shell=True)来使用内容。你知道吗

有一些问题。您报告的第一个错误是对shell的调用找不到maf2hal程序—听起来像是路径问题。您需要验证命令是否位于正在创建的shell的路径中。你知道吗

第二,您的call正在传递单词“hal\u input”和“hal\u output”。您需要首先构建该命令来传递这些变量的值

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

这是错误的:

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

应该是:

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

否则,您将使用“hal\u input”作为实际文件名,而不是使用变量。你知道吗

除非绝对必要,否则不应该使用shell=True,在这种情况下,它不仅没有必要,而且毫无意义地低效。只需直接调用可执行文件,如上所述。你知道吗

对于加分,请使用check_call()而不是call(),因为前者实际上会检查返回值,如果程序失败则会引发异常。使用call()不会,因此错误可能会被忽略。你知道吗

相关问题 更多 >