Python output to Console within Subprocess from the child scricpt
in my parent script, I do the following:
fout=open(outfile,"w")
ferr = open(errfile,"w")
subprocess.call("1.py",stdout=fout,stderr=ferr,shell=True)
In the 1.py
, script, I want most of the log message to go to log file, but some messages, I want to print on Console, based on the Print Conditions:
print "Hello World"
but it is printing to outfile, which I wanted to print on console as well, I tried doing
sys.__stdout__.write("Hello World");
but that aslso doesn't work. Any help would be appreciated!
Solution 1:
If stdout, stderr are redirected then you could try to print directly to the console:
try: # Windows
from msvcrt import putwch
def print_to_console(message):
for c in message:
putwch(c)
# newline
putwch('\r')
putwch('\n')
except ImportError: # Unix
import os
fd = os.open('/dev/tty', os.O_WRONLY | os.O_NOCTTY)
tty = os.fdopen(fd, 'w', 1)
del fd
def print_to_console(message, *, _file=tty):
print(message, file=_file)
del tty
Example:
print_to_console("Hello TTY!")
# -> Hello TTY!