Python Stdin Filename
Solution 1:
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 osprint(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
.
Solution 2:
You can use ArgumentParser
, which automattically gives you interface with commandline arguments, and even provides help, etc
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('fname', metavar='FILE', help='file to process')
args = parser.parse_args()
withopen(args.fname) as f:
#do stuff with f
Now you call python2 ritwc.py DarkAndStormyNight.txt
. If you call python3 ritwc.py
with no argument, it'll give an error saying it expected argument for FILE
. You can also now call python3 ritwc.py -h
and it will explain that a file to process
is required.
PS here's a great intro in how to use it: http://docs.python.org/3.3/howto/argparse.html
Solution 3:
In fact, as it seams that python cannot see that filename when the stdin is redirected from the console, you have an alternative:
Call your program like this:
python3 ritwc.py -i your_file.txt
and then add the following code to redirect the stdin from inside python, so that you have access to the filename through the variable "filename_in":
import sys
flag=0forargin sys.argv:
if flag:
filename_in = argbreakifarg=="-i":
flag=1
sys.stdin = open(filename_in, 'r')
#the rest of your code...
If now you use the command:
print(sys.stdin.name)
you get your filename; however, when you do the same print command after redirecting stdin from the console you would got the result: <stdin>
, which shall be an evidence that python can't see the filename in that way.
Solution 4:
I don't think it's possible. As far as your python script is concerned it's writing to stdout. The fact that you are capturing what is written to stdout and writing it to file in your shell has nothing to do with the python script.
Post a Comment for "Python Stdin Filename"