简体   繁体   English

标准输出未写入文件?

[英]Stdout not being written to file?

I'm having trouble with something here, and I don't know whats going on. 我在这里遇到问题,我不知道发生了什么。

I have a python script test.py that connects to my server, gets some information, then prints this information (in an infinite loop, essentially). 我有一个python脚本test.py连接到我的服务器,获取一些信息,然后打印此信息(本质上是无限循环)。

I also have a bash script starter.sh as follows: 我也有一个bash脚本starter.sh,如下所示:

#!/bin/bash

if [ ! `pgrep python` ]; then
    cd /home/user/test
    python test.py
fi

When I run it from the terminal, everything is fine and works as expected. 当我从终端运行它时,一切都很好并且可以按预期工作。 It simply writes some text to the console. 它只是将一些文本写入控制台。

The problem happens when I involve cron jobs. 当我涉及cron工作时,就会发生问题。

I have the following cron job: 我有以下cron工作:

*/1 * * * * /home/user/test/starter.sh >> /home/user/test/log.txt 2>&1

When cron job runs (and I know it runs because I check my server and it receives a connection, a request for data, and then sends the data. 当cron作业运行时(并且我知道它在运行,因为我检查我的服务器并且它接收到连接,对数据的请求,然后发送数据)。

I want to log whatever my python script prints though. 我想记录我的python脚本打印的内容。 But nothing is being written to the log?? 但是什么也没有写到日志中? What do I do 我该怎么办

EDIT: Simply running python test.py>>echo.txt or python test.py>echo.txt doesnt seem to work either. 编辑:简单地运行python test.py >> echo.txt或python test.py> echo.txt似乎也不起作用。

I'm using pythons print function to print data 我正在使用pythons打印功能来打印数据

Ok, I seem to figured out the issue (if anyone else happens to have this same problem). 好的,我似乎已经弄清楚了这个问题(如果其他任何人碰巧也遇到同样的问题)。 The problem is print in python 2.7 doesn't flush stdout. 问题是在python 2.7中打印不会刷新标准输出。 by running python -u test.py this solves the problem and works fine 通过运行python -u test.py可以解决问题并可以正常工作

from man, here is what the -u switch does: 来自man,这是-u开关的作用:

-u Force stdin, stdout and stderr to be totally unbuffered. -u强制完全禁止stdin,stdout和stderr。 On systems where it matters, also put stdin, stdout and stderr in binary mode. 在重要的系统上,还将stdin,stdout和stderr置于二进制模式。 Note that there is internal buffering in xread- lines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. 请注意,xread-lines(),readlines()和文件对象迭代器(“ sys.stdin中的行”)具有内部缓冲,该缓冲不受此选项的影响。 To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop 若要解决此问题,您将需要在“ while 1:”循环内使用“ sys.stdin.readline()”

I'm also a starter @ bash scripting.It should work i guess 我也是bash scripting的入门者。

#!/bin/bash

if [ ! `pgrep python` ]; then
    cd /home/user/test
    python test.py >> /home/user/test/log.txt
fi

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

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