user171780
user171780

Reputation: 3075

How to properly call functions defined in other directories in Python?

Sorry, this has been already answered for sure, but I cannot find the answer to my problem... I want to make two separate scripts callable. Let me explain in detail with an example.

I have a directory structure similar to this:

maindir
|- subdir
|   |- script.py
|   `- myfunc.py
`- main.py

with the following content:

In myfunc.py there is

def myverynicefunc():
    print('Hello, I am your very nice func :)')

in script.py there is

import myfunc

def scriptfunc():
    print('I am the script function :)')

myfunc.myverynicefunc()

and in main.py there is

from subdir.script import scriptfunc

scriptfunc()

If I go to the subdir directory and execute the script it works, I mean:

.../main_dir/subdir$ python3 script.py 
Hello, I am your very nice func :)

However if I try to execute the main.py script it fails:

.../main_dir$ python3 main.py 
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from subdir.script import scriptfunc
  File "/home/alf/Escritorio/main_dir/subdir/script.py", line 1, in <module>
    import myfunc
ModuleNotFoundError: No module named 'myfunc'

If I modify the content of script.py to

from . import myfunc

def scriptfunc():
    print('I am the script function :)')

myfunc.myverynicefunc()

now the situation is the inverse, the main.py script works ok:

.../main_dir$ python3 main.py 
Hello, I am your very nice func :)
I am the script function :)

but the script.py script fails:

.../main_dir/subdir$ python3 script.py 
Traceback (most recent call last):
  File "script.py", line 1, in <module>
    from . import myfunc
ImportError: cannot import name 'myfunc'

Is there a way to make both calls to main.py and to script.py to work?

Upvotes: 0

Views: 819

Answers (2)

Apoorv Goyal
Apoorv Goyal

Reputation: 82

Try this in your script.py-

import sys
current_path = sys.path[0]
if current_path.split('/')[-1] != 'subdir':
    sys.path.insert(0, current_path+'/subdir/')
    import myfunc

By this, if the current directory for python is the parent directory of the file, that is the maindir, it would change the path to directory and then import it.

With this, it should work in both scenarios. Hope this helps. :)

Upvotes: 1

The_Pingu
The_Pingu

Reputation: 192

with the second scenario, you can do python3 -c "import subdir.script" in your main directory

Upvotes: 0

Related Questions