python 命令行输入参数有误_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

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参数的时候,却提示了错误,这个问题是出在哪里呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值