python – 将变量传递给Subprocess.Popen

我有一个脚本,它通过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)

解决方法:

Drop shell = True. The 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子进程运行linux grep命令


下一篇:Python subprocess.Popen()错误(没有这样的文件或目录)