首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将subprocess.call()输出推到终端和文件?

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

Stack Overflow用户
提问于 2014-09-21 19:35:25
回答 2查看 1.6K关注 0票数 1

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-22 07:11:55

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

代码语言:javascript
复制
$ ddrescue input_path output_path ddrescue_logfile |& tee logfile

如果是这样,那么您可以尝试使用script实用程序提供一个伪tty:

代码语言:javascript
复制
$ script -c 'ddrescue input_path output_path ddrescue_logfile' -q logfile

如果是it writes directly to a terminal,那么可以使用screen捕获输出:

代码语言:javascript
复制
$ screen -L -- ddrescue input_path output_path ddrescue_logfile

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

要在Python中模拟tee-based命令而不调用tee实用程序:

代码语言:javascript
复制
#!/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()

在Python中使用tee-based命令调用shell=True

代码语言:javascript
复制
#!/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-based命令:

代码语言:javascript
复制
#!/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命令:

代码语言:javascript
复制
#!/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')
票数 2
EN

Stack Overflow用户

发布于 2014-09-22 13:09:53

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25963074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档