您的位置:首页 > 编程语言 > Python开发

nohup 执行 python 程序 , 以及 print 无法输出问题

2017-10-21 11:55 549 查看
这里的测试环境为 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."


再次执行该 shell 脚本,nohup.out 中就会有 python 中 print 输出的内容

四. 关闭 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 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐