【问题标题】:Python Daemon calling a subprocess periodicallyPython Daemon 定期调用子进程
【发布时间】:2013-01-26 20:18:43
【问题描述】:

我正在基于Sander Marechal's 代码构建一个简单的 pyhon 守护进程。 Daemon 的全部目的是每秒运行一个 php 文件(php 文件循环通过数据库检查值和更新数据库)。部分出现问题

subprocess.call(['php','test.php'])

我可以在 shell 上运行“php test.php”,它会做它应该做的事情,但是当从守护进程定期调用它时,它似乎没有被执行。我也知道守护进程通过检查正在运行的进程 ps aux | 在后台工作grep "daemon-example" 我还包含了一个 do_something 函数,它记录每次函数执行的时间并将时间附加到文本文件中。

#!/usr/bin/env python
import sys, time,subprocess
from daemon import Daemon


def runphp():
    #subprocess.call(['php ~/pydaemon/test.php'], shell=True)
    subprocess.call(['python', 'test.py'])
def do_something():
    with open("/tmp/current_time.txt",'a') as f:
        f.write("The time is now\n" + time.ctime())

class MyDaemon(Daemon):
    def run(self):
        while True:
            time.sleep(1)
            do_something()
            subprocess.call(['php','test.php'])
            #runphp()
if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

【问题讨论】:

    标签: python subprocess python-daemon


    【解决方案1】:

    你试图运行的脚本没有被执行,因为工作目录是根目录('/'),这是因为这段代码:

    # decouple from parent environment
    os.chdir("/")
    

    所以实际上你的代码试图执行:python /test.py(不存在)而不是'your_current_directory/test.py'
    要修复它,请删除 os.chdir("/"),或提供文件的完整路径,如下所示:

    subprocess.call(['python','my_full_path_to_working_directory/test.py'])
    

    【讨论】:

    • 你在哪里看到 os.chdir("/")?我尝试提供 test.py 的完整路径(如下所示:/root/pydaemon/test.py)但没有运气。
    • 它在您使用的脚本中,在 Daemon 类中。(第 34 行)
    • 如果删除 os.chdir("/") 会发生什么?
    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2012-10-17
    • 2018-09-11
    • 2015-07-18
    相关资源
    最近更新 更多