In python3, use (sys.argv) cat.py on the command line followed by a parameter to indicate an error

system: windows
IDLE:spyder
python3

-sharp!/usr/bin/python
-sharp Feilname:cat.py

import sys

def readfile(filename):
    """Print a file to the standard output."""
    f = open(filename)
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line,) -sharp Notice comma
    f.close

-sharp Script starts from here
if len(sys.argv) < 2:
    print("No action specified.")
    sys.exit()
    
if sys.argv[1].startswith("--"):
    option = sys.argv[1][2:]
    -sharp fetch sys.argv[1] but without the first two characters
    if option == "version":
        print("Version1.2")
    elif option == "help":
        print("""\
        This is progarm prints files to the standard ouput.
        Any number of files can be specified.
        Options inculde:
        --Version:Prints the version number
        --help :Dispay this help""")
    else:
        print("Unknown option.")
    sys.exit()
else:
    for filname in sys.argv[1:]:
        readfile(filename)    

cmd command line run result:

D:\python-spyder>python cat.py
No action specified.

D:\python-spyder>python cat.py --version
Version1.2

D:\python-spyder>python cat.py poem.txt
Traceback (most recent call last):
  File "cat.py", line 38, in <module>
    readfile(filename)
NameError: name "filename" is not defined

tutorial corresponding parameters result:

$ python cat.py
No action specified.

$ python cat.py --version
Version 1.2

$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

the first two outputs are fine, but when the third one adds the poem.txt parameter in the same directory as cat.py, it prompts an error. What is the problem?

Apr.04,2022

Oolong, I eliminated it myself, and I found that the problem was

.
else:
    for filname in sys.argv[1:]:
        readfile(filename) 

filname mistyped, changed to filename.
and then followed by the file name, ok

Menu