Skip to main content
 首页 » 编程设计

Python之使用重定向构建 subprocess.popen

2025年05月04日11hnrainll

我想用 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 选项,因此我的问题是如何实现它。

问候 斯特凡

请您参考如下方法:

不可能,除非您调用的程序本身实现了重定向(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'})