user797963
user797963

Reputation: 3017

Python subprocess, how to pass a list?

I'm trying to run a cmd through subprocess and pass it a list of arguments, one argument being a list that contains additional arguments. How can I pass this to subprocess?

Example:

my_list = ['arg1', 'arg2', 'arg3']
subprocess.run(["./some.sh", "--flag", "some_arg", "--another_flag", my_list ])

Is this possible?

Upvotes: 5

Views: 2153

Answers (1)

trent
trent

Reputation: 27895

Either use * to unpack the list:

subprocess.run(["./some.sh", "--flag", "some_arg", "--another_flag", *my_list])

Or concatenate the two lists together with +:

subprocess.run(["./some.sh", "--flag", "some_arg", "--another_flag"] + my_list)

+ will only work on lists (not generators, for example).

The "unpacking" behavior of * is documented in the official tutorial here, although it only addresses using it in function calls, not constructing new lists. It works regardless.

Upvotes: 9

Related Questions