mk1
mk1

Reputation: 141

Subprocess File Operations in Python

I have a command line program which can be run through the following subprocess.

subprocess.call([CMD.bat, '-infile', infile1.tif, infile2.tif, '-outfile', outfile.tif])

When input files are a few, there is no problem with the above code.

However, when the input files are many, it becomes difficult to input them all. So, I wanted to use glob.glob to input all files.

files = glob.glob("D:\\*.tif")

files = ",".join(files)

subprocess.call([CMD.bat, '-infile', files, '-outfile', outfile.tif])

Unluckily, this code does not run at all. How to solve this problem?

Any ideas, please help.

Upvotes: 3

Views: 66

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11922

you can't put that files in as a single argument, you need to unpack it:

files = glob.glob("D:\\*.tif")
subprocess.call(['cmd.bat', '-infile', *files, '-outfile', 'outfile.tif'])

Notice the * used for unpacking arguments. For more info on unpacking, see here and here

No need to join the arguments first, that just creates a long string (that is still one single argument)

An example:

files = ['1.tif', '2.tif']
cmd = ['cmd.bat', '-infile', *files, '-outfile', 'outfile.tif']
print(cmd) # ['cmd.bat', '-infile', '1.tif', '2.tif', '-outfile', 'outfile.tif']

Upvotes: 1

Related Questions