Apr 20, 2016

Disappearing Console Output Running Python Script In Remote Shell

Image result for python






If you're running a script that requires user input or prints useful information the console and you want to execute that script in a remote shell (eg. ssh or psexec), you may run into issues where you are unable to see the prompts or other information that should be printed to the console.

After some research and thanks to a post from CesarB over at stackoverflow.com on a related issue, I learned that this behavior is caused by stdout being buffered.

One way to resolve this is by adding the following code to the top of your script, somewhere after importing sys:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)


This will force stdout to flush throughout the entire script for immediate display to the console.

I run Python 2.7.11. If you are running Python 3.3 or later, you can flush without the need for this additional statement, as the print function now has a "flush" argument for this.

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Whether or not output is buffered is usually determined by file, but if the flush keyword argument is true, then the stream is forcibly flushed.



ref: http://stackoverflow.com/a/230774/6230542, CesarB
ref: https://docs.python.org/3.3/library/functions.html#print, Python 3