系統(tǒng):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命令行運(yùn)行結(jié)果:
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
教程對(duì)應(yīng)參數(shù)結(jié)果:
$ 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!
前兩個(gè)輸出都是沒(méi)有問(wèn)題,但是在第三個(gè)加入cat.py同目錄下的poem.txt參數(shù)的時(shí)候,卻提示了錯(cuò)誤,這個(gè)問(wèn)題是出在哪里呢?
python3中在命令行里使用(sys.argv)cat.py后面加參數(shù),提示錯(cuò)誤
拉風(fēng)的咖菲貓
2019-02-17 06:36:36