Is there a way to find out the name of the file stdout is redirected to in Python

Question:

I know how to detect if my Python script’s stdout is being redirected (>) using sys.stdout.isatty() but is there a way to discover what it’s being redirected to?

For example:

python my.py > somefile.txt

Is there a way to discover the name somefile.txt on both Windows and Linux?

Asked By: Kev

||

Answers:

I doubt you can do that in a system-independent way. On Linux, the following works:

import os
my_output_file = os.readlink('/proc/%d/fd/1' % os.getpid())
Answered By: Igor Nazarenko

If you need a platform-independent way to get the name of the file, pass it as an argument and use argparse (or optparse) to read your arguments, don’t rely on shell redirection at all.

Use python my.py --output somefile.txt with code such as:

parser = argparse.ArgumentParser()
parser.add_argument('--output', # nargs='?', default=sys.stdout,
                    type=argparse.FileType('w'), 
                    help="write the output to FILE", 
                    metavar="FILE")

args = parser.parse_args()
filename = args.output.name

If knowing the name is optional and used for some weird optimization, then use Igor Nazarenko’s solution and check that sys.platform is 'linux2', otherwise assume that you don’t have the name and treat it as a normal pipe.

Answered By: Rosh Oxymoron