Starting/stopping 没有 nohup 的后台 Python 进程 + ps aux grep + kill

Starting/stopping a background Python process wtihout nohup + ps aux grep + kill

我通常使用:

nohup python -u myscript.py &> ./mylog.log &       # or should I use nohup 2>&1 ? I never remember

启动后台 Python 进程,我想继续 运行 即使我注销,并且:

ps aux |grep python
# check for the relevant PID
kill <relevantPID>

它有效,但执行所有这些步骤很烦人。

我看过一些需要将PID保存在文件中的方法,但那更麻烦。


是否有一种干净的方法可以轻松启动/停止 Python 脚本? 如:

startpy myscript.py             # will automatically continue running in
                                # background even if I log out

# two days later, even if I logged out / logged in again the meantime
stoppy myscript.py

或者这个较长的部分 nohup python -u myscript.py &> ./mylog.log & 是否可以写在脚本的 shebang 中,这样我就可以使用 ./myscript.py 轻松启动脚本而不是编写长的 nohup 行?


注意:我正在寻找一两行解决方案,我不想为此操作编写专用的 systemd 服务

您是指远程登录和注销(例如通过 SSH)吗?如果是这样,一个简单的解决方案是安装 tmux(终端多路复用器)。它为终端创建一个服务器,运行 在它下面作为客户端。你用 tmux 打开 tmux,输入你的命令,从 tmux 输入 CONTROL+B+D 到 'detach',然后在主终端输入 exit 退出。当您重新登录时,tmux 和其中的进程 运行ning 仍将是 运行ning.

据我所知,远程系统上的 运行 后台脚本问题只有两个(或者可能三个或四个?)解决方案。

1) nohup

nohup python -u myscript.py > ./mylog.log  2>&1 &

1之二) 否认

与上面相同,略有不同,因为它实际上将程序删除到 shell 作业列表,从而阻止发送 SIGHUP。

2) 屏幕(或 neared 建议的 tmux)

Here你会找到屏幕的起点。

看到这个post for a great explanation of how background processes works. Another related post

3) Bash

另一个解决方案是编写两个 bash 函数来完成这项工作:

mynohup () {
    [[ "" = "" ]] && echo "usage: mynohup python_script" && return 0
    nohup python -u "" > "${1%.*}.log" 2>&1 < /dev/null &
}

mykill() {
    ps -ef | grep "" | grep -v grep | awk '{print }' | xargs kill
    echo "process "" killed"
}

只需将上述函数放入 ~/.bashrc~/.bash_profile 中,然后将它们用作正常的 bash 命令即可。

现在你可以完全按照你说的去做了:

mynohup myscript.py             # will automatically continue running in
                                # background even if I log out

# two days later, even if I logged out / logged in again the meantime
mykill myscript.py

4) 守护进程

这个daemon module很有用:

python myscript.py start

python myscript.py stop