Skip to main content
 首页 » 编程设计

Python调用外部软件命令

2025年05月04日14虾米姐

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

我需要从 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) 

请您参考如下方法:

这是错误的:

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

应该是:

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

否则,您会将“hal_input”作为实际文件名,而不是使用变量。

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

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