2011-12-30 58 views
2

這裏是一個教程代碼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 

我不明白爲什麼。請幫忙。

+0

你可以檢查[這個問題](http://stackoverflow.com/questions/1187970/how-to-exit-from-python-without-traceback)退出沒有回溯 – osoner 2011-12-30 17:00:07

+0

我試着運行這段代碼,並且沒有出現「錯誤」。下面的答案正確地將其識別爲一個'SystemExit'異常,這實際上不是一個錯誤,而是(有效)一個鉤子,允許您在程序退出前進行清理。但通常'SystemExit'異常不會產生像這樣的回溯。有一些奇怪的事情發生在這裏... – senderle 2011-12-30 17:09:49

+1

你使用什麼版本的Python?這不是一個正常的Python安裝,對吧? – 2011-12-30 17:10:27

回答

3

它告訴你sys.exit()已經在程序的第17行上執行了。

The entry for for sys.exit in the Python documentation告訴你,這退出你的程序。

這行不能執行沒有產生其他輸出,所以我認爲這是缺少的問題。

+2

這受到[SystemExit](http://docs.python.org/library/exceptions.html#exceptions.SystemExit)文檔的支持:「當它不被處理時,Python解釋器退出;沒有堆棧回溯被打印「。 – 2011-12-30 17:07:47

1

這不是一個錯誤。 sys.exit()引發SystemExit破例允許try:... finally塊清理使用的資源

嘗試在空閒:

import sys 

sys.exit() 

從文檔sys.exit():從Python的

退出。這是通過引發SystemExit異常實現的,所以try語句的finally子句指定的清理操作得到遵守,並且可以在外層攔截退出嘗試。

編輯

不能正常打印的錯誤,除非你想運行在一些交互式解釋腳本(例如空閒)。 沒什麼好擔心的,但腳本看起來像是獨立的,所以你應該這樣使用它。

2

如果您使用IDLE,它將打印堆棧。嘗試從命令行運行腳本,在IDE外部執行時不會打印該錯誤消息。