beginner_yaml_user beginner_yaml_user - 1 year ago 121
Python Question

how to call def from another .py in different folder

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

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

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

Tried with creating
and then calling
import generator
. - Not worked.
from utils import generator
- Not worked

Dir structure

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

Answer Source

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

Assuming the following directory structure:

├── inline
│   ├──
│   └──
└── utils

And your containing a simple import like (the function a() being defined in

from utils.generator import a

if __name__ == '__main__':

And would look something like this:

def a():
    print "hi there"

You won't be able to run your program using python inline/ 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/

UPDATE: Added example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download