如何在Python中有条件地进行导入?
我想在C中做一些类似的事情:如何在Python中有条件地进行导入?,python,python-import,Python,Python Import,我想在C中做一些类似的事情: #ifdef SOMETHING do_this(); #endif 但在Python中,这并不是jive: if something: import module 我做错了什么?首先,这可能吗?它应该可以正常工作: >>> if False: ... import sys ... >>> sys Traceback (most recent call last): File "<stdin>
#ifdef SOMETHING
do_this();
#endif
但在Python中,这并不是jive:
if something:
import module
我做错了什么?首先,这可能吗?它应该可以正常工作:
>>> 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)>
它应该可以很好地工作:
>>> 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)>
Python中有一个名为Exception的内置特性。。适用于您的需求:
try:
import <module>
except: #Catches every error
raise #and print error
有更复杂的结构,所以在web上搜索更多文档。在Python中,有一个名为Exception的内置功能。。适用于您的需求:
try:
import <module>
except: #Catches every error
raise #and print error
有更复杂的结构,因此请在web上搜索更多文档。如果您得到以下信息:
NameError: name 'something' is not defined
这里的问题不是import语句,而是使用了一些东西,一个显然还没有初始化的变量。只要确保它被初始化为True或False,它就会工作。如果您得到以下信息:
NameError: name 'something' is not defined
这里的问题不是import语句,而是使用了一些东西,一个显然还没有初始化的变量。只要确保它被初始化为True或False,它就会工作。在C构造中,条件定义ifdef测试某个东西是否只存在,其中python表达式测试表达式的值是否为True或False,在我看来,另外还有两个非常不同的东西,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
hth在C构造中,条件define 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
hth包含一条错误消息会有帮助。包含一条错误消息会有帮助。