Python stdin filename

后端 未结 4 672
难免孤独
难免孤独 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 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: , which shall be an evidence that python can't see the filename in that way.

提交回复
热议问题