2016-04-12 25 views
0

您好,我試圖讓「嘗試」只有一個條件下工作:的Python嘗試用一些額外的邏輯

try: 
    print "Downloading URL: ", url 
    contents = urllib2.urlopen(url).read() 
except: 
    message = "No record retrieved." 
    print message 
    return None 

我不想讓上面的代碼工作,如果kwarg nodownload爲True。

所以我曾嘗試以下:

try: 
    if nodownload: 
     print "Not downloading file!" 
     time.sleep(6) 
     raise 
    print "Downloading URL: ", url 
    contents = urllib2.urlopen(url).read() 
except: 
    message = "No record retrieved." 
    print message 
    return None 

總是以上,如果--nd參數在命令行通過下載不管。下面的代碼總是跳過文件,而不是傳遞參數。

if not nodownload: 
     print "Not downloading file!" 
     time.sleep(6) 
     raise 
    print "Downloading URL: ", url 
    contents = urllib2.urlopen(url).read() 
except: 
    message = "No record retrieved." 
    print message 
    return None 

沒有下載是在命令行輸入:

parser.add_argument('--nodownload', dest='nodownload', action='store_true', 
        help='This doesn't work for some reason') 
+1

'如果不是nodownload:'? –

+0

我沿着這些線路嘗試了一些東西,但失敗了。午餐後我會發布更新的代碼。謝謝。 – CodeHard

+0

請製作[mcve]。目前還不清楚'nodownload'變量來自哪裏。 –

回答

1

您可以使用raise引起的異常,當你需要,從而使try失敗。

0

正如其他人所說的,人們可以提出一個例外。

除了使用預定義異常,你也可以使用自己:

class BadFriend(Exception): 
    pass 


class VirtualFriend(Exception): 
    pass 


class DeadFriend(Exception): 
    pass 


try: 
    name = raw_input("Tell me name of your friend: ") 
    if name in ["Elvis"]: 
     raise DeadFriend() 
    if name in ["Drunkie", "Monkey"]: 
     raise BadFriend() 
    if name in ["ET"]: 
     raise VirtualFriend() 
    print("It is nice, you have such a good friend.") 
except BadFriend: 
    print("Better avoid bad friends.") 
except VirtualFriend: 
    print("Whend did you shake hands with him last time?") 
except DeadFriend: 
    print("I am very sorry to tell you, that...") 

你甚至可以通過提出異常傳遞一些數據,但要小心,不要濫用它太遠(如果 標準結構工作,使用更簡單的)。