将unix命令输出重定向到python中的文件中

2024-06-16 12:01:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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,而输出文件是一个空白文件。在

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

基本上,这里的目的是将shell命令的输出重定向到python中的一个文件中


Tags: 文件fromimportrenoneossysshell
1条回答
网友
1楼 · 发布于 2024-06-16 12:01:11

除非您真的需要分离stdout/stderr(根据您最初的帖子,您不需要),否则一种方法是使用subprocess.check_输出. 它类似于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)

相关问题 更多 >