Sys.path.insert插入模块的路径,但是导入不起作用 [英] Sys.path.insert inserts path to module but imports are not working

查看:1372
本文介绍了Sys.path.insert插入模块的路径,但是导入不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在项目中导入模块,由于导入错误,这给我带来很多麻烦.因此,我决定编写一个小测试以查看问题所在.我将文件夹添加到sys路径,然后尝试导入它.然后我得到一个Import Error: no module found named xyz

I want to import a module in a project and it gives me lots of troubles because of an import error. So I decided to write a little test to see where the problem lies. I add a folder to my sys path and try to import it. And I get an Import Error: no module found named xyz

像这样:

import sys
import os

sys.path.insert(0, os.path.abspath('../../myfolder'))
import myfolder
print(sys.path)

sys.path是['/Users/myuser/myproject/mywebsitefolder/myfolder/', ...]

The sys.path is ['/Users/myuser/myproject/mywebsitefolder/myfolder/', ...]

myfolder包含一个__init__.py文件.对myfolder的路径进行硬编码具有相同的结果.网络上的其他问题可以通过添加正确的路径或添加init来解决问题.但我同时认为,问题仍然存在.

myfolder contains an __init__.py file. Hardcoding the path to myfolder has same results. Other questions on the web solve the problem by either adding the correct path or by adding an init. But I have both I think and the problem remains.

我的印象是python在系统路径中查找可导入模块,还是我误解了它应该如何工作?

I was under the impression that python looks in the system path for importable modules or do I misunderstand how this is supposed to work?

如果我理解正确,有什么办法可以进一步调试它?还是这可能是python版本的问题?

If I understand correctly, is there any way I can debug this further? Or could this be a problem with python versions?

非常感谢您的帮助.预先感谢!

Help is very much appreciated. Thanks in advance!

这是我的目录结构

  • mywebsitefolder
    • 我的文件夹
      • api_supply
        • 测试(包含所有文件的所有测试)
        • 初始化 .py
        • serializers.py
        • urls.py
        • views.py
        • mywebsitefolder
          • myfolder
            • api_supply
              • tests (contains all my tests with many files)
              • init.py
              • serializers.py
              • urls.py
              • views.py
              • 测试(包含所有文件的所有测试)
              • 初始化 .py
              • serializers.py
              • urls.py
              • views.py
              • tests (contains all my tests with many files)
              • init.py
              • serializers.py
              • urls.py
              • views.py

              推荐答案

              替换代码,因为您不需要将文件夹添加到路径中,所有您需要的是文件夹路径

              Replace the code as this you dont need to add the folder to the path all you need is the path to the folder

              import sys
              import os
              
              sys.path.insert(0, os.path.abspath('../../'))
              import myfolder
              print(sys.path)
              

              这篇关于Sys.path.insert插入模块的路径,但是导入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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