【问题标题】:Run a python script from another python script running as a daemon从作为守护进程运行的另一个 python 脚本运行 python 脚本
【发布时间】:2019-02-07 14:22:26
【问题描述】:

我有一个小的 python 文件,它只输出一个字符串:

#!/usr/bin/env python
print("This is a Test")

我可以像这样从另一个 python 脚本调用这个 python 脚本:

subprocess.call(['python', 'myPythonFile.py'])

我可以在我的源 python 程序中看到“这是一个测试”。

但我想从正在运行的守护程序调用此脚本,如下所述:https://gist.github.com/andreif/cbb71b0498589dac93cb

当我打电话给

    subprocess.call(['python', 'myPythonFile.py'])

在 MyDaemon.Run 中我看不到输出。

我该怎么做?

【问题讨论】:

  • 我正在查看你链接的类,我注意到在初始化时它有 stdout='/dev/null' 如果你不给它正确的输出它会打印为 null 所以你永远看不到它!
  • 如果我使用 print("Show something") 我可以在控制台中看到它??
  • 您是在问还是在说?您的评论不清楚
  • 当我使用 print("Show something") 我可以在控制台中看到这个输出。我是否还需要将 stout 更改为其他东西才能看到我的第二个 python 脚本的输出?
  • 你的问题说你看不到,现在你可以看到了吗?你在哪里可以看到它,你想在哪里看到它?

标签: python python-daemon


【解决方案1】:

尝试使用check_output 函数在控制台中查看实际输出

subprocess.check_output(['python', 'myPythonFile.py'])

您可以在subprocess docs找到更多信息

【讨论】:

  • 嗨,这没有任何区别。还有其他想法吗?
【解决方案2】:

subprocess.call 可以将其输出发送到文件

tempfile = '/tmp/output.tmp' # better use mktemp

with open( tempfile, 'w') as output:
    response = subprocess.call(
         ['python', 'myPythonFile.py'], 
         stdout=output, 
         stderr=output,
    )
with open( tempfile, 'r') as output:
    # read what happened from output, and decide what to do next
    # or perhaps just feed it into your logging system

【讨论】:

    【解决方案3】:

    守护进程的特点是没有控制终端,因为它与启动守护进程的任何东西分离。根据定义,守护进程未连接到任何控制台。

    所以,如果该守护进程运行另一个进程:

    我想从一个正在运行的守护进程调用这个脚本

    那么仍然没有控制终端,标准输出默认连接到空设备。

    您需要安排守护进程将其输出放在某处。例如,一个日志文件。

    尝试the python daemon library 来创建守护进程指定特定文件(例如您打开的日志文件)以在守护进程中保持打开状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 2011-01-03
      • 2013-10-14
      • 1970-01-01
      相关资源
      最近更新 更多