Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 347
mk1 Avatar asked Dec 03 '25 00:12

mk1


1 Answers

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']
like image 99
Ofer Sadan Avatar answered Dec 04 '25 15:12

Ofer Sadan