3

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!

Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
Viks
  • 760
  • 4
  • 12
  • 26

2 Answers2

2

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!
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

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
Ehtesh Choudhury
  • 7,452
  • 5
  • 42
  • 48
  • This works if it is run from python shall, but if it is called from subprocess.call(), It didnt work, IT still logs the data to the log file specified through the subprocess.call – Viks Jan 07 '14 at 23:39
  • You should remove the redirection of stdout and stderr in your subprocess.call() method. So use `subprocess.call("1.py",shell=True) ` – Ehtesh Choudhury Jan 08 '14 at 03:53