Capturing output from an infinite cycle
Hi,
I tried to run a simple script: run_forever.py
import time
i = 0
while True:
time.sleep(1)
print(i)
i += 1
with sarge as described in the docs:
In [1]: import sarge
In [2]: p = sarge.run('python run_forever.py', async=True, stdout=sarge.Capture())
However, I can't capture the output:
In [3]: p.stdout.readline()
Out[3]: b''
In [4]: p.commands[0].stdout.readline()
Out[4]: b''
Am I doing it wrong? How can I achieve that?
Comments (7)
-
repo owner -
repo owner - changed status to resolved
You can dispense with the
-u
if you insert asys.stdout.flush()
after theprint()
inrun_forever.py
. So, it's not a bug insarge
. -
repo owner - changed status to invalid
-
reporter Thanks for the clarification!
-
repo owner No problem. See the docs about buffering.
-
reporter Just want to add 2 cents - I have to call
python -u read_forever.py
or addsys.stdout.flush()
aftersys.stdout.write
inread_forever.py
to get the output (I'm using python 3.3.4). -
repo owner I'm surprised, though you do have to add a
.decode('utf-8')
for Python 3 on the results ofc.readline()
because that is a byte-string. It works fine (on Python 3.4 - I don't have 3.3 installed) with just thedecode()
added, and usingsys.executable
to invokerun_forever
with the same interpreter asread_forever
.$ python3.4 read_forever.py running: /usr/local/bin/python3.4 run_forever.py 11:42:58: 0 11:42:59: 1 11:43:00: 2 11:43:01: 3 11:43:02: 4
- Log in to comment
I think it's a buffering issue. With your
run_forever
script, the following script illustrates what you need to do:Note the use of
-u
to run Python unbuffered in the child process.When I run this, I get the following output: