2

I have the following project structure :

-project
  -src
    -package1
      -script1.py
      -__init__.py
    -package2
      -script2.py
      - __init__.py
    -__init__.py

Now script1.py includes two functions :

def my funct1():
    print("Hello")

def my funct2():
    // do something

Now I want to run funct1() in script2.py. I am new to something like that as I always write my whole code in main.py and that's it. I have searched for this problem and I wrote the following code in script2.py :

from src.package1.script1 import *

    funct1()

This gives me the following error :

    from src.package1.script1 import *
ModuleNotFoundError: No module named 'src'

Somebody please help me to import the function. I have another question, when I solve the import error, do I directly call funct1() in script2.py or do I need to do something extra, like including a main function in script2.py ??

AAA
  • 305
  • 1
  • 7

1 Answers1

3

You can use relative imports like:

from ..package1.script1 import * since src has it's own __init__.py it's all the same module.

This will work if calling script2 as a module, i.e.

python3 -m project.src.package2.script2

rather than

python3 project/src/package2/script2.py

In the later case you'll get the error ImportError: attempted relative import with no known parent package.

If this wasn't the case, i.e. package_1 and package2 are separate modules, you should just add the module path to sys.path by including:

import os
import sys

current file = __file__
src_directory_path = os.path.dirname(os.path.dirname(current file))
sys.path.append(os.path.join(src_directory_path, "package1"))

in package2/__init__.py. Then your call things like import package1

For more on relative imports see the answers to Relative imports in Python 3

DrPrettyman
  • 165
  • 1
  • 8
  • what are ".." before the "package1.script1 import * ? – AAA May 22 '23 at 13:25
  • I have tried from ..package1.script1 import * but I got this error ImportError: attempted relative import with no known parent package – AAA May 22 '23 at 18:50
  • The ".." are referring to moving "two steps upwards" in the package hierarchy. If you had another script `script2a.py` next to `script2.py`, you would use `from .script2a import ...` - the single dot referring to moving one step up. – DrPrettyman May 23 '23 at 19:08
  • This relative import will only work if you're calling script2 as a module (using the -m flag). I'll put this in the answer. – DrPrettyman May 23 '23 at 19:09