从子目录或相对路径导入包 [英] importing a package from a subdir or relative path

查看:106
本文介绍了从子目录或相对路径导入包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的目录设置:

mydir
├── script1.py
└── shared
    ├── otherstuff
    ├── script2.py
    └── pkg
        ├── box.py
        └── __init__.py

script2.py

import pkg 

,效果很好.当我在script1.py中包含同一行时,我得到:

and it works great. When I include the same line in script1.py, I get:

Traceback (most recent call last):
  File "script1.py", line 1, in <module>
    import pkg

是否有什么好方法可以使在script1.py中使用的语法简单?在过去的一个小时中,我一直在阅读有关PYTHONPATHsys.path的信息,但是我正在尝试为我的仓库提供一些基本功能,而且我不相信它每次需要时都需要修改PYTHONPATH运行脚本.

Is there any good way to get syntax that simple to work in script1.py? I have been reading about PYTHONPATH and sys.path for the past hour, but I'm trying to make some basic functions available to my repo, and I can't believe that it will require modifying PYTHONPATH everytime I want to run a script.

我在这里想念什么?将pkg放入script1.py的最佳方法是什么?

What am I missing here? What's the best way to get pkg into script1.py?

推荐答案

您必须这样做:

from shared import pkg

此外,您的shared目录应具有__init__.py文件

Also, your shared directory should have an __init__.py file

这篇关于从子目录或相对路径导入包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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