zakoda zakoda - 4 months ago 6
Python Question

Output to two different consoles using python

I am writing a script and I have two different kinds of output, say Op1 and Op2. I want to output Op1 to the terminal where the python process was called from while Op2 should be dumped to a different terminal instance. Can I do that?

Even if the answer is Linux-specific it's okay, I need a temporary solution.

Answer

You can make the Python script write to a file, or pipe its output to a file python script.py >> output.log, then you can tail the file with -f which makes it continuously update the view on your console.

Example snippet

# logmaker.py
import time
import datetime

buffer_size = 0 # This makes it so changes appear without buffering
with open('output.log', 'a', buffer_size) as f:
    while(True):
        f.write('{}\n'.format(datetime.datetime.now()))
        time.sleep(1)

Run that file

python logmaker.py

Then in one or more consoles do

tail -f output.log

or less if you prefer

less +F output.log

You should get a continuous update like this

2016-07-06 10:52:44.997416
2016-07-06 10:52:45.998544
2016-07-06 10:52:46.999697
Comments