Administrator
发布于 2025-10-15 / 9 阅读
0
0

在debian系统里如何让python代码在后台运行?

在 root 下添加为开机自启(使用 systemd,服务以 root 身份运行)。将下面内容写入 /etc/systemd/system/liu_btc_trade_strategy.service 并启用:

  1. 创建 unit 文件:

Code

sudo tee /etc/systemd/system/liu_btc_trade_strategy.service > /dev/null <<'EOF'
[Unit]
Description=liu_btc_trade_strategy Python service (run as root)
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/liu
ExecStart=/usr/bin/python3 /home/liu/liu_btc_trade_strategy.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF
  1. 载入并启用(并立即启动):

Code

sudo systemctl daemon-reload
sudo systemctl enable --now liu_btc_trade_strategy.service
  1. 管理与查看:

Code

sudo systemctl status liu_btc_trade_strategy.service
sudo journalctl -u liu_btc_trade_strategy.service -f
sudo systemctl stop liu_btc_trade_strategy.service
sudo systemctl disable liu_btc_trade_strategy.service

注意:

  • 确认 /home/liu/liu_btc_trade_strategy.py 可被 root 读取并可运行(通常 root 有权限)。

  • 若脚本需虚拟环境或特定 PATH,把 ExecStart 改为该虚拟环境的 python 路径。

=========================================================================

在 root 下添加为开机自启(使用 systemd,服务以 root 身份运行)。将下面内容写入 /etc/systemd/system/yang_btc_trade_strategy.service 并启用:

  1. 创建 unit 文件:

Code

sudo tee /etc/systemd/system/yang_btc_trade_strategy.service > /dev/null <<'EOF'
[Unit]
Description=yang_btc_trade_strategy Python service (run as root)
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/yang
ExecStart=/usr/bin/python3 /home/yang/yang_btc_trade_strategy.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF
  1. 载入并启用(并立即启动):

Code

sudo systemctl daemon-reload
sudo systemctl enable --now yang_btc_trade_strategy.service
  1. 管理与查看:

Code

sudo systemctl status yang_btc_trade_strategy.service
sudo journalctl -u yang_btc_trade_strategy.service -f
sudo systemctl stop yang_btc_trade_strategy.service
sudo systemctl disable yang_btc_trade_strategy.service

注意:

  • 确认 /home/yang/yang_btc_trade_strategy.py 可被 root 读取并可运行(通常 root 有权限)。

  • 若脚本需虚拟环境或特定 PATH,把 ExecStart 改为该虚拟环境的 python 路径。


评论