有没有一种方法可以导入不存在的模块而不会出现错误?

时间:2020-08-31 05:11:38

标签: python module

我知道这听起来像元,但是,我正在尝试测试自己造成的模块错误,并尝试使python解释器在找不到该模块时跳过该模块。

我尝试过的代码:

if ModuleNotFoundError is blah:
print("blah blah blah")
while True:
    blah = input("Continue? (y or n)")
    if blah == "y":
        break
    if blah == "n":
        sys.exit("Game exited")
    else:
        pass

如果未找到,有一个选项可以跳过并继续。但是,当我尝试运行脚本时,这会在Windows Powershell中发生 输入:

 & C:/Users/sayne/AppData/Local/Programs/Python/Python38-32/python.exe "c:/Users/sayne/Documents/ireallylovecoding/python and practice/Interrogation/main.py"

输出:

ModuleNotFoundError: No module named 'blah'

有人可以帮助我吗? (P.S Blah是与我的main.py文件位于同一目录的python文件。)

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

try:
    import blah
    print('Do whatever you want to do if the module does import.')
except ImportError:
    print('Do whatever you want to do if the module does not import.')