1

How can I pass multiple arguments within my subprocess call in python while running my shell script?

import subprocess

subprocess.check_call('./test_bash.sh '+arg1 +arg2, shell=True)

This prints out the arg1 and arg2 concatenated as one argument. I would need to pass 3 arguments to my shell script.

1
  • can you try check_call(['./test_bash.sh',arg1,arg2],shell=True) ? or drop shell=True and add ["sh","-c", before your bash script? Commented Oct 16, 2018 at 18:21

1 Answer 1

3

of course it concatenates because you're not inserting a space between them. Quickfix would be (with format, and can fail if some arguments contain spaces)

 subprocess.check_call('./test_bash.sh {} {}'.format(arg1,arg2), shell=True)

can you try (more robust, no need to quote spaces, automatic command line generation):

check_call(['./test_bash.sh',arg1,arg2],shell=True)`

(not sure it works on all systems because of shell=True and argument list used together)

or drop shell=True and call the shell explicitly (may fail because shebang is not considered, unlike with shell=True, but it's worth giving up shell=True, liable to code injection among other issues):

check_call(['sh','-c','./test_bash.sh',arg1,arg2])
Sign up to request clarification or add additional context in comments.

3 Comments

awesome, that did it.
how can I pass the same multiple arguments that are stored as a list such as arg1={}, arg2={} and I'd like the script to use arg1[0], arg2[0] first and then increment to next arg1[1], arg2[1].
just create a list that you'll add to the "first arguments" list. but you'll need to zip & flatten: ["sh','-c","test_bash_whatever] + list(itertools.chain.from_iterable(zip(arg1,arg2))) something like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.