python 导包问题求助~

2016-09-19 10:43:49 +08:00
 kysida
目录层级如下:
[root@localhost auto]# tree
.
├── bin
│   ├── __init__.py
│   ├── publish
│   │   ├── __init__.py
│   │   └── test.py
│   ├── ros
│   │   ├── __init__.py
│   │   └── ros.py
│   └── test.py
├── controllers
│   ├── Apiactions.py
│   └── __init__.py
├── __init__.py
├── public
│   ├── conf
│   │   └── __init__.py
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── library
│   │   ├── Gitclone.py
│   │   ├── __init__.py
│   │   └── Print.py
│   ├── modules
│   │   └── __init__.py
│   ├── test.py
│   └── test.pyc
├── tmp
│   ├── gitwarehouse
│   │   └── __init__.py
│   └── resources
│   └── __init__.py
└── ymlmodules
└── publish

目的:在 bin/publish/test.py 中导入 public/library/Print.py
原来做法两层目录够用:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
现在多一层次导入失败
1767 次点击
所在节点    Python
9 条回复
kysida
2016-09-19 11:30:21 +08:00
找不到简单的办法目前只能用笨办法了。。。。~~~~(>_<)~~~~
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
csdreamdong
2016-09-19 11:36:16 +08:00
最大的根目录,是 auto 目录嘛?
感觉你这个 auto 目录就是一个包啊。
auto.public.library.Print
一直点下来不能么?
kysida
2016-09-19 13:52:58 +08:00
@csdreamdong 这个 auto 并不是根目录,在 test.py 里面使用 auto 提示 no module named auto
yangtukun1412
2016-09-19 16:32:51 +08:00
包内引用还是用 relative import 方便点. 修改 sys.path 的方式总感觉不是很优雅.
kinghui
2016-09-19 16:42:30 +08:00
没看到你描述如何运行的 test.py,猜测应是

$ cd bin/publish && python test.py

其实你的 auto 整个就是一个包, 如果你在 bin/publish/test.py 是通过如下方式导入 public/library/Print.py

from auto.public.library import Print

那么其实你可以跳到上层目录执行:

$ python -m auto.bin.publish.test

如果你是通过如下方式导入

from auto.public.library import Print

那么你可以执行

$ python -m auto.bin.publish.test

来运行.
kinghui
2016-09-19 16:43:54 +08:00
@kinghui

修正一下
-----------

如果你是通过如下方式导入

from auto.public.library import Print

那么你可以执行

$ python -m bin.publish.test

来运行.
kysida
2016-09-19 16:55:41 +08:00
@yangtukun1412 relative import 是优雅点,但是运用很容易出错
kysida
2016-09-19 17:35:57 +08:00
@kinghui 这样做的话用户会比较麻烦,我现在写了个地址处理的方法,还算是比较简单
kinghui
2016-09-19 17:43:17 +08:00
@kysida 为什么源代码还涉及用户呢, 嫌复杂可以使用 Makefile 隐藏复杂性

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/307180

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX