我想在 C 中做这样的事情:
#ifdef SOMETHING
do_this();
#endif
但在 Python 中,这并不能解决问题:
if something:
import module
我究竟做错了什么?首先这可能吗?
我想在 C 中做这样的事情:
#ifdef SOMETHING
do_this();
#endif
但在 Python 中,这并不能解决问题:
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)>
如果你得到这个:
NameError: name 'something' is not defined
那么这里的问题不在于import
语句,而在于使用something
显然尚未初始化的变量。只要确保它被初始化为 True 或 False,它就会工作。
在C构造中,条件定义#ifdef测试是否仅存在“SOMETHING”,您的python表达式测试表达式的值是True还是False,在我看来是两个非常不同的东西,此外,C构造是在编译时评估。
正如其他人已经指出的那样,基于您原始问题的“某事”必须是一个(存在并且)评估为真或假的变量或表达式,问题可能在于未定义该“某事”变量。所以python中的“最接近的等价物”是这样的:
if 'something' in locals(): # or you can use globals(), depends on your context
import module
或(hacky):
try:
something
import module
except NameError, ImportError:
pass # or add code to handle the exception
hth
在 Python 中有一个名为“异常”的内置功能。适用于您的需求:
try:
import <module>
except: #Catches every error
raise #and print error
有更复杂的结构,因此请在网络上搜索更多文档。