2012-01-11 61 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]'})