在日常的python开发中,有时我们需要让程序在后台持续运行 , 而不是关闭终端窗口或按下Ctrl+C导致程序停止运行 。本篇文章将从多个角度分析如何让python程序保持后台运行 。

一、使用nohup命令
使用nohup命令可以让程序在后台持续运行 。例如,我们的python程序叫做test.py,执行以下命令即可:
nohup python test.py &
其中,&表示让任务在后台运行 。程序运行的输出会保存在nohup.out文件中,可以使用tail命令查看运行日志 。
二、使用screen命令
使用screen命令也可以让程序在后台持续运行 。screen是一个终端窗口管理工具,可以在同一终端窗口中创建多个虚拟终端窗口,并可以在这些窗口之间自由切换 。例如,我们执行以下命令:
screen -S test
然后在新的虚拟窗口中执行python test.py即可 。此时,按下Ctrl+A+D即可切换回原来的窗口 , 而程序仍然在后台运行 。
三、使用systemd
使用systemd也是一种让程序在后台持续运行的方法 。systemd是Linux下的服务管理器,可以管理系统启动、进程管理等 。我们可以创建一个systemd服务,使得python程序在系统启动时自动运行 。具体步骤如下:
1. 创建服务文件 , 比如test.service:
[Unit]
Description=test service
After=network.target
[Service]
ExecStart=/usr/bin/python /path/to/test.py
Restart=always
[Install]
WantedBy=multi-user.target
2. 将服务文件拷贝到systemd目录下:
sudo cp test.service /etc/systemd/system/
3. 重新加载systemd配置:
sudo systemctl daemon-reload
4. 启动服务:
sudo systemctl start test
至此,我们的python程序就会在后台持续运行了 。
四、使用Python代码
最后 , 我们介绍一种使用Python代码让程序在后台持续运行的方法 。具体代码如下:
import os
def create_daemon():
pid = os.fork()
if pid > 0:
# Exit first parent
sys.exit(0)
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Fork again, to ensure process cannot acquire terminal again.
pid = os.fork()
if pid > 0:
# Exit second parent
sys.exit(0)
# Redirect standard file descriptors.
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# Run the actual program.
main()
create_daemon()
使用该方法,我们可以在Python程序中调用create_daemon()函数即可让程序在后台持续运行 。
【python程序保持后台运行?】综上所述,我们介绍了四种让python程序保持后台运行的方法:使用nohup命令、使用screen命令、使用systemd和使用Python代码 。读者可以根据实际情况选择合适的方法 。
猜你喜欢
- python中n 表示什么?
- python实现人工蜂群算法
- 实例代码 Python3实现mysql连接和数据框的形成
- Python 爬虫的工具列表大全
- python 8种必备的gui库
- Python Flask框架实现简单加法工具过程解析
- python怎么终止进程?
- python输出列表差集?
- python字符的获取方式
- python多线程中消息队列如何实现?
