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?
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())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With