代码之家  ›  专栏  ›  技术社区  ›  user225312

导入驻留在不相关路径中的文件

  •  2
  • user225312  · 技术社区  · 15 年前

    假设我有一个名为 root 它有两个目录: x y . 我有一个模块文件驻留在 ,我们称之为 test.py . 现在在 y ,我有一个模块需要调用

    我正在做一个简单的:

    from x import test

    而且很有效。我在想,这是怎么回事?

    编辑:它是如何工作的,就像在没有 __init__.py 文件输入 ,但从 我可以从那里呼叫一个模块。

    2 回复  |  直到 13 年前
        1
  •  1
  •   Jed Smith    15 年前

    没有。您或您的操作系统或Python站点启动脚本已经修改 PYTHONPATH .

    14:59 jsmith@upsidedown pwd
    /Users/jsmith/Test/Test2/root
    
    14:59 jsmith@upsidedown cat x/test.py
    def hello():
      print "hello"
    
    14:59 jsmith@upsidedown cat y/real.py
    #!/usr/bin/python
    from x import test
    test.hello()
    
    14:59 jsmith@upsidedown y/real.py
    Traceback (most recent call last):
      File "y/real.py", line 3, in <module>
        from x import test
    ImportError: No module named x
    
        2
  •  0
  •   Eric Palakovich Carr    15 年前

    因为有一条通往它的路。试试这个:

    import sys
    print sys.path
    

    它应该输出python用作解析模块位置的起始目录的所有位置。例如,如果 root

    ['', '/usr/local/lib/python2.6/dist-packages', *more stuff*, '/home/PulpFiction/root']
    

    ['', 'C:\\python26\\site-packages', *more stuff here*, 'C:\Documents and Settings\PulpFiction\My Documents\root']
    

    有几种方法 sys.path 可设置(据我所知):

    1. 运行脚本的目录
    2. 环境变量(确切地说是PYTHONPATH)
    3. Windows注册表(仅在Windows上)

    (比如说 main.py ),并且该脚本最终从两个 x y from x import test 去工作。

    编辑

    没有 __init__.py 嗯?你确定没有 __init__.pyc 有(注意pyc中的C)?