Search code examples
pythonlinuxbashimporterror

ImportError . No module named Commons error - python


Hi I have a project which it's made up of a couple of folders named Proj1 and Proj2.

Home
    Proj1
       Scripts1.py

    Proj2
       Scripts2.py

    Commons.py

In Scripts1 I set

sys.path.append('/Home')
os.chdir('/Home')

and import Commons which contains function useful for every scripts. The whole project is on a Linux server. I run the scripts with a bash

script_name=Scripts1
script_file="/Home/Proj1/${script_name}.py"
python "$script_file"

I keep getting error ModuleNotFoundError: No module named 'Commons'. What Am I missing?


Solution

  • You need to pick a top-level name for your module, then arrange your code like this:

    Home
      script_name.py
      somename
        Common.py
        Proj1
          Scripts1.py
        Proj2
          Scripts2.py
    

    Then use import somename and use somename.Common within the module itself and somename.Proj1.Scripts1 etc. Also, you probably want to move script_name.py outside of the module directory itself as shown.