如何在“ subprocess.run”函数中使用多个变量?

时间:2019-08-29 08:28:25

标签: python python-3.x variables subprocess

我有一个小的python3代码。 我想在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

如何在命令中使用script_home变量?

我已经尝试过:

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

2 个答案:

答案 0 :(得分:2)

字符串说明符在您的实现中不正确。

尝试以下行:

subprocess.run("{script_home}/script.sh {script_args}".format(script_home=script_home, script_args=script_argument), shell=True, capture_output=True).stdout

答案 1 :(得分:0)

您想将参数作为列表传递。

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

请注意,shell=True对于此更改不再是必需的或有用的(或正确的)。

另请参阅Actual meaning of 'shell=True' in subprocess

(我想您忘记了前面的return。没有这个,您的函数只会返回None。)

在这里产生第一个字符串的方法有很多。

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+
相关问题