【Python程序开发系列】如何让python脚本一直在后台保持运行
这是我的第385篇原创文章。
一、引言
让 Python 脚本在后台持续运行,有几种常见的方式,具体方式可以根据你的系统环境和需求选择。
二、Linux 或 macOS 系统
2.1 使用 nohup命令
nohup(no hang up)命令可以让进程在后台运行,即使用户退出终端会话,该进程也会继续运行。
nohup python your_script.py &
nohup:命令会使得脚本在后台运行,并且输出会被重定向到 nohup.out文件。&:符号使得进程在后台运行。
如果你希望将输出重定向到特定文件,可以这样做:
nohup python your_script.py > output.log 2>&1 &
> output.log:将标准输出重定向到 output.log 文件。
2>&1:将标准错误输出(stderr)重定向到标准输出(stdout)。
2.2 使用 screen或 tmux工具
screen 和 tmux 是常见的终端复用工具,可以让你在后台运行多个会话,并且可以随时断开和重新连接。
启动一个新的 screen 会话:
screen -S my_session
运行你的 Python 脚本:
python your_script.py
按 Ctrl + A 然后按 D 来将会话放到后台。对于 tmux,操作类似。
2.3 使用 systemd服务(适用于 Linux 系统)
如果你需要将 Python 脚本作为系统服务运行,可以使用 systemd 服务来管理。创建一个新的 systemd 服务文件,例如 /etc/systemd/system/myscript.service:
sudo nano /etc/systemd/system/myscript.service
在文件中加入以下内容:[Unit]
Description=My Python Script
[Service]
ExecStart=/usr/bin/python3 /path/to/your_script.py
WorkingDirectory=/path/to/your/script
Restart=always
User=your_user
Group=your_group
StandardOutput=file:/path/to/log/output.log
StandardError=file:/path/to/log/error.log
[Install]
WantedBy=multi-user.target
重新加载 systemd 服务并启用它:sudo systemctl daemon-reload
sudo systemctl enable myscript.service
sudo systemctl start myscript.service
查看日志:sudo journalctl -u myscript.service
三、Windows 系统
3.1 使用 pythonw.exe
在 Windows 上,可以使用 pythonw.exe 来运行 Python 脚本。pythonw.exe 是一个没有命令行窗口的 Python 解释器,适用于后台运行脚本。
使用 pythonw.exe 来启动脚本:
pythonw your_script.py
3.2 使用任务计划程序(Task Scheduler)
Windows 提供了任务计划程序(Task Scheduler)来管理后台任务。
- 打开“任务计划程序”(Task Scheduler)。
- 选择“创建任务”(Create Task)。
- 在“常规”选项卡下,设置任务的名称和描述。
- 在“触发器”选项卡下,设置任务触发的条件(例如,系统启动时或指定时间)。
- 在“操作”选项卡中,选择“启动程序”,并选择 Python 可执行文件以及你的脚本。
- 点击“确定”,即可后台运行 Python 脚本。
3.3 使用 pyinstaller打包成可执行文件
如果你希望 Python 脚本在没有命令行界面的情况下运行,并且能够方便地管理,可以使用 pyinstaller 打包你的脚本成 Windows 可执行文件(.exe):
安装 pyinstaller:
pip install pyinstaller
使用 pyinstaller 打包脚本:
pyinstaller --noconsole --onefile your_script.py
--noconsole 选项确保脚本没有控制台窗口。
--onefile 选项将所有文件打包成一个单一的可执行文件
执行后,生成的 .exe 文件会在 dist/ 目录中,可以直接在后台运行。
作者简介: 读研期间发表6篇SCI数据算法相关论文,目前在某研究院从事数据算法相关研究工作,结合自身科研实践经历持续分享关于Python、数据分析、特征工程、机器学习、深度学习、人工智能系列基础知识与案例。关注gzh:数据杂坛,获取数据和源码学习更多内容。
原文链接: