2

i hava a small python3 code. I want to use multiple variables in subprocess.run

import subprocess

scripts_home='/usr/local/bin'
script_argument = 'argument'

def function():
    subprocess.run("script_home/script.sh %s" % script_argument, shell=True, capture_output=True).stdout

how can i use script_home variable in command ?

I will already tried:

subprocess.run("%s/script.sh %s" % script_home % script_argument, shell=True, capture_output=True).stdout
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
1
  • 1
    '%s some string %s' % (s1, s2). But use f-strings or .format()! Commented Aug 29, 2019 at 8:35

2 Answers 2

2

The string specifiers are not correct in your implementation.

Try the following line:

subprocess.run("{script_home}/script.sh {script_args}".format(script_home=script_home, script_args=script_argument), shell=True, capture_output=True).stdout
Sign up to request clarification or add additional context in comments.

1 Comment

Thank for answer, its worked !
1

You want to pass in the arguments as a list instead.

import subprocess

scripts_home='/usr/local/bin'
script_argument = 'argument'

def function():
    return subprocess.run(
        [f"{script_home}/script.sh", script_argument],
        capture_output=True).stdout

Notice how shell=True is no longer necessary or useful (or correct) with this change.

See also Actual meaning of 'shell=True' in subprocess

(And I guess you forgot the return in front. Without that, your function simply returns None.)

There are many different ways to produce the first string here.

script_home + '/script.sh'     # string addition is pretty inefficient and ugly
'%s/script.sh' % script_home   # legacy Python 2.x, fugly %
'{0}/script.sh'.format(script_home)
f'{script_home}/script.sh'     # f-string, Python 3.6+

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.