2013-12-09 54 views
-5

我有行之有效以下Python代碼:的Python如果在try和除其他

try: 
    with urlopen("http://my.domain.com/get.php?id=" + id) as response: 
     print("Has content" if response.read(1) else "Empty - no content") 
except: 
    print("URL Error has occurred") 

但是我想在try內的if else語句改變這樣的:讓我能運行額外的代碼,而不是僅僅顯示一條消息

try: 
    with urlopen("http://my.domain.com/get.php?id=" + id) as response: 
     if response.read(1): 
      print("Has content") 
     else: 
      print("Empty - no content") 
except: 
    print("URL Error has occurred") 

但上面不工作,給人以縮進

任何想法有什麼不對相關的錯誤?

+0

嘗試刪除try-except塊並運行try:語句後面的代碼。你會看到有什麼問題。 – leeladam

+2

你錯過了「有內容」 – njzk2

+2

的引號,定義'not working' – njzk2

回答

1

你可以把異常到一個變量和打印太

except Exception as e: 
    print("Error has occurred", e) 

如果縮進看起來像原來的問題,那可能是你的問題 - 混合標籤與空間

+0

你是正確的有一些空間,我認爲在標籤中,所以我把所有的東西都拿出來,重新縮進,並解決了問題。 – John

0

您在第一個if中缺少引號。應該

if response.read(1): 
    print("Has content") 
0

你可以嘗試else子句來運行代碼

http://docs.python.org/2/tutorial/errors.html

的嘗試... except語句有一個可選的else子句,當被 目前,必須遵守除條款之外的所有條款如果try子句不引發異常,則必須執行 代碼。對於 例如:

for arg in sys.argv[1:]: 
    try: 
     f = open(arg, 'r') 
    except IOError: 
     print 'cannot open', arg 
    else: 
     print arg, 'has', len(f.readlines()), 'lines' 
     f.close() 
0

你應該分開不同的區域,可能會發生異常與不同try塊。

具體而言,而不是將withtry塊環繞,請使用contextlib模塊來處理這些細節。這是直接從PEP 343,例6:

from contextlib import contextmanager 

@contextmanager 
def opened_w_error(filename, mode="r"): 
    try: 
     f = open(filename, mode) 
    except (IOError, err): 
     yield None, err 
    else: 
     try: 
      yield f, None 
     finally: 
      f.close() 

with opened_w_error('/tmp/file.txt', 'a') as (f, err): 
    if err: 
     print ("IOError:", err) 
    else: 
     f.write("guido::0:0::/:/bin/sh\n")