簡體   English   中英

如何將subprocess.call()輸出推送到終端和文件?

[英]How do I push a subprocess.call() output to terminal and file?

我有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輸入錯誤。

如果ddrescue的stdout / stderr重定向到管道時ddrescue不會更改其輸出,則可以使用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文件中。


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

要使用shell=True在Python中調用基於tee的命令:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM