有一種情況,我必須在運行我的腳本時告訴用戶他/她哪里出錯了,為此,我想在遇到例外時告訴自定義訊息。
我試圖做:
try:
module = __import__(module_name)
return module
except ModuleNotFoundError:
raise ModuleNotFoundError('\nCould not load module script. \nModule "%s" was not found in the current directory. \nTry using --help for help.\n' % (module_name))
這里的輸出混淆了實際錯誤的用戶,因為訊息“在處理上述例外期間,發生了另一個例外”。
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ModuleNotFoundError: No module named 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ModuleNotFoundError:
Could not load module script.
Module "a" was not found in the current directory.
Try using --help for help.
我需要的只是底部部分,或者是自定義訊息本身。
我不能只列印該訊息,因為我必須停止腳本的功能并出現此錯誤。有沒有辦法解決??
使用 sys.exit() 很好,但我還需要一個正式的方法。
我推薦的是這樣的:
import pathlib, os
module = input()
path = os.getcwd()
module_name = pathlib.Path(module).stem
module_path = os.path.dirname(module)
class ModuleUnavailableError(ModuleNotFoundError):
def __str__(self):
return "ModuleUnavailableError: The module %s located at %s was not found at %s." % (module_name, module_path, path)
__import__.Exception = ModuleUnavailableError
module = __import__(module_name)
當未找到該模塊時,將引發此例外及其訊息:
ModuleUnavailableError: The module alpha located at /home/user/bin/python/lib was not found at /home/user/games/Dumbledore/
uj5u.com熱心網友回復:
你可以只是print
你的訊息,然后exit
:
module_name = 'a'
try:
module = __import__(module_name)
return module
except ModuleNotFoundError:
print('\nCould not load module script. \nModule "%s" was not found in the current directory. \nTry using --help for help.\n' % (module_name))
sys.exit()
輸出:
Could not load module script.
Module "a" was not found in the current directory.
Try using --help for help.
uj5u.com熱心網友回復:
有關許多選項,請參閱例外鏈接。最后一個可能是您正在尋找的:
您可以列印一條訊息并傳遞例外:
>>> try:
... module = __import__('missing')
... except ModuleNotFoundError:
... print('missing module not found')
... raise
...
missing module not found
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ModuleNotFoundError: No module named 'missing'
您可以鏈接例外:
>>> try:
... import missing
... except ModuleNotFoundError as e:
... raise ValueError('wrong import') from e
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ModuleNotFoundError: No module named 'missing'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: wrong import
您可以引發不同的例外并抑制原始例外:
>>> try:
... import missing
... except ModuleNotFoundError as e:
... raise ModuleNotFoundError(f'where was the darn {e.name} module???') from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ModuleNotFoundError: where was the darn missing module???
exception( e
) 中可用的引數可能會有所不同。aprint(dir(e))
中except
可以看到有什么可用的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494838.html