【问题标题】:Redirect unix command output into a file in python将unix命令输出重定向到python中的文件
【发布时间】:2015-06-26 01:56:52
【问题描述】:
import sys,re,os
from subprocess import Popen, PIPE, call


newCmd = 'diff -qr -b -B '+sys.argv[1]+' '+sys.argv[2]+' --exclude-from='+sys.argv[3]+' | grep pattern1\|pattrern2 > outputFile'

ouT,erR = Popen(newCmd, shell=True).communicate()
print ouT,erR

out 和 erR 正在打印 None, None 并且 outputFile 是一个空白文件。

当我在普通 shell 中执行相同的“newCmd”时,它执行得很好

基本上,这里的目的是将shell命令的输出重定向到python内部的一个文件中。尝试了不同的方法(使用调用),对我来说没有任何结果

【问题讨论】:

标签: python unix pipe subprocess popen


【解决方案1】:

除非您真的需要分离 stdout/stderr(根据您的原始帖子,您不需要),否则一种方法是使用 subprocess.check_output。它类似于 Popen,但捕获输出并将其作为字符串返回。之后,您可以在 python 中操作输出(例如,而不是使用 'grep')并将生成的字符串写入您选择的文件中。

output_as_string = subprocess.check_output('dir', shell=True)
# i'll replace all "bananas" into "apples" just for demo purposes:
manip_output = output_as_string.replace('bananas', 'apples')

with open('yourfile.txt', 'w') as f:
    f.write(manip_output)

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2020-10-14
    • 2018-06-07
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多