Is there any way to find out the file name, stdout is redirected in Python

I know how to determine if my Python script stdout ( > ) is being sys.stdout.isatty() using sys.stdout.isatty() , but is there any way to find out what it is redirected to?

For instance:

  python my.py> somefile.txt 

Is there a way to find out the name somefile.txt for Windows and Linux?

+6
source share
2 answers

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

 import os my_output_file = os.readlink('/proc/%d/fd/1' % os.getpid()) 
+10
source

If you need a platform-independent way to get the file name, 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, for example:

 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 knowledge of the name is optional and used for some strange optimization, then use Igor Nazarenko’s solution and make sure sys.platform is 'linux2' , otherwise suppose you don’t have a name and treat it like a regular channel.

+1
source

Source: https://habr.com/ru/post/887674/


All Articles