Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 887
Kev Avatar asked May 10 '11 00:05

Kev


2 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())
like image 180
Igor Nazarenko Avatar answered Nov 06 '22 02:11

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.

like image 28
Rosh Oxymoron Avatar answered Nov 06 '22 00:11

Rosh Oxymoron