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:
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: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.