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)
If you are in control of what's in 1.py
, you could have your own instances of stdout
and stderr
You could alternatively, not redirect stdout/stdin in for 1.py
, and instead pass fout/ferr
to it as parameters. something like:
# assuming python 2.7.x
from __future__ import print_function
import argparse
import sys
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--stdout'
, nargs='?'
, type=argparse.FileType('a')
, default=sys.stdout)
parser.add_argument( '--stderr'
, nargs='?'
, type=argparse.FileType('a')
, default=sys.stderr)
namespace = parser.parse_args()
print("Hello There", file=namespace.stdout)
print("Error time", file=namespace.stderr)
print("Always to stdout")
print("Always to stderr", file=sys.stderr)
And then run it like so:
python 1.py --stdout=outfile.log stderr=errfile.log
To call from subprocess
:
subprocess.call("1.py",shell=True) # no need to redirect stdout and stderr now
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!