2

私はサブプロセスを使用して、unixddを使用して/dev/randomからランダムファイルを作成しています。ここで、ddのデータ出力をstdoutではなくファイルに書き込みたい場合。これが使用しているコードです、

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 = ['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()

これは、dd出力をファイルに出力せず、代わりにstdoutに出力します。これはddコマンドの特定の機能ですか?または、サブプロセスがどのように機能するかについて何かが欠けていますか?

4

2 に答える 2

3

ddstdout ではなく、stderr にデバッグ情報を出力します。

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()
于 2011-09-28T10:35:29.290 に答える
2

ファイルに何も書き込まれない理由は、stderr に書き込まれるためです。stderr をリダイレクトすると、結果が得られます。

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()

また、「時間を実行しています...」を書いた後、バッファをフラッシュします

于 2011-09-28T10:31:40.930 に答える