Nohup 运行 python 程序

Nohup to run python program

我正在从本地计算机上安装了 CentOS 的远程服务器上工作,

我想要 运行 以下代码:

nohup python3 search_large_files.py &

然而,它并没有像我预期的那样工作

[root@iz2ze9wve43n2nyuvmsfx5z ~]# ps ax| grep nohup
29360 pts/1    R+     0:00 grep --color=auto nohup

我如何利用 nohup 来 运行 我的 python 代码,这样我就可以在服务器工作时关闭电源并进入睡眠状态。

nohup 将其自身从进程名称中删除 运行。由于这个原因,您无法使用 ps ax| grep nohup 找到它。

检查我创建的这个 test.py 文件:

import sys
import time
while True:
    time.sleep(0.5)
    sys.stdout.write('ok\n')
    sys.stdout.flush()

运行它:

nosklo@Whosebug:~$ python3 test.py 
ok
ok
^CTraceback (most recent call last):
  File "test.py", line 4, in <module>
    time.sleep(0.5)
KeyboardInterrupt

现在 nohup:

nosklo@Whosebug:~$ nohup python3 test.py > foo.txt &
nohup: ignoring input and redirecting stderr to stdout
[1] 12453
nosklo@Whosebug:~$ ps ax | grep -i nohup
nosklo  12548  0.0  0.0  15976   944 pts/17   S+   14:14   0:00 grep --color=auto -i nohup
nosklo@Whosebug:~$ ps ax | grep -i python
nosklo  12453  0.0  0.0  31400  5660 pts/17   S    14:13   0:00 python3 test.py
nosklo  12528  0.0  0.0  15976   940 pts/17   S+   14:14   0:00 grep --color=auto -i python

如您所见,它就在那里,pid 12453 但名称中没有 nohup

nosklo@Whosebug:~$ kill %1
[1]+  Terminated               nohup python3 test.py > foo.txt
nosklo@Whosebug:~$ tail foo.txt
ok
ok
ok
....

它一直在工作。