如何将subprocess.call()输出推送到终端和文件?

时间:2014-09-21 19:35:25

标签: python linux subprocess dd

我有subprocess.call(["ddrescue", in_file_path, out_file_path], stdout=drclog)。我想在终端运行时显示ddrescue并将输出写入文件drclog。我尝试过使用subprocess.call(["ddrescue", in_file_path, out_file_path], stdout=drclog, shell=True),但这给了我输入错误ddrescue。

2 个答案:

答案 0 :(得分:2)

如果ddrescue的stdout / stderr被重定向到管道,则不会更改其输出,那么您可以使用tee实用程序,在终端上显示输出并将其保存到文件:

$ ddrescue input_path output_path ddrescue_logfile |& tee logfile

如果确实如此,您可以尝试使用script实用程序提供伪tty:

$ script -c 'ddrescue input_path output_path ddrescue_logfile' -q logfile

如果it writes directly to a terminal,您可以使用screen来捕获输出:

$ screen -L -- ddrescue input_path output_path ddrescue_logfile

默认情况下,输出保存在screenlog.0文件中。


在Python中模拟基于tee的命令而不调用tee实用程序:

#!/usr/bin/env python3
import shlex
import sys
from subprocess import Popen, PIPE, STDOUT

command = 'ddrescue input_path output_path ddrescue_logfile'
with Popen(shlex.split(command), stdout=PIPE, stderr=STDOUT, bufsize=1) as p:
    with open('logfile', 'wb') as logfile:
        for line in p.stdout:
            logfile.write(line)
            sys.stdout.buffer.write(line)
            sys.stdout.buffer.flush()

使用tee

在Python中调用基于shell=True的命令
#!/usr/bin/env python
from pipes import quote
from subprocess import call

files = input_path, output_path, ddrescue_logfile
rc = call('ddrescue {} |  tee -a drclog'.format(' '.join(map(quote, files))),
          shell=True)

模拟基于script的命令:

#!/usr/bin/env python3
import os
import shlex
import pty

logfile = open('logfile', 'wb')
def read(fd):
    data = os.read(fd, 1024) # doesn't block, it may return less
    logfile.write(data) # it can block but usually not for long
    return data
command = 'ddrescue input_path output_path ddrescue_logfile'
status = pty.spawn(shlex.split(command), read)
logfile.close()

在Python中调用screen命令:

#!/usr/bin/env python3
import os
import shlex
from subprocess import check_call

screen_cmd = 'screen -L -- ddrescue input_path output_path ddrescue_logfile'
check_call(shlex.split(screen_cmd))
os.replace('screenlog.0', 'logfile')

答案 1 :(得分:-1)

对我有用的解决方案是subprocess.call(["ddrescue $0 $1 | tee -a drclog", in_file_path, out_file_path], shell=True)