這裏是一個教程代碼Python中的字節:不明白這個使用sys模塊的
import sys
filename = 'poem.txt'
def readfile(filename):
#Print a file to standard output
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
if len(sys.argv) < 2:
print 'No action specified'
sys.exit() //<--This is where the error is occurring
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:] #fetches sys.argv[1] without first 2 char
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version: Prints the version number
--help: Displays this help'''
else:
print 'Unknown option'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
當我運行此代碼,這是出現錯誤:
Traceback (most recent call last):
File "C:/Python/sysmodulepr.py", line 17, in <module>
sys.exit()
SystemExit
我不明白爲什麼。請幫忙。
你可以檢查[這個問題](http://stackoverflow.com/questions/1187970/how-to-exit-from-python-without-traceback)退出沒有回溯 – osoner 2011-12-30 17:00:07
我試着運行這段代碼,並且沒有出現「錯誤」。下面的答案正確地將其識別爲一個'SystemExit'異常,這實際上不是一個錯誤,而是(有效)一個鉤子,允許您在程序退出前進行清理。但通常'SystemExit'異常不會產生像這樣的回溯。有一些奇怪的事情發生在這裏... – senderle 2011-12-30 17:09:49
你使用什麼版本的Python?這不是一個正常的Python安裝,對吧? – 2011-12-30 17:10:27