首页 > python > 通过Python的子进程模块使用dd命令

通过Python的子进程模块使用dd命令 (Using dd command through Python's subprocess module)

问题

通过Python的子进程模块,我试图捕获dd命令的输出。这是代码片段:

r = subprocess.check_output(['dd', 'if=/Users/jason/Desktop/test.cpp', 'of=/Users/jason/Desktop/test.out'])

但是,当我做类似的事情

print r

我得到一个空白。

有没有办法将dd命令的输出捕获到某种数据结构中,以便我以后可以访问它?

我本质上想要的是将下面的输出存储到列表中,以便稍后我可以对字节数进行操作。

1+0 records in
1+0 records out
4096 bytes transferred in 0.000409 secs (10011579 bytes/sec)

解决方法

dd不会向stdout输出任何内容,因此您的结果是正确的。但是,它输出到stderr。传入stderr=subprocess.STDOUT以获取stderr输出:

>>> o = subprocess.check_output(
    ['dd', 'if=/etc/resolv.conf', 'of=r'], stderr=subprocess.STDOUT)
>>> print(o)
b'0+1 records in\n0+1 records out\n110 bytes (110 B) copied, 0.00019216 s, 572 kB/s\n'

问题

Through Python's subprocess module, I'm trying to capture the output of the dd command. Here's the snippet of code:

r = subprocess.check_output(['dd', 'if=/Users/jason/Desktop/test.cpp', 'of=/Users/jason/Desktop/test.out'])

however, when I do something like

print r

I get a blank line.

Is there a way to capture the output of the dd command into some sort of data structure so that I can access it later?

What I essentially want is to have the output below be stored into a list so that I can later do operations on say the number of bytes.

1+0 records in
1+0 records out
4096 bytes transferred in 0.000409 secs (10011579 bytes/sec)

解决方法

dd does not output anything to stdout, so your result is correct. However, it does output to stderr. Pass in stderr=subprocess.STDOUT to get the stderr output:

>>> o = subprocess.check_output(
    ['dd', 'if=/etc/resolv.conf', 'of=r'], stderr=subprocess.STDOUT)
>>> print(o)
b'0+1 records in\n0+1 records out\n110 bytes (110 B) copied, 0.00019216 s, 572 kB/s\n'
相似信息