当前位置:   article > 正文

Python程序后台运行的五种方式_python 后台运行

python 后台运行

现在我来详细讲解 Python程序后台运行的五种方式 的完整攻略。

1. 使用nohup命令

nohup是一个常用的命令,可在远程服务器上运行命令行应用程序,并将输出重定向到文件nohup.out中。您可以使用以下命令将Python脚本在后台执行,无论是否注销SSH连接:

nohup python script.py &
  • 1

使用“&”符号在后台运行脚本,执行此命令后,控制台将返回进程号,并且您可以随时查看nohup.out文件来检查输出。

2. 使用screen命令

使用screen命令可以在后台运行多个命令行会话,并且甚至可以在SSH连接断开后保持会话。可以使用以下命令来运行Python脚本:

screen -S mysession  
python script.py
  • 1
  • 2

这将创建名为“mysession”的新会话,并在其中启动Python脚本。按“Ctrl + A + D”键组合来断开会话,返回到控制台或另一个屏幕会话。

3. 使用systemd服务

Systemd是Linux系统的一个初始化系统,并提供了一种方便的方法来启动、停止和管理系统服务。您可以使用以下过程在systemd服务中运行Python脚本:

  1. 编写systemd服务配置文件。例如,在“/etc/systemd/system/”目录下创建名为“myscript.service”的文件,其内容为:
[Unit]  
Description=My Python Script  
After=multi-user.target  
  
[Service]  
Type=idle  
ExecStart=/usr/bin/python3 /path/to/script.py  
  
[Install]  
WantedBy=multi-user.target
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. 保存文件并重载systemd守护程序配置:
sudo systemctl daemon-reload
  • 1
  1. 启动服务:
sudo systemctl start myscript
  • 1
  1. 您可以查看服务状态并检查是否存在错误:
sudo systemctl status myscript
  • 1

4. 使用celery任务队列

Celery是Python中一个流行的任务队列实现,使多进程执行变得简单。您可以使用以下过程在Celery任务队列中运行Python脚本:

  1. 安装Celery:使用pip安装celery:
pip install celery
  • 1
  1. 编写任务代码:
from celery import Celery  
app = Celery('task', backend='rpc://', broker='amqp://localhost')  
  
@app.task  
def mytask():  
  # 任务逻辑
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. 启动worker:在终端中,执行以下命令来启动worker:
celery -A tasks worker
  • 1
  1. 调用任务:在Python中,您可以通过以下方式调用任务:
from tasks import mytask  
mytask.delay()
  • 1
  • 2

5. 使用supervisord

Supervisord是一个进程控制系统,帮助您以可靠的方式启动、停止和重启应用程序。可以使用以下过程在supervisord中运行Python脚本:

  1. 安装supervisord:使用pip安装supervisord:
pip install supervisor
  • 1
  1. 创建supervisord配置文件:在“/etc/supervisor/conf.d/”目录下创建名为“myscript.conf”的文件,其内容为:
[program:myscript]  
command=/usr/bin/python /path/to/script.py  
autostart=true  
autorestart=true  
stderr_logfile=/var/log/myscript.err.log  
stdout_logfile=/var/log/myscript.out.log  
user=username
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

其中,program是程序名称,command是要执行的命令,autostart和autorestart指定程序启动和重启的设置,stderr_logfile和stdout_logfile指定错误和输出日志的位置。

  1. 保存文件并重新加载supervisord配置:
sudo supervisorctl reread  
sudo supervisorctl update
  • 1
  • 2
  1. 启动脚本:
sudo supervisorctl start myscript
  • 1

以上就是我讲解“Python脚本后台运行的五种方式”的完整攻略,希望对您有所帮助。

点击下方安全链接前往获取

CSDN大礼包:《Python入门&进阶学习资源包》免费分享

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/836153

推荐阅读
相关标签