这里的测试环境为 MacOS
一. python 文件
建立 test.py 文件,其代码如下 :
# coding:utf-8
import time
while True:
# 每隔 2 秒钟打印一次字符串
time.sleep(2)
print('hello, python...')
二. shell 脚本文件
建立 test.sh 文件,其代码如下 :
#!/bin/bash
echo "begin."
nohup python test.py > nohup.out 2>&1 &
echo "end."
修改该 test.sh 文件使之具有执行权限 :
# chmod +x ./test.sh
三. 执行脚本启动 nohup ,以及 python 内部 print 无法输出问题
执行 shell 脚本 :
# ./test.sh
该目录下会多出一个文件 nohup.out , 此时目录下有三个文件 test.sh test.py nohup.out ,
但是发现 nohup.out 中显示不出来 python 程序中 print 的内容,
这是因为 python 输出有缓冲,使得 nohup.out 中不能马上有内容
此时,可以使用 python 的 -u 参数,使得 python 不启用缓冲,即 test.sh 脚本改为 :
#!/bin/bash
echo "begin."
nohup python -u test.py > nohup.out 2>&1 &
echo "end."
四. 关闭 nohup 启动的 python 程序
查找 python 进程 :
# ps
显示如下 :
PID TTY TIME CMD
2986 ttys001 0:00.47 -bash
8409 ttys001 0:00.02 python -u test.py
根据进程 ID , kill 掉该 python 进程
# kill -9 8409