2012-06-01 42 views
1

我想写一个python脚本来执行一个命令行程序,并从另一个文件导入参数。本方案的命令行接口的工作原理如下: ./executable.x参数的(a)参数(b)中的参数(c)中...Python:如何使用其他文件的参数执行外部程序?

我的代码是:

#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]) 

测试。 dat文件如下所示:

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

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

回答

1

你想:

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

你现在有什么会通过整条生产线的程序作为一个参数。 (就像调用它的外壳为program "arg1 arg2 arg3"

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

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()) 
+0

那完美。谢谢您的帮助。 – user1431534

+0

我会如何将子流程的输出保存到文件中? – user1431534

+0

创建一个文件对象('outputfile = open('output.txt','w')')并使用'stdout'关键字将它传递给Popen:'('subprocess.Popen(arglist,stdout = outputfile)') – mgilson

0

首先,你的情况下,使用subprocess.call ()not subprocess.popen()

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

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

您确定line包含您期望它包含的数据吗?

要确保,(如果源文件是短暂的)尝试打开文件到列表中明确,并确保有数据在“行”:

for line in file.readlines(): 
    if len(line.trim().split(" ")) < 2: 
     raise Exception("Where are my params?") 
+0

行包含文件的一行。如果该行是“hello”,那么你的解决方案会将“h l l o o”作为参数传递。而且使用'Popen'没有什么问题 - 无论如何,使用'call'只是围绕'Popen'的一个包装。 – mgilson

+0

此外,'line.trim()'会引发AttributeError,因为字符串没有修剪方法。 (至少不在python 2.6中)。 'line.split()'应该工作得很好。 – mgilson

相关问题