How to run a Python script in the background even

2019-01-08 03:31发布

I have Python script bgservice.py and I want it to run all the time, because it is part of the web service I build. How can I make it run continuously even after I logout SSH?

8条回答
劫难
2楼-- · 2019-01-08 04:17

You can nohup it, but I prefer screen.

查看更多
该账号已被封号
3楼-- · 2019-01-08 04:20

If what you need is that the process should run forever no matter whether you are logged in or not, consider running the process as a daemon.

supervisord is a great out of the box solution that can be used to daemonize any process. It has another controlling utility supervisorctl that can be used to monitor processes that are being run by supervisor.

You don't have to write any extra code or modify existing scripts to make this work. Moreover, verbose documentation makes this process much simpler.

After scratching my head for hours around python-daemon, supervisor is the solution that worked for me in minutes.

Hope this helps someone trying to make python-daemon work

查看更多
We Are One
4楼-- · 2019-01-08 04:22

Run nohup python bgservice.py & to get the script to ignore the hangup signal and keep running. Output will be put in nohup.out.

Ideally, you'd run your script with something like supervise so that it can be restarted if (when) it dies.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-08 04:30

You might consider turning your python script into a proper python daemon, as described here.

python-daemon is a good tool that can be used to run python scripts as a background daemon process rather than a forever running script. You will need to modify existing code a bit but its plain and simple.

If you are facing problems with python-daemon, there is another utility supervisor that will do the same for you, but in this case you wont have to write any code (or modify existing) as this is a out of the box solution for daemonizing processes.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-08 04:33

If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.

Ctrl+Z (suspend the process)

bg (restart the process in the background

disown %1 (assuming this is job #1, use jobs to determine)

查看更多
疯言疯语
7楼-- · 2019-01-08 04:34

Here is a simple solution inside python using a decorator:

import os, time

def daemon(func):
    def wrapper(*args, **kwargs):
        if os.fork(): return
        func(*args, **kwargs)
        os._exit(os.EX_OK)
    return wrapper

@daemon
def my_func(count=10):    
  for i in range(0,count):
     print('parent pid: %d' % os.getppid())
     time.sleep(1)


my_func(count=10)
#still in parent thread
time.sleep(2)
#after 2 seconds the function my_func lives on is own

You can of course replace the content of your bgservice.py file in place of my_func.

查看更多
登录 后发表回答