开发者

python subprocess dd and stdout

I am using subprocess to create a random file from /dev/random using unix dd. Now, if i want the data output of dd to be written to a file instead of stdout. so here's the code am using,

import subprocess
out_fd = open(开发者_StackOverflow社区'test_file','w')
def os_system_dd():
   global out_fd
   out_fd.write("executing the time dd command\n")
   cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random', 'bs=1M' ,'count=5']
   a = subprocess.Popen(cmd_list,stdout=out_fd)
   a.wait()

if __name__ == '__main__':
   os_system_dd()

This doesn't print the dd output to the file and instead prints it in the stdout. Is this a specific functionality of dd command? Or am i missing some thing about how subprocess works?


dd outputs its debugging information on stderr, not stdout:

import subprocess
out_fd = open('test_file','w')
def os_system_dd():
   out_fd.write("executing the time dd command\n")
   cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random',
                           'bs=1M' ,'count=5']
   a = subprocess.Popen(cmd_list,stderr=out_fd) # notice stderr
   a.communicate()

if __name__ == '__main__':
   os_system_dd()


The reason nothing gets written in the file is because its written to stderr. Redirect stderr and you will get the result.

import subprocess
out_fd = open('test_file','w')
def os_system_dd():
   global out_fd
   out_fd.write("executing the time dd command\n")
   cmd_list = ['date'] #Your list
   a = subprocess.Popen(cmd_list,stdout=out_fd, stderr=out_fd)
   a.wait()

if __name__ == '__main__':
   os_system_dd()

Also, flush the buffer after writing "executing the time..."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜