使用管道运行外部程序并在 python 中传递参数
我尝试过,但是当我尝试打印这些参数时,它不返回任何值。 我提交下面的代码:
script1 运行外部 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)
#(...)
script2 正在由 script1 运行
#(...)
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
#(...)
I tried that, but when I try to print these arguments it returns no values.
I submit my code below:
script1 that runs external python program (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)
#(...)
script2 that is being run by the script1
#(...)
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
#(...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这个版本的脚本 1:
如果它不起作用,它应该可以更容易地找到您的问题;但我认为会的。
Try this version of script 1:
It should make it easier to find your problem if it doesn't work; but I think it will.
Docs 说,当指定 shell=True 时,任何其他参数都被视为 shell 的参数,不听命令。要使其工作,只需将 shell 设置为 False 即可。我不明白为什么你需要它是真的。
编辑:我看到你想使用 shell 来设置环境变量。使用 env 参数来设置环境变量。
Docs say that when specifying shell=True any additional args are treated as args to the shell, not to the command. To make it work, just set shell to False. I don't see why you need it to be True.
edit: I see you want to use shell to set environment variables. Use the env argument to set the environment variables instead.
Popen
的env
参数传递环境变量:shell=True
。它可以是安全性风险(请参阅警告)。
test.py:
test2.py:
产量
Popen
'senv
parameter to pass environment variables:shell=True
unless you have to. It can be a securityrisk (see Warning).
test.py:
test2.py:
yields