如何解决python中的导入错误? [英] How to resolve import errors in python?

查看:132
本文介绍了如何解决python中的导入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定的问题,可能需要一般解决方案。我目前正在学习 apache thrift 。我使用了这个指南。我按照所有步骤和我收到导入错误,因为无法导入模块UserManager。所以问题是
如何进行python导入查找。首先检查哪个目录。它是如何向上移动的?

sys.path.append('')如何工作?


我找到了答案此处。我按照相同的步骤。但我仍然面临同样的问题。有什么想法吗?我应该提出的更多内容可以帮助调试你们。 ?

I have a specific problem which might require a general solution. I am currently learning apache thrift. I used this guide.I followed all the steps and i am getting a import error as Cannot import module UserManager. So the question being
How does python import lookup take place. Which directory is checked first. How does it move upwards?
How does sys.path.append('') work?

I found out the answer for this here. I followed the same steps. But i am still facing the same issue. Any ideas why? Anything more i should put up that could help debug you guys. ?

帮助表示赞赏。

推荐答案

在Windows上,Python看起来来自默认python路径中Lib文件夹的模块,例如来自C:\Python34 \Lib \。您可以在自定义文件夹(my-lib或sth。)中添加Python库,但是您需要一个文件来告诉Python您可以从那里导入。此文件名为 __ init __。py ,并且完全为空。该数据结构应如下所示:

On windows, Python looks up modules from the Lib folder in the default python path, for example from "C:\Python34\Lib\". You can add your Python libaries in a custom folder ("my-lib" or sth.) in there, but you need a file in order to tell Python that you can import from there. This file is called __init__.py , and is totally empty. That data structure should look like this:

my-lib

  • __ init __。py
  • / myfolder
  • mymodule.py

    my-lib

  • __init__.py
  • /myfolder
  • mymodule.py

    (这是每个Python模块的工作方式。例如urllib.request,它位于%PYTHONPATH%\ Lib \urllib \request.py)

    (This is how every Python module works. For example urllib.request, it's at "%PYTHONPATH%\Lib\urllib\request.py")

    您可以通过输入

    import my-lib
    

    然后使用

    mylib.mymodule.myfunction
    

    或者您可以使用

    from my-lib import mymodule
    

    然后只使用你的函数名称。

    And then just using the name of you function.

    你现在可以使用sys了.path.append将您传递给函数的路径追加到Python查找模块的文件夹中(请注意,这不是永久性的)。如果模块的路径应该是静态的,则应考虑将它们放在Lib文件夹中。如果该路径是相对于您的文件,您可以查找您执行的文件的路径,然后附加相对于您的文件的sys.path,但我建议使用相对导入。

    You can now use sys.path.append to append the path you pass into the function to the folders Python looks for the modules (Please note that thats not permanent). If the path of your modules should be static, you should consider putting these in the Lib folder. If that path is relative to your file you could look for the path of the file you execute from, and then append the sys.path relative to your file, but i reccomend using relative imports.

    如果您考虑这样做,我建议您阅读文档,您可以在此处执行此操作: https://docs.python.org/3/reference/import.html#submodules

    If you consider doing that, i recommend reading the docs, you can do that here: https://docs.python.org/3/reference/import.html#submodules

    这篇关于如何解决python中的导入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆