如果从源目录导入,则捕获 python 'ImportError'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14750711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:19:26  来源:igfitidea点击:

Catch python 'ImportError' if import from source directory

pythonexception-handlingimporterror

提问by Julian

When one tries to import a module foowhile being in the source directory, one gets an rather confusing ImportErrormessage: ImportError: No module named foo.

foo在源目录中尝试导入模块时,会收到一条相当混乱的ImportError消息:ImportError: No module named foo.

How can I easily catch this case and return a more informative message, e.g. 'Please do not load module foo from the source directory'?

我怎样才能轻松地捕捉到这种情况并返回一条信息更丰富的消息,例如“请不要从源目录加载模块 foo”?

Having the __init__.py, I would start with:

有了__init__.py,我会开始:

try:
    from _foo import *
except ImportError:
    ## check whether in the source directory...

So I would like to distinguish the different causes for an ImportError(e.g. because a module named foois not installed at all), and detect the case in which the setup.pyis located in the current directory. What would be a elegant way of doing this?

所以我想区分不同的原因ImportError(例如因为foo根本没有安装一个名为的模块),并检测setup.py位于当前目录中的情况。这样做的优雅方式是什么?

采纳答案by isedev

ImportError: No module named fooactually means the module foo.pyor package foo/__init__.pycould not be found in any of the directories in the search path (sys.pathlist).

ImportError: No module named foo实际上意味着在搜索路径(列表)的任何目录中都找不到模块foo.py或包。foo/__init__.pysys.path

Since sys.pathusually contains .(the current directory), that's probably what you meant by being in the source directory. You are in the top-level directory of package foo(where the __init__.pyfile is) so obviously you can't find foo/__init__.py.

由于sys.path通常包含.(当前目录),这可能就是您在源目录中的意思。您位于包的顶级目录foo__init__.py文件所在的位置),因此显然您找不到foo/__init__.py.

Finally, you've answered your own question, more or less:

最后,您或多或少地回答了自己的问题:

try:
    from _foo import *
except ImportError:
    raise ImportError('<any message you want here>')

Alternatively, you could check the contents of sys.path, the current directory and, if known, the expected package directory and produce an even detailed and context-aware message.

或者,您可以检查 的内容sys.path、当前目录以及(如果知道)预期的包目录,并生成甚至详细且上下文感知的消息。

Or add ..to the PYTHONPATHenvironment variable (on Unix) to allow you to run from your source directory. Might even work on Windows, but I wouldn't know.

或者添加..PYTHONPATH环境变量(在 Unix 上)以允许您从源目录运行。甚至可能在 Windows 上工作,但我不知道。