Python stdin filename

后端 未结 4 670
难免孤独
难免孤独 2020-12-19 05:21

I\'m trying to get the filename thats given in the command line. For example:

python3 ritwc.py < DarkAndStormyNight.txt

I\'m

相关标签:
4条回答
  • 2020-12-19 05:57

    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.

    0 讨论(0)
  • 2020-12-19 05:59

    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.

    0 讨论(0)
  • 2020-12-19 06:00

    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()
    
    with open(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

    0 讨论(0)
  • 2020-12-19 06:04

    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=0
    for arg in sys.argv:
        if flag:
            filename_in = arg
            break
        if arg=="-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.

    0 讨论(0)
提交回复
热议问题