如何在“中使用多个变量”子流程运行“功能?

2024-04-25 17:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小Python3代码。 我想用多个变量子流程运行你知道吗

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\u 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

Tags: run代码importtruehomeoutputshstdout
2条回答

字符串说明符在实现中不正确。你知道吗

请尝试以下行:

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

您希望将参数作为列表传递。你知道吗

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+

相关问题 更多 >