我正在尝试编写一个 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)...
脚本调用程序,但不传递变量。我错过了什么?
最佳答案
你想要:
line=f.readline()
subprocess.Popen([program]+line.split())
您当前拥有的内容会将整行作为单个参数传递给程序。 (就像在 shell 中将其调用为 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())
关于Python:如何使用另一个文件中的参数执行外部程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10856759/