2009-12-04 21 views
1

我想要做這樣的事情在C:如何在Python中有條件地導入?

#ifdef SOMETHING 
do_this(); 
#endif 

但是在Python這並不合拍:

if something: 
    import module 

我在做什麼錯?這首先可能嗎?

+1

這將有助於包括錯誤消息。 – 2009-12-04 14:36:13

回答

17

它應該很好地工作:

>>> if False: 
...  import sys 
... 
>>> sys 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'sys' is not defined 
>>> if True: 
...  import sys 
... 
>>> sys 
<module 'sys' (built-in)> 
0

在Python有一個內置的功能,稱爲「異常」 ..適用於您的需求:

try: 

    import <module> 

except:  #Catches every error 
    raise #and print error 

還有更復雜的結構,以便搜索一下網絡獲取更多文檔。

0

如果您收到這樣的:

NameError: name 'something' is not defined 

那麼這裏的問題是不是與import語句,但隨着使用something,你顯然沒有初始化的變量。只要確保它已被初始化爲True或False,它就可以工作。

0

在C結構,條件界定的#ifdef測試「東西」是否只,其中存在的Python表達式測試表達式的值是否無論是真是假,在我看來,兩個非常不同的東西,另外,C編譯器在編譯時進行評估。

基於你的原始問題的「東西」必須是一個變量或表達式(存在和)的計算結果爲真或假,正如其他人已經指出的那樣,問題可能與「某事」變量沒有被定義。因此, 「最接近的」 在Python會是這樣的:

if 'something' in locals(): # or you can use globals(), depends on your context 
    import module 

或(哈克):

try: 
    something 
    import module 
except NameError, ImportError: 
    pass # or add code to handle the exception 

心連心