subprocess.Popen()IO重定向

Pet*_*rts 11 python popen

尝试将子进程的输出重定向到文件.

server.py:

while 1:
    print "Count " + str(count)
    sys.stdout.flush()
    count = count + 1
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

Laucher:

cmd = './server.py >temp.txt'
args = shlex.split(cmd)
server = subprocess.Popen( args )
Run Code Online (Sandbox Code Playgroud)

输出显示在屏幕上,temp.txt保持为空.我究竟做错了什么?

作为背景我试图捕获已经编写的程序的输出.

我不能用:

server = subprocess.Popen(
                [exe_name],
                stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

因为该程序可能不会刷新.相反,我打算通过fifo重定向输出.如果我手动启动server.py,这很好,但显然不是因为我Popen()导致重定向不起作用. ps -aux显示server.py正确启动.

jco*_*ado 10

另外,您可以将stdout参数与文件对象一起使用:

with open('temp.txt', 'w') as output:
    server = subprocess.Popen('./server.py', stdout=output)
    server.communicate()
Run Code Online (Sandbox Code Playgroud)

文档中所述:

stdin,stdout和stderr分别指定执行程序的标准输入,标准输出和标准错误文件句柄.有效值为PIPE,现有文件描述符(正整数),现有文件对象和无.

  • 这里不需要调用`.communicate()`.`subprocess.check_call('command',stdout = file)`有效. (2认同)

Ada*_*mKG 7

使用">"输出重定向是shell的一项功能 - 默认情况下subprocess.Popen不会实例化一个.这应该工作:

server = subprocess.Popen(args, shell=True)
Run Code Online (Sandbox Code Playgroud)

  • 除非有必要(不是必需的),否则不建议使用“ shell = True” (2认同)