在python中在后台运行一个函数

时间:2016-08-26 22:52:50

标签: python process fork

我希望使用子进程在后台运行特定函数,并且我还希望在需要时终止子进程。

我将子进程的pid存储在一个文件中。因此,当用户输入" python script.py exit"之类的东西时,我可以接受命令行争论并杀死孩子。

import os
import time
import notify2
f = open("output.txt","w")
def notify(message):
    notify2.init("Cricket Matches")
    n = notify2.Notification("Live Update",message)
    n.show()

def fun():
    while(True):
        notify("match")

pid = os.fork()
if pid == 0:
    fun()
else:
    #do other stuff
    f1.write(str(pid))

是否有更好的替代方案来实现相同目标?我发现nohup和屏幕很难从脚本(而不是从命令行)实现。

0 个答案:

没有答案