【问题标题】:python subprocess print and store stdoutpython子进程打印和存储标准输出
【发布时间】:2021-02-06 04:03:05
【问题描述】:

我正在学习 python 并编写一个小脚本。我需要将我的输出保存在一个文件中,并且还要在屏幕上打印输出。我尝试了各种方法,例如stdout=subprocess.PIPEi 无法确定输出到两者。请原谅我这个愚蠢的问题`

#!/usr/bin/python
import os
import subprocess
with  open('/root/test/testfile') as f , open('aaa.txt',"w") as final:
    content =  f.read().splitlines()
    for x in content:
            result= subprocess.Popen(['grep',x,'/news/today/night/logs'],stdout=final)

【问题讨论】:

  • 我认为这是重复的。如果它不能满足您的需求,请告诉我。
  • @tdelaney 我无法理解与我的问题相比的解决方案,请您帮助我处理 proc wait 和 sys 命令。
  • testfile 中有哪些行?在日志或正则表达式中可以找到一些单词?
  • 我认为您根本不需要子流程。只需让 python 找到这些行。这有点像现有答案的作用,但似乎文件混淆了。我会发布我的尝试。
  • @tdelaney 谢谢你,如果你能分享你的解决方案,我创造了类似于你的东西,但我只得到一个 grep 输出。

标签: python linux python-2.7 subprocess python-2.x


【解决方案1】:

看起来您只是使用子进程来运行 grep,但 python 也可以对字符串进行类似 grep 的匹配。该程序将读取“testfile”中的行,然后从“log”中写出包含 testfile 行的行。 “testfile”中第一行的所有日志匹配都将在第二行的匹配之上,等等......并且匹配多个testfile行的日志行将输出多次。

此代码假定您没有匹配正则表达式。

#!/usr/bin/python

# assuming logs is not too big, you could read it into memory once
# with open('/news/today/night/logs') as logfile:
#     logs = list(logfile)
    
with  open('/root/test/testfile') as f , open('aaa.txt',"w") as final:
    for wanted in f:
        wanted = wanted.strip()
        with open('/news/today/night/logs') as logs:
            for log in logs:
                if wanted in log:
                    print(log, end='')
                    final.write(log)

【讨论】:

  • 哇没有意识到我可以这样写......使用我的代码与你的代码相比有什么缺点吗?你能帮我在我的代码中打印标准输出吗?非常感谢
  • 我最初链接的答案向您展示了如何做到这一点。使您的子进程标准输出成为管道,然后循环读取管道并写入多个位置。 stackoverflow.com/questions/15535240/…
  • 谢谢你,但正如你所说,我无法在内存中打开日志(打开('/news/today/night/logs')作为日志),因为它可以是系统/应用程序日志大,我会试试你的其他方法,并会更新你:)
【解决方案2】:

试试这个:

#!/usr/bin/python
import os

with open('/root/test/testfile') as f, open('/root/test/aaa.txt',"a") as final:
    content = f.read().splitlines()
    for line in content:
        if "/news/today/night/logs" in line:
            print(line)
            final.write(line)

我让你的 aaa.txt 文件追加而不是写入。

【讨论】:

  • 抱歉,我正在打印 x 值,我正在尝试获取 grep result= subprocess.Popen(['grep',x,'/news/today/night/logs'] 的输出标准输出=最终)
  • 收到此错误 --- Traceback(最近一次调用最后一次):文件“/usr/sbin/akash.py”,第 7 行,在 if '/news/today/night/ logs' in line: NameError: name 'line' is not defined
  • 哈哈我的错,忘了它叫x。现在应该好了!
  • 抱歉缺少输出。谢谢
  • 任何错误代码?该文件的任何行中是否还包含/news/today/night/logs
猜你喜欢
  • 2014-04-29
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 2013-06-29
  • 2013-05-01
  • 2018-02-25
  • 1970-01-01
相关资源
最近更新 更多