Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python subprocess run works with single string but not list of strings

I'm trying to initiate a command-line program with command-line options from my Python script using the run method from the subprocess module.

My command is defined as a list of strings specifying the program and options as follows (where pheno_fp and construction_fp are strings representing file paths in my system and exe is a string representing the file path to the program I'm running):

    step1_cmd = [exe, 
                "--step 1",
                "--p " + pheno_fp,
                "--b 1000",
                "--o " + construction_fp + "dpw_leaveout"]

Not working - When I try the following, the program I want to run is started but the command I've specified is interpreted incorrectly because the program exits with an error saying "specify output file path with --o flag":

    test1 = subprocess.run(step1_cmd)

Working - When I try the following, the program executes correctly, meaning all arguments are interpreted as intended:

    test1 = subprocess.run(" ".join(step1_cmd), shell=True)

If I understood the documentation correctly, the former approach is the recommended usage but I can't understand why it's not working. I'm pretty sure it's formatted the same as the examples in the documentation so I'm a bit stumped. Any ideas?

like image 494
jremedy Avatar asked Nov 16 '25 08:11

jremedy


1 Answers

Split each parameter with its value, like so:

step1_cmd = [exe, 
             "--step",
             "1",
             "--p",
             str(pheno_fp),  # if it isn't a string already
             "--b",
             "1000",
             "--o",
             str(construction_fp) + "dpw_leaveout"
]

Because when passing a list of parameters, each part is separated with a space, both options and their values

like image 68
Zionsof Avatar answered Nov 18 '25 02:11

Zionsof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!