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
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

2 Answers2

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
milanbalazs
  • 4,811
  • 4
  • 23
  • 45
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+
tripleee
  • 175,061
  • 34
  • 275
  • 318