在Python中使用管道运行外部程序并传递参数
我试过这样做,但当我尝试打印这些参数时,它没有返回任何值。
我把我的代码放在下面:
这是一个运行外部 Python 程序(script2)的脚本(script1)
#(...)
proc = subprocess.Popen(['export PYTHONPATH=~/:$PYTHONPATH;' +
'export environment=/path/to/environment/;' +
'python /path/to/my/program/myProgram.py',
'%(date)s' %{'date':date}, '%(time)s' %{'time':time}],
stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
#(...)
这是被 script1 运行的 script2
#(...)
print sys.argv[0] #prints the name of the command
print sys.argv[1] #it suppose to print the value of the first argument, but it doesn't
print sys.argv[2] #it suppose to print the value of the second argument, but it doesn't
#(...)
3 个回答
1
- 使用
Popen
的env
参数来传递环境变量: - 除非必要,不要使用
shell=True
。这样做可能会带来 安全风险(见警告)。
test.py:
import subprocess
import shlex
import datetime as dt
now=dt.datetime.now()
date=now.date()
time=now.strftime('%X')
proc = subprocess.Popen(shlex.split(
'python /tmp/test2.py %(date)s %(time)s'%{'date':date,
'time':time}),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env={'PYTHONPATH':'~/:$PYTHONPATH',
'environment':'/path/to/environment/'})
out,err=proc.communicate()
print(out)
print(err)
test2.py:
import sys
import os
print(os.environ['PYTHONPATH'])
print(os.environ['environment'])
for i in range(3):
print(sys.argv[i])
结果是
~/:$PYTHONPATH
/path/to/environment/
/tmp/test2.py
2011-08-09
17:50:04
1
文档上说,当你设置shell=True时,任何额外的参数都会被当作是传给shell的,而不是传给你要执行的命令。要让它正常工作,只需把shell设置为False。我不明白为什么你需要把它设置为True。
补充一下:我看到你想用shell来设置环境变量。你可以使用env参数来设置环境变量,而不是通过shell。
1
试试这个版本的脚本 1:
proc = subprocess.Popen('python /path/to/my/program/myProgram.py %s %s' % (date, time),
stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True,
env = {'PYTHONPATH': '~/:$PYTHONPATH',
'environment': '/path/to/environment/'})
如果这个版本不管用,应该能更容易帮你找到问题所在;不过我觉得它应该是可以的。