[问题 - 加载模块]如何加载上层目录的模块??

2013-10-23 18:19:49 +08:00
 1989922yan
假如这样的目录结构:

/test_root
....test.py
..../test_sub
........test_sub.py
........__init__.py


在test_sub.py中,如何加载上层目录中的 test.py??

1. 直接,import test,这样会报错
2. 我的__init__.py文件为空,是否可以通过修改__init__.py文件,动态加载呢???

THX every answer!!
4469 次点击
所在节点    Python
7 条回复
mozillazg
2013-10-23 19:47:09 +08:00
试试 from .. import test
1989922yan
2013-10-23 21:20:49 +08:00
@mozillazg 我追加了内容,那个好像是不行的,能再帮看看吗??
SErHo
2013-10-23 21:31:28 +08:00
@1989922yan test 里面有没有 __init__.py 文件?
forgetbook
2013-10-23 22:35:33 +08:00
import sys
sys.path.append("..")
import test

不用谢。
话说回来,居然在这楼里看到故人了
dexbol
2013-10-23 22:45:50 +08:00
同为新手,特别能体会到你的迷惑。

首先 `test_root` 下添加 __init__.py 是必须的,这样才能形成package的一个层级。

然后你基本有两张方法搞定它:

* 一种是相对路径。在test_sub.py 中这样引用test.py: `form .. import test` 然后将命令行当前目录更改到 test_root 的父目录,键入:

python -m test_root.test_sub.test.sub


* 或者绝对路径。 在test_sub.py 中键入

import sys
import os

sys.path.insert(0, os.path.dirname(__file__) + '.\..\..')

import test_root.test


详细可参考这些:
http://docs.python.org/2/tutorial/modules.html#intra-package-references
http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python
1989922yan
2013-10-23 23:19:32 +08:00
@SErHo 有的。是一个空文件。
1989922yan
2013-10-25 00:49:57 +08:00
@dexbol 第二种方法,我没试成功。

我觉得还有__import__这个函数,可以用,这个也很好用

谢谢T_T

要是你也做web.py,咱们也能交流

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

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

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

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

© 2021 V2EX