如何在Python中有条件地导入模块?

2 投票
4 回答
926 浏览
提问于 2025-04-15 16:41

我想在C语言中做类似这样的事情:

#ifdef SOMETHING
do_this();
#endif

但是在Python中这样做就不太对劲:

if something:
    import module

我哪里出错了?这本来就不可能吗?

4 个回答

1

在Python中,有一个内置的功能叫做“异常”。这个功能可以帮助你处理程序运行中出现的问题,让你的程序更加稳定。

try:

    import <module>

except:     #Catches every error
    raise   #and print error

还有更复杂的用法,所以可以上网搜索一下更多的文档来了解。

1

如果你看到这个:

NameError: name 'something' is not defined

那么问题不在于 import 语句,而是在于你使用的 something 这个变量,显然你没有给它初始化。只需要确保它被设置为 True 或 False,就可以正常工作了。

18

这段代码应该没问题:

>>> 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)>

撰写回答