gpt4 book ai didi

python - 尽管传递了参数列表,为什么将变量传递给 subprocess.Popen 不起作用?

转载 作者:太空狗 更新时间:2023-10-29 20:12:36 26 4
gpt4 key购买 nike

我有一个脚本,它通过 subprocess.Popen 调用另一个 Python 脚本。但是因为我有参数存储在变量中

servers[server]['address']
servers[server]['port']
servers[server]['pass']

我无法执行命令

p = subprocess.Popen(
["python mytool.py -a ", servers[server]['address'], "-x", servers[server]['port'], "-p", servers[server]['pass'], "some additional command"],
shell=True,
stdout=subprocess.PIPE
)

最佳答案

删除 shell=TrueThe arguments to Popen() are treated differently on Unix if shell=True :

import sys
from subprocess import Popen, PIPE

# populate list of arguments
args = ["mytool.py"]
for opt, optname in zip("-a -x -p".split(), "address port pass".split()):
args.extend([opt, str(servers[server][optname])])
args.extend("some additional command".split())

# run script
p = Popen([sys.executable or 'python'] + args, stdout=PIPE)
# use p.stdout here...
p.stdout.close()
p.wait()

请注意,为具有外部输入的命令传递 shell=True 是一种安全隐患,如警告 in the docs 所述.

关于python - 尽管传递了参数列表,为什么将变量传递给 subprocess.Popen 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20140137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com