【问题标题】:Running external program using pipes and passing arguments in python使用管道运行外部程序并在 python 中传递参数
【发布时间】:2011-08-09 21:38:17
【问题描述】:

我试过了,但是当我尝试打印这些参数时,它没有返回任何值。 我在下面提交我的代码:

运行外部python程序的script1 (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 正在运行的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
#(...)

【问题讨论】:

  • 你试过使用shlex.split吗?
  • 不,不是真的,这会有帮助吗?

标签: python subprocess pipe popen


【解决方案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/'})

如果它不起作用,它应该更容易找到您的问题;但我认为会的。

【讨论】:

  • 不幸的是它不起作用,实际上它甚至不会打印 script2 的输出
  • 我编辑后你试过了吗?你试过没有=PIPE 参数吗?
  • 我只是尝试不使用 =PIPE 参数,但它会引发错误,因为它无法导入库,所以它可能没有正确设置信封
【解决方案2】:

Docs 表示当指定 shell=True 时,任何额外的 args 都被视为 shell 的 args,而不是命令。要使其工作,只需将 shell 设置为 False。我不明白你为什么需要它是真实的。

edit:我看到你想使用 shell 来设置环境变量。使用 env 参数来设置环境变量。

【讨论】:

  • 其他两个答案解决了重要问题,但这是主要问题。
  • 我需要 shell 是真的,因为我需要先导出库
  • 就像我说的。使用 env 参数来设置环境。如果您需要从当前环境中复制任何环境变量,请在 os 模块中复制 environ
【解决方案3】:
  1. 使用Popenenv参数传递环境变量:
  2. 除非必须,否则不要使用shell=True。可以是security risk (see Warning)

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

【讨论】:

  • 如果print sys.argv[0] 工作正常,那么管道不是他的问题。 env 参数调用良好。
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 2019-12-19
  • 2012-04-15
  • 2015-10-31
  • 1970-01-01
相关资源
最近更新 更多