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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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!

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x