问题:即使注销SSH,如何在后台运行Python脚本?

我有Python脚本,bgservice.py并且希望它一直运行,因为它是我构建的Web服务的一部分。即使注销SSH,如何使它连续运行?

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?


回答 0

运行nohup python bgservice.py &以获取脚本以忽略挂断信号并继续运行。输出将被放入nohup.out

理想情况下,您可以使用类似的脚本来运行脚本,supervise以便在脚本终止时可以重新启动。

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.


回答 1

如果您已经开始该过程,并且不想杀死它并在nohup下重启,则可以将其发送到后台,然后将其取消。

Ctrl+Z (暂停过程)

bg (在后台重新启动该过程

disown %1(假设这是工作#1,用于jobs确定)

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)


回答 2

您还可以使用几乎每个Linux / Unix系统都应该具有的GNU屏幕

如果您使用的是Ubuntu / Debian,它的增强版本byobu也相当不错。

You could also use GNU screen which just about every Linux/Unix system should have.

If you are on Ubuntu/Debian, its enhanced variant byobu is rather nice too.


回答 3

你可能会考虑把您的Python脚本到合适的Python守护进程,如所描述这里

python-daemon是一个很好的工具,可用于将python脚本作为后台守护进程运行,而不是永远运行的脚本。您将需要修改现有的代码,但是要简单明了。

如果您遇到python-daemon的问题,可以使用另一个实用程序管理器为您执行相同的操作,但是在这种情况下,您将不必编写任何代码(或修改现有代码),因为这是一种实现即用即用的解决方案流程。

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.


回答 4

您可以不用,但我更喜欢screen

You can nohup it, but I prefer screen.


回答 5

这是使用装饰器的python内部简单解决方案:

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

您当然可以代替替换bgservice.py文件的内容my_func

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.


回答 6

zsh的外壳有一个选项,以使与nohup的运行所有的后台进程。

~/.zshrc添加行:

setopt nocheckjobs  #don't warn about bg processes on exit
setopt nohup        #don't kill bg processes on exit

然后,您只需要运行类似这样的过程:python bgservice.py &,就不再需要使用nohup命令。

我知道使用zsh的人并不多,但是我推荐它是一个非常酷的shell。

The zsh shell has an option to make all background processes run with nohup.

In ~/.zshrc add the lines:

setopt nocheckjobs  #don't warn about bg processes on exit
setopt nohup        #don't kill bg processes on exit

Then you just need to run a process like so: python bgservice.py &, and you no longer need to use the nohup command.

I know not many people use zsh, but it’s a really cool shell which I would recommend.


回答 7

如果您需要的是无论您是否登录,该进程都将永远运行,请考虑将该进程作为守护程序运行。

supervisord是一个伟大的开箱解决方案,可用于任何守护进程处理的。它具有另一个控制实用程序supervisorctl,可用于监视主管正在运行的进程。

您无需编写任何额外的代码或修改现有的脚本即可完成此工作。此外,冗长的文档使此过程更加简单。

在围绕python-daemon抓了几个小时后,supervisor是在几分钟内为我工作的解决方案。

希望这可以帮助尝试使python-daemon工作的人

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


回答 8

您也可以使用Yapdi

基本用法:

import yapdi

daemon = yapdi.Daemon()
retcode = daemon.daemonize()

# This would run in daemon mode; output is not visible
if retcode == yapdi.OPERATION_SUCCESSFUL:
print('Hello Daemon')

You can also use Yapdi:

Basic usage:

import yapdi

daemon = yapdi.Daemon()
retcode = daemon.daemonize()

# This would run in daemon mode; output is not visible
if retcode == yapdi.OPERATION_SUCCESSFUL:
print('Hello Daemon')

回答 9

试试这个:

nohup python -u <your file name>.py >> <your log file>.log &

您可以在屏幕上运行以上命令,然后退出屏幕。

不可以通过以下方式尾随python脚本的日志: tail -f <your log file>.log

要杀死脚本,可以使用ps auxkill命令。

Try this:

nohup python -u <your file name>.py >> <your log file>.log &

You can run above command in screen and come out of screen.

Now you can tail logs of your python script by: tail -f <your log file>.log

To kill you script, you can use ps -aux and kill commands.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。