无法在Windows上处理python子进程stderr

时间:2015-03-10 15:42:28

标签: python windows subprocess stderr

我正在尝试使用Windows下的dd进行简单的文件复制操作。代码很简单。只需使用子流程打开命令并阅读stderr。然后处理stderr以显示操作的进度。这是我试图完成的示例/简单代码: -

import time
import signal
import subprocess
import os

def dd_win():
    windd = "dd.exe"
    in_file = os.path.join("E:", "test-in.iso")
    out_file = os.path.join("E:", "test-out.iso")
    parameter1 = "if=" + in_file
    parameter2 = "of=" + out_file
    parameter3 = "bs=1M"
    parameter4 = "--progress"
    command = [windd, parameter1, parameter2, parameter4]
    print command
    dd_process = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, bufsize=0)

    while dd_process.poll() is None:
        time.sleep(.1)
        line = dd_process.stderr.readline()
        if not line:
            break
        print ">>>>>", line.strip()
    if dd_process.poll() is not None:
        print "Process finished."

dd_win()

这是我作为输出得到的。我可以看到stderr但无法处理传输字节以转换为兆字节: -

C:\Users\user\Documents>python test.py
['dd.exe', 'if=E:test-in.iso', 'of=E:test-out.iso', '--progress']
>>>>> rawwrite dd for windows version 0.6beta3.
>>>>> Written by John Newbigin <jn@it.swin.edu.au>
>>>>> This program is covered by terms of the GPL Version 2.
>>>>>
175,882,240  # <--- Problem output line. Unable to assign to other variable for progress calculation
Process finished.

我实际上不知道数字的来源。它来自stderr还是缓冲区?如果它来自stderr,那么“&gt;&gt;&gt;&gt;&gt;”应该在数字之前打印。我在Windows 7上工作并使用Windows版本的dd。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

正如聊天中所讨论的那样,数字来自stderr。通过打印每个字符的ascii-index,我们发现readline()返回的最后一行是\t75,881,728 \r175,882,240 \r\n。看起来嵌入在此字符串中间的\r(DD输出)会使您的代码混乱。