How to run application with parameters in Python?

2019-03-25 11:12发布

问题:

I need to run an application (binary file) and pass arguments using a Python code. Some arguments represent strings got during Python file processing.

for i in range ( len ( files ) ) :
    subprocess.call(["test.exe", files[i]]) //How to pass the argument files[i]

Thanks...

Updated question:


Maybe I do not understand passing arguments in Python 3. A code without parameters runs OK

args = ['test. exe']
subprocess.call(args)

However the code with parameter causes an error:

args = ['test. exe']
subprocess.call(args, '-f')  //Error

Error:

Error File "C:\Python32\lib\subprocess.py", line 467, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python32\lib\subprocess.py", line 652, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

回答1:

args = ['test. exe']
subprocess.call(args, '-f')  //Error

should be:

args = ['test.exe', '-f']
subprocess.call(args) 

The command line argument should all be inside a single list for the first parameter of subprocess.call. The second argument to call is bufsize, which is supposed to be an integer (hence why you get the error you do)



回答2:

With regard to your updated question: The arguments for your subprocess are not passed as individual parameters to call(); rather, they're passed as a single list of strings, like so:

args = ["test.exe", "first_argument", "second_argument"]

Original response: The code as you have it will create a separate process for each element in files. If that's what you want, your code should work. If you want to call the program with all of the files simultaneously, you'll want to concatenate your list:

args = ["test.exe"] + files
subprocess.call(args)


回答3:

All you need to do is include it in the argument list, instead of as a separate argument:

subprocess.call(["test.exe", files[i]])