【问题标题】:How to receive real time logs from PID's in terminal?如何在终端接收来自 PID 的实时日志?
【发布时间】:2021-04-16 08:38:56
【问题描述】:

我有一个使用 Ray 包用 Python 编写的计算程序,输出如下:

 Actor(Play001,69a6825d641b461327313d1c01000000)

此进程使用以下 pid:

pid = 87972

在 Ray 仪表板中,我可以查看日志。片段如下:

Logs

192.168.0.101 (PID: 87972)

1 Function 1: Starting up
2 Worker 1: Done
3 Press enter to continue or to exit

在 Python 中,我设法检查了这个 PID 是否存在:

import psutil
pid = 87972
if psutil.pid_exists(pid):
    print("a process with pid %d exists" % pid)

我想要在终端输出中实时显示日志。我该怎么做?

【问题讨论】:

  • 您想远程查看日志,还是在同一台机器上查看?另外,你能提供你的代码吗?帮助你会更容易。见Minimal Reproducible Example
  • 在同一台机器上;我已经发布了一个解决方案。如果你有更好的,请发布它。
  • 您是从命令行启动脚本吗?如果是这样,您可以使用管道在其他地方输入脚本的标准输出
  • 确实如此

标签: python pid ray psutil


【解决方案1】:

在 ray 上,驱动程序进程从所有其他工作人员的标准输出日志中输出。如果你想在另一个脚本上处理你的脚本日志,你可以使用管道。

假设您有两个文件:myrayscript.pymylogparser.py

myrayscript.py 上,您拥有自己的脚本,就像之前编写的一样。

mylogparser,您将收到来自标准输入的光线日志:

while True:
  logLine = input()
  # do your stuff here

现在,从命令行使用管道:

python3 myrayscript.py | python3 mylogparser.py

【讨论】:

  • 代码挂起。按 ctrl+c 时:KeyboardInterrupt Exception 在以下位置被忽略:<_io.textiowrapper name="<stdout>" mode="w" encoding="utf-8"> BrokenPipeError: [Errno 32] Broken pipe
【解决方案2】:

以下解决方案虽然麻烦,但仍然有效:

pid = 87972
p = psutil.Process(pid)   
temp = p.open_files()
sPth = temp[0][0]
oFile = open(sPth)
Content = oFile.read()
msContent = Content.splitlines()

为了更加完整,您可以观察文件中的变化。

from watchgod import watch
for changes in watch(sPth):
       print(changes)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    相关资源
    最近更新 更多