简体   繁体   English

需要将python脚本的输出附加到文件

[英]Need to append output from the python script to the file

I'm trying to write a simple shell script to start and stop my python script. 我正在尝试编写一个简单的shell脚本来启动和停止我的python脚本。 The reason I'm doing this is because I want to use tool called monit to monitor processes and I also would need to be sure that this script is running. 我这样做的原因是因为我想使用名为monit工具来监视进程,并且还需要确保此脚本正在运行。 So here is my python script: 所以这是我的python脚本:

test.py test.py

 import time

 for i in range(100):
     time.sleep(1)
     print 'a'*i

and here is my shell script: 这是我的shell脚本:

wrapper_test.sh wrapper_test.sh

 #! /bin/bash

 PIDFILE=/home/jhon/workspace/producer/wrapper_test.pid

 case $1 in
   start)
     echo $$ > ${PIDFILE};
     exec /usr/bin/python /home/jhon/workspace/producer/test.py 1>&2 output
     ;;
   stop)
     kill `cat ${PIDFILE}`
     ;;
   *)
     echo "Usage: wrapper {start|stop}" 
     ;;

 esac
 exit 0

The result that I want is lets say I do tail -f output and I would see staff coming to the file. 我想要的结果是说我执行tail -f output并且我会看到工作人员进入该文件。 I also tried to change 1>&2 to just > but this creates file, and once I press Ctrl + C than all the data appends to the file. 我还尝试将1>&2更改为>但这会创建文件,一旦按Ctrl + C ,所有数据都会追加到文件中。

But right now, I dont see anything 但是现在,我什么都没看到

For append (you never want to cut the file), use >> ; 对于追加(您永远不想剪切文件),请使用>> to get the stderr too, use 2>&1 要也获得标准错误,请使用2>&1

exec /usr/bin/python /home/jhon/workspace/producer/test.py >> output 2>&1

and

import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write('a'*i)
    sys.stdout.flush()

> output 2>&1替换1>&2 output

 exec /usr/bin/python /home/jhon/workspace/producer/test.py > output 2>&1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM