python中模块的相对路径

时间:2017-03-19 18:15:24

标签: python relative-path python-module python-packaging

我尝试了一些不同的技术试图做一些对我来说似乎可行的事情,但我想我错过了一些关于python的问题(使用2.7但是如果可能的话,我希望这也能用于3. *)。

我不确定包装或模块这样的术语,但对我而言,以下内容似乎非常简单"可行的情景。

这是目录结构:

.
├── job
│   └── the_script.py
└── modules
    ├── __init__.py
    └── print_module.py

the_script.py的内容:

# this does not work
import importlib
print_module = importlib.import_module('.print_module', '..modules')

# this also does not work
from ..modules import print_module

print_module.do_stuff()

print_module的内容:

def do_stuff():
    print("This should be in stdout")

我想运行所有这些"相对路径"东西:

/job$ python2 the_script.py

但是importlib.import_module会出现各种错误:

  • 如果我只使用1个输入参数..modules.print_module,那么我得到:TypeError("relative imports require the 'package' argument")
  • 如果我使用2个输入参数(如上例所示),那么我得到:ValueError: Empty module name

另一方面,我使用from ..modules语法得到:ValueError: Attempted relative import in non-package

我认为__init__.py空文件应足以将该代码限定为" packages" (或模块?不确定术语),但似乎有一些关于如何管理相对路径的遗漏。

我读到过去,人们使用path以及import osimport sys中的其他函数来攻击它,但根据官方文档(python 2.7和3. *)这不再需要了。

我做错了什么,怎样才能实现打印内容modules/print_module.do_stuff从#34;相对目录"中的脚本调用它的结果。 job/

3 个答案:

答案 0 :(得分:2)

如果您在此处遵循本指南的结构:http://docs.python-guide.org/en/latest/writing/structure/#test-suite(强烈建议您阅读所有内容,这非常有帮助)您会看到:

  

要为各个测试导入上下文,请创建tests / context.py文件:

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import sample
     

然后,在各个测试模块中,导入模块,如下所示:

from .context import sample
     

无论安装方法如何,这都将按预期工作。

在您的情况下翻译,这意味着:

root_folder
├── job
│   ├── context.py <- create this file
│   └── the_script.py
└── modules
    ├── __init__.py
    └── print_module.py

context.py文件中写下上面显示的行,但import modules代替import samples

最后在您的the_script.pyfrom .context import module中,您将开始行动!

祝你好运:)

答案 1 :(得分:2)

如果您对术语不确定,请转到非常好的教程:

http://docs.python-guide.org/en/latest/writing/structure/#modules

http://docs.python-guide.org/en/latest/writing/structure/#packages

但是对于你的结构:

.
├── job
│   └── the_script.py
└── modules
    ├── __init__.py
    └── print_module.py

the_script.py

中说
import sys
sys.append('..')
import modules.print_module

这会将父目录添加到PYTHONPATH,而python会看到目录&#39; parallel&#39;到工作目录,它会工作。

我认为在最基本的层面上,知道这一点是足够的:

  1. 是包含__init__.py文件
  2. 的任何目录
  3. 模块是一个.py的文件,但在导入模块时,省略了扩展名。

答案 2 :(得分:1)

我找到了使用sysos的解决方案。

脚本the_script.py应为:

import sys
import os
lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../modules'))
sys.path.append(lib_path)

# commenting out the following shows the `modules` directory in the path
# print(sys.path)

import print_module

print_module.do_stuff()

然后我可以通过命令行运行它,无论我在路径中的哪个位置,例如:

  • /job$ python2 the_script.py
  • <...>/job$ python2 <...>/job/the_script.py
相关问题