【问题标题】:Python - Constructing a subprocess.popen with redirectionPython - 构造一个带有重定向的 subprocess.popen
【发布时间】:2012-02-07 21:42:01
【问题描述】:

我想用 popen 创建一个子进程。 特殊需求是在命令中使用shell方向。

args = [
    '/bin/cat',
    '<',
    'textfile',
    ]
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           env={'LANG':'de_DE@euro'})
processpid = process.pid
output = process.communicate()

我不想使用 shell=True 选项,因此我的问题是,如何实现它。

问候 斯蒂芬

【问题讨论】:

    标签: python arguments redirect subprocess


    【解决方案1】:

    除非您调用的程序本身实现了重定向(cat 没有),否则这是不可能的。要使用 shell 功能,您必须传递 shell=True 或显式调用 shell。

    OTOH,如果你只是想从textfile 中读取,你可以将它作为子进程的stdin 传递:

    subprocess.Popen(args,
                     stdin=open("textfile"),
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     env={'LANG':'de_DE@euro'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2014-06-11
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多