beginner_yaml_user beginner_yaml_user - 2 months ago 8
Python Question

how to call def from another .py in different folder

I have following structure:
utils_dir has generator.py file which has 3 defs.

I have test.py in inline_dir. And I am trying to use defs from generator.py in test.py.

inline_dir and utils_dir are in different folders.
How can I achieve it to use defs?

Tried with creating

_init_.py
and then calling
import generator
. - Not worked.
Tried
from utils import generator
- Not worked

Dir structure



Support_dir
├── dir_A
│ ├── dir_aa
│ └──----- main.py [Want to use a and b from generator.py]
└── utils
|
└── generator.py
|
|___ def a
|___ def b

Answer

It sounds like you're trying to execute a .py file in a subdirectory.

Assuming the following directory structure:

.
├── inline
│   ├── __init__.py
│   └── main.py
└── utils
    ├── __init__.py
    └── generator.py

And your main.py containing a simple import like (the function a() being defined in generator.py):

from utils.generator import a

if __name__ == '__main__':
    a()

And generator.py would look something like this:

def a():
    print "hi there"

You won't be able to run your program using python inline/main.py because this will set the module search path to inline/

If you want to execute a file in a subdirectory while importing from your project-level, you could do the following:

PYTHONPATH=. python inline/main.py

UPDATE: Added example generator.py