Python:如何使用其他文件中的参数执行外部程序?

时间:2012-06-01 20:13:31

标签: python subprocess external-process

我正在尝试编写一个python脚本来执行一个命令行程序,其中包含从另一个文件导入的参数。该程序的命令行界面如下: ./executable.x参数(a)参数(b)参数(c)......

我的代码是:

#program to pass parameters to softsusy
import subprocess
#open parameter file
f = open('test.dat', 'r')
program = './executable.x'
#select line from file and pass to program
for line in f:
    subprocess.Popen([program, line])

test.dat文件如下所示:

param(a) param(b) param(c)...

脚本调用程序,但它不传递变量。我错过了什么?

2 个答案:

答案 0 :(得分:1)

你想:

line=f.readline()
subprocess.Popen([program]+line.split())

您目前拥有的内容会将整行作为单个参数传递给程序。 (比如在program "arg1 arg2 arg3"

中在shell中调用它

当然,如果你想为文件中的每一行调用一次程序:

with open('test.dat','r') as f:
for line in f:
    #you could use shlex.split(line) as well -- that will preserve quotes, etc.
    subprocess.Popen([program]+line.split())

答案 1 :(得分:0)

首先,对于你的情况,使用subprocess.call()而不是subprocess.popen()

至于“没有被传递的参数”,你的剧本中没有任何明显的错误。尝试将整个事物连接成长字符串并将字符串赋予.call()而不是list。

subprocess.call( program + " " + " ".join(line) )

您确定line包含您希望其包含的数据吗?

要确保(如果源文件很短),请尝试明确地将文件转换为列表,并确保“line”中有数据:

for line in file.readlines():
    if len(line.trim().split(" ")) < 2:
        raise Exception("Where are my params?")
相关问题