Python - 使用重定向构造subprocess.popen

Ste*_*anS 1 python redirect arguments subprocess

我想用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()
Run Code Online (Sandbox Code Playgroud)

我不想使用shell = True选项,因此我在这里向您提出问题,如何实现它.

关心斯特凡

Fre*_*Foo 9

除非您正在调用的程序本身实现重定向(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'})
Run Code Online (Sandbox Code Playgroud)