Вопрос

I am trying to write a python script to execute a command line program with parameters imported from another file. The command line interface for the program works as follows: ./executable.x parameter(a) parameter(b) parameter(c) ...

My code is:

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

The test.dat file looks like this:

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

The script calls the program however it does not pass the variables. What am I missing?

Это было полезно?

Решение

You want:

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

What you currently have will pass the entire line to the program as a single argument. (like calling it in the shell as program "arg1 arg2 arg3"

Of course, if you want to call the program once for each line in the file:

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

Другие советы

To start with, for you case, use subprocess.call() not subprocess.popen()

As for the "params not being passed" there is nothing obviously wrong in your script. Try concatenating the whole thing into long string and giving the string to .call() instead of list.

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

Are you sure that line contains the data you expect it to contain?

To make sure, (if source file is short) try turning the file into list explicitly and making sure there is data in "line":

for line in file.readlines():
    if len(line.trim().split(" ")) < 2:
        raise Exception("Where are my params?")
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top