您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

如果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

如果它直接写入终端,则可以screen用来捕获输出

$ screen -L -- ddrescue input_path output_path ddrescue_logfile

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

tee在Python中模拟基于命令的命令而不调用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使用shell=True以下命令在Python中调用基于命令:

#!/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()

screen在Python中调用命令:

#!/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')
其他 2022/1/1 18:20:33 有588人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶