为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉风的咖菲猫 2019-02-17 06:36:36
系统:windowsIDLE:spyderpython3 #!/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参数的时候,却提示了错误,这个问题是出在哪里呢?
查看完整描述

1 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

乌龙了,自己排除法,结果发现问题是

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

filname打错,改为filename.
然后跟入文件名,ok了

查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 736 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信