栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将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 python3import shleximport sysfrom subprocess import Popen, PIPE, STDOUTcommand = '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 pythonfrom pipes import quotefrom subprocess import callfiles = input_path, output_path, ddrescue_logfilerc = call('ddrescue {} |  tee -a drclog'.format(' '.join(map(quote, files))),          shell=True)

要模拟

script
基于命令:

#!/usr/bin/env python3import osimport shleximport ptylogfile = 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 datacommand = 'ddrescue input_path output_path ddrescue_logfile'status = pty.spawn(shlex.split(command), read)logfile.close()

screen
在Python中调用命令:

#!/usr/bin/env python3import osimport shlexfrom subprocess import check_callscreen_cmd = 'screen -L -- ddrescue input_path output_path ddrescue_logfile'check_call(shlex.split(screen_cmd))os.replace('screenlog.0', 'logfile')


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368910.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号