[英]How to import python files within two subdirectories
I have a directory structure as below 我有一个目录结构如下
- src\module1\ __init__.py
- src\module1\foo1.py
- src\module2\ __init__.py
- src\module2\foo2.py
I want to import functions from foo1.py in foo2.py. 我想从foo2.py中的foo1.py导入函数。 I tried importing using
我尝试使用导入
from module1.foo1 import *
but this is throwing traceback error. 但这会引发回溯错误。 please suggest how to import
foo1.py
in foo2.py
请建议如何导入
foo1.py
在foo2.py
Thanks in advance manu 在此先感谢manu
尝试这个
from module1.foo1 import ClassName
From https://docs.python.org/2/tutorial/modules.html 从https://docs.python.org/2/tutorial/modules.html
6.1.2.
6.1.2。 The Module Search Path
模块搜索路径
When a module named spam is imported, the interpreter first searches for a built-in module with that name.
导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。 If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.
如果找不到,它将在变量sys.path给出的目录列表中搜索名为spam.py的文件。 sys.path is initialized from these locations:
sys.path从以下位置初始化:
the directory containing the input script (or the current directory).
包含输入脚本的目录(或当前目录)。
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
PYTHONPATH(目录名称列表,语法与shell变量PATH相同)。
the installation-dependent default.
取决于安装的默认值。
After initialization, Python programs can modify sys.path.
初始化后,Python程序可以修改sys.path。
So let's modify sys.path 因此,让我们修改sys.path
import sys
sys.path.append('src\module1\')
import foo1
It's worth printing sys.path so you can see why it's not being found already. 值得打印sys.path,因此您可以查看为什么尚未找到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.