Python stdin filename

filenames, python, stdin

Solution

In general it is not possible to obtain the filename in a platform-agnostic way. The other answers cover sensible alternatives like passing the name on the command-line.

On Linux, and some related systems, you can obtain the name of the file through the following trick:

import os
print(os.readlink('/proc/self/fd/0'))

`/proc`/ is a special filesystem on Linux that gives information about processes on the machine. `self` means the current running process (the one that opens the file). `fd` is a directory containing symbolic links for each open file descriptor in the process. 0 is the file descriptor number for `stdin`.

Problem

I'm trying to get the filename thats given in the command line. For example: python3 ritwc.py < DarkAndStormyNight.txt I'm trying to get DarkAndStormyNight.txt When I try fileinput.filename() I get back same with sys.stdin. Is this possible? I'm not looking for sys.argv[0] which returns the current script name. Thanks!

Original source