简体   繁体   English

python:目录结构导入问题,使脚本和模块分开

[英]python: import problems with directory structure that keeps scripts and modules separate

I have the following directory structure: 我有以下目录结构:

app/
  bin/
    script1.py
    script2.py
  lib/
    module1/
      __init__.py
      module1a.py
      module1b.py
    __init__.py
    module2.py
  Dockerfile

My problem is that I want to execute script1.py and script2.py , but inside those scripts, I want to import the modules in lib/ . 我的问题是我想执行 script1.pyscript2.py ,但是在这些脚本中,我想将模块导入lib/

I run my scripts from the root app/ directory (ie adjacent to Dockerfile ) by simply executing python bin/script1.py . 我通过简单地执行python bin/script1.py从根app/目录(即与Dockerfile相邻)运行脚本。 When I import modules into my scripts using from lib.module1 import module1a , I get ImportError: No module named lib.module1 . 使用from lib.module1 import module1a将模块导入脚本时,出现ImportError: No module named lib.module1 When I try to import using relative imports, such as from ..lib.module1 import module1a , I get ValueError: Attempted relative import in non-package . 当我尝试使用相对导入(例如from ..lib.module1 import module1a ,出现ValueError: Attempted relative import in non-package

When I simply fire up the interpreter and run import lib.module1 or something, I have no issues. 当我简单地启动解释器并运行import lib.module1东西时,我没有任何问题。

How can I get this to work? 我该如何工作?

In general, you need __init__.py under app and bin , then you can do a relative import, but that expects a package 通常,您需要在appbin下使用__init__.py ,然后可以进行相对导入,但是需要一个软件包

If you would structure your python code as python package (egg/wheel) then you could also define an entry point, that would become your /bin/ file post install. 如果您将python代码构造为python包(egg / wheel),则还可以定义一个入口点,它将成为安装后的/bin/文件。

here is an example of a package - https://python-packaging.readthedocs.io/en/latest/minimal.html 这是一个包的示例-https: //python-packaging.readthedocs.io/en/latest/minimal.html

and this blog explains entry points quite well - https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/ 这个博客很好地解释了入口点-https: //chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/

if so, that way you could just do python setup.py install on your package and then have those entry points available within your PATH , as part of that you would start to structure your code in a way that would not create import issues. 如果是这样,您可以在软件包上进行python setup.py install ,然后在PATH使用这些入口点,作为其中的一部分,您将开始以不产生导入问题的方式来构造代码。

You can add to the Python path at runtime in script1.py: 您可以在运行时在script1.py中添加到Python路径:

import sys
sys.path.insert(0, '/path/to/your/app/')
import lib.module1.module1a

you have to add current dir to python path. 您必须将当前目录添加到python路径。

use export in terminal or sys.path.insert in your python script both are ok 在终端中使用export或在python脚本中使用sys.path.insert都可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM