从另一个作为守护进程运行的python脚本运行python脚本

2024-04-20 08:37:29 发布

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

我有一个小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中,我看不到输出

我该怎么做


Tags: 文件字符串pytest程序env脚本bin
3条回答

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

因此,如果该守护进程运行另一个进程:

I want to call this script from a running Daemon

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

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

尝试the ^{} library获取创建守护进程指定特定文件(例如,打开的日志文件)的方法,以便在守护进程中保持打开状态

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

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

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

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

相关问题 更多 >