简体   繁体   English

从子目录导入python

[英]python import from the sub-directories

I have the following directories: 我有以下目录:

|-- project
|   |-- __init__.py
|   |-- proj1
|   |   |-- file.py
|   |   |-- file.py~
|   |   `-- __init__.py
|   `-- proj2
|       |-- call.py
|       |-- call.py~
|       `-- __init__.py

And the call.py has: 并且call.py具有:

from proj1.file import hello

hello('nishant')

And the file.py has. 和file.py有。

def hello(arg):
    print 'hello ,' + arg

When i am trying to call outside the project directory python project/proj2/call.py i get the import Error: No module named proj1.file 当我尝试在项目目录python project/proj2/call.py之外调用时,我得到导入错误:没有名为proj1.file的模块

Any Idea ..? 任何想法 ..?

This is because imports are relative to paths in your PATH environment variable (or sys.path in python). 这是因为导入相对于PATH环境变量(或python中的sys.path )中的路径。 By default this var only contains the current directory, which is the directory you run from. 默认情况下,此var仅包含当前目录,即您从中运行的目录。

Run you project from within the project directory: python proj2/call.py project目录中运行项目: python proj2/call.py

Alternatively, you can append your project root to sys.path before doing the imports: 或者,您可以在导入之前将项目根目录附加到sys.path

import sys
sys.path.append(YOUR_PROJECT_ROOT)

Note that the call.py and file.py are not in same path so you need too add the prog1 to path of call.py with .. : 请注意, call.pyfile.py不在同一路径中,因此您也需要使用..prog1添加到call.py路径中:

import sys ,os
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if not path in sys.path:
    sys.path.insert(1, path)
del path

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

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