我试过了,但是当我尝试打印这些参数时,它不返回任何值。 我在下面提交我的代码:
运行外部python程序(script2)的脚本
#(...)
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正在运行的脚本2
#(...)
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
#(...)
答案 0 :(得分: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/'})
如果问题不起作用,应该更容易找到问题;但我认为会的。
答案 1 :(得分:1)
Docs说当指定shell = True时,任何其他args都被视为shell的args,而不是命令。要使其工作,只需将shell设置为False。我不明白为什么你需要它是真的。
编辑:我看到你想用shell来设置环境变量。请使用env参数来设置环境变量。
答案 2 :(得分:1)
Popen
的{{1}}参数传递环境变量:env
。它可以是security
risk (see Warning)。test.py:
shell=True
test2.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)
产量
import sys
import os
print(os.environ['PYTHONPATH'])
print(os.environ['environment'])
for i in range(3):
print(sys.argv[i])