python3中在命令行里使用(sys.argv)cat.py后面加参数,提示错误

系统:windows
IDLE:spyder
python3

#!/usr/bin/python
# 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,) # Notice comma
    f.close

# 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:]
    # 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命令行运行结果:

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

教程对应参数结果:

$ 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!

前两个输出都是没有问题,但是在第三个加入cat.py同目录下的poem.txt参数的时候,却提示了错误,这个问题是出在哪里呢?

拉风的咖菲猫
浏览 739回答 1
1回答

四季花海

乌龙了,自己排除法,结果发现问题是 else: for filname in sys.argv[1:]: readfile(filename) filname打错,改为filename.然后跟入文件名,ok了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python