洛阳网站开发,google广告投放,深圳网站建设那家好,wordpress中英文网站场景
最近在使用ubuntu服务器部署MySQL和同步数据#xff0c;同步数据使用的是python#xff0c;但是我不能直接操作服务器#xff0c;只能通过Xshell远程访问服务器#xff0c;但是启动python脚本的时候如果关掉xshell会停止Python脚本#xff0c;所以如果要让python脚本…场景
最近在使用ubuntu服务器部署MySQL和同步数据同步数据使用的是python但是我不能直接操作服务器只能通过Xshell远程访问服务器但是启动python脚本的时候如果关掉xshell会停止Python脚本所以如果要让python脚本继续在后台运行有以下几种方法来实现。 选择哪种方法取决于您的具体需求和偏好。nohup 简单但功能有限screen 或 tmux 提供更多灵活性而 systemd 方法更适合长期运行的后台服务。
1.使用nohup命令
nohup 命令可以让您运行的程序在关闭终端后继续运行。
执行命令
nohup python3 your_script.py 这里 your_script.py 是您的Python脚本文件。
nohup 会将输出重定向到 nohup.out 文件除非您指定了其他输出文件。
2.使用screen或tmux
screen 和 tmux 是终端多路复用器允许您从一个会话中分离出来并在以后重新连接。
首先安装 screen 或 tmux如果尚未安装
sudo apt-get install screen或
sudo apt-get install tmux创建一个新会话
screen -S session_name或
tmux new -s session_name在会话中运行您的Python脚本
python3 your_script.py分离会话 在 screen 中按 Ctrl-A 然后按 D。在 tmux 中按 Ctrl-B 然后按 D。 重新连接到会话 对于 screen使用 screen -r session_name。对于 tmux使用 tmux attach -t session_name。
3.使用 systemd 服务
如果您希望脚本像服务一样运行可以创建一个 systemd 服务单元。
1.准备你的python脚本
确保你的Python脚本位于你的Ubuntu服务器上并记下其路径。例如假设脚本的路径是 /home/username/my_script.py。确保脚本具有执行权限
chmod x /home/username/my_script.py脚本首行应该指定Python解释器的路径例如
#!/usr/bin/env python32.创建Systemd服务文件
以root用户权限打开一个新的服务文件。假设你的服务名为 y_python_script.service
sudo nano /etc/systemd/system/my_python_script.service在服务文件中添加以下内容替换/home/username/my_script.py为你的脚本的实际路径
[Unit]
DescriptionMy Python Script Service[Service]
ExecStart/usr/bin/python3 /home/username/my_script.py
WorkingDirectory/home/username/
Restarton-failure[Install]
WantedBymulti-user.targetDescription 是服务的描述。ExecStart 指定启动服务时执行的命令。Restart 指定何时重启服务on-failure 表示仅在失败时重启。WorkingDirectory 指定的是脚本所在目录并且在脚本引用外部的配置文件时要写上。
保存并关闭文件。
3.启用服务
重新加载 systemd 以识别新服务
sudo systemctl daemon-reload启动服务
sudo systemctl start my_python_script.service检查服务状态确保一切运行正常
sudo systemctl status my_python_script.service可选设置服务在系统启动时自动启动
sudo systemctl enable my_python_script.service4.管理服务
停止服务:
sudo systemctl stop my_python_script.service重新启动服务:
sudo systemctl restart my_python_script.service查看服务日志:
journalctl -u my_python_script.service结束
主要花了很大的篇幅来介绍systemd服务因为使用 systemd 管理Python脚本作为服务提供了更多的控制和灵活性例如自动重启、日志记录等。这对于生产环境中运行长期任务特别有用。