简体   繁体   中英

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. I tried importing using

from module1.foo1 import *

but this is throwing traceback error. please suggest how to import foo1.py in foo2.py

Thanks in advance manu

尝试这个

from module1.foo1 import ClassName

From https://docs.python.org/2/tutorial/modules.html

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. 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 is initialized from these locations:

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).

the installation-dependent default.

After initialization, Python programs can modify sys.path.

So let's modify 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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