Run python script from within the python project, which is a part of a big project (not only Python source code)

Viewed 28

I have a big project:

main
    golang
          src
             file1.go
    python
          src
             file1.py
             file2.py
          __init__.py
    java
          src
             file1.java
    scripts
          script.py
          validator.sh
venv
    bin
          pip
          python3
          pyyaml
          dateutil

Python project will use interpreter from:

ven/bin/python3

So anywhere inside

file1.py
file2.py

I can use imports:

import pyyaml
import dateutil

And this will work, by running from CLI:

venv/bin/python3 python/src/file1.py

However I wish to use some functions from file1.py inside file2.py

And have "relative reference" like this (inside file2.py)

from src.file1 import some_function

But having this kind of import and running the same way as before from CLI fails with error:

ModuleNotFoundError: No module named 'src'

What should I do? Pay attention that I have init.py file.

1 Answers

When you do from src.file1 this is relative to your sys.path.

Usually your current working directory is the first element in sys.path.

Thus you need to cd to main/python and then run ../venv/bin/python3 src/file1.py to make the imports work.

I've had similar issues and thus I have created an experimental, new import library: ultraimport.

It gives you more control over your imports and allows file system based imports.

You could then write in file2.py:

import ultraimport
file1 = ultraimport('__dir__/file1.py)'

This will always work, no matter how you run your code

Related