无法在 windows 上处理 python 子进程 stderr
Unable to process python subprocess stderr on windows
我正在尝试使用 Windows 下的 dd
进行简单的文件复制操作。代码很简单。只需使用子进程打开命令并读取 stderr
。然后处理 stderr
以显示操作进度。这是我试图完成的 sample/simple 代码:-
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
,那么应该在数字之前打印“>>>>>”。我在 Windows 7 上工作并使用 windows 版本的 dd.
感谢任何帮助。
正如在聊天中讨论的那样,数字来自 stderr。通过逐行打印每个字符的 ascii 索引,我们发现 readline() 返回的最后一行是 \t75,881,728 \r175,882,240 \r\n
。看起来嵌入在该字符串中间的 \r
(DD 输出)混淆了您的代码。
我正在尝试使用 Windows 下的 dd
进行简单的文件复制操作。代码很简单。只需使用子进程打开命令并读取 stderr
。然后处理 stderr
以显示操作进度。这是我试图完成的 sample/simple 代码:-
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
,那么应该在数字之前打印“>>>>>”。我在 Windows 7 上工作并使用 windows 版本的 dd.
感谢任何帮助。
正如在聊天中讨论的那样,数字来自 stderr。通过逐行打印每个字符的 ascii 索引,我们发现 readline() 返回的最后一行是 \t75,881,728 \r175,882,240 \r\n
。看起来嵌入在该字符串中间的 \r
(DD 输出)混淆了您的代码。