ars*_*nal 57 command-line process
我正在从我的 Ubuntu 机器的终端运行一个 python 程序,
$ python test.py
Run Code Online (Sandbox Code Playgroud)
但是如果我关闭终端,我的整个程序将停止,有没有办法在后台运行这个 python 程序,这样如果我关闭我的终端,它仍然会继续运行?
而且在后台运行这个程序之后,如果我再次登录到那个终端,我如何找出我的实际程序是否仍在运行?
sou*_* c. 95
在python脚本中使用 shebang 行。使用命令使其可执行,
chmod +x test.py
Run Code Online (Sandbox Code Playgroud)
即使关闭终端,也不要挂断在后台运行程序,
nohup /path/to/test.py &
Run Code Online (Sandbox Code Playgroud)
或者简单地(不对您的程序进行任何更改)
nohup python /path/to/test.py &
Run Code Online (Sandbox Code Playgroud)
不要忘记使用& 将它放在后台。
作用nohup: nohup使您的脚本忽略SIGHUP,并将stdout/stderr重定向到文件nohup.out,以便在您注销后该命令可以在后台继续运行。如果您关闭 shell/终端或注销,您的命令不再是该 shell的子级。它属于init进程。如果您搜索,pstree您会看到它现在归进程 1 (init) 所有。
要再次查看该过程,请在终端中使用,
ps ax | grep test.py
Run Code Online (Sandbox Code Playgroud)
无法将其带回前台,因为前台(因为终端已经关闭)不再存在。因此,一旦关闭,就无法再次恢复该终端。
en4*_*4bz 14
python test.py &
Run Code Online (Sandbox Code Playgroud)
将在后台运行文件。
为了找到正在运行的程序,您可以使用ps -e列出所有正在运行的程序。您可以使用grep从列表中查找您的特定程序。