2012-01-11 62 views
1

我想用popen创建一个子进程。 特殊需求是在命令中使用shell方向。Python - 用重定向构造一个subprocess.popen

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

我不想使用shell = True选项,因此在这里我的问题给你,如何实现它。

问候 斯特凡

回答

9

不可能的,除非该程序正在呼叫重定向工具本身(这cat没有)。要使用shell功能,您必须通过shell=True或明确调用shell。

OTOH,如果你只是想从textfile阅读,你可以把它作为子进程的stdin

subprocess.Popen(args, 
       stdin=open("textfile"), 
       stdout=subprocess.PIPE, 
       stderr=subprocess.PIPE, 
       env={'LANG':'[email protected]'})