Kailegh
Kailegh

Reputation: 197

Import custom modules from in script launched from Django

I am trying to process an uploaded file to Django server. When I receive it I launch a python script that processes the file (I need to do it this way instead of with classes, so please do not tell me to do it from a class).

My Django structure is the following:

Project

From the views I launch a python script:

sb_info = subprocess.run(['python', 'src/pipeline/master.py', '/tmp'], stdout=subprocess.PIPE, universal_newlines=True)

This works nicely, but when the script is launched I get the following error:

File "src/pipeline/master.py", line 10, in from src.classes.misc import path_to_dest ModuleNotFoundError: No module named 'src'

The problem is that that file does exits. I have checked using os.listdir() and the master.py does see the src module, this is the output that I get:

[temp.txt, db.sqlite3, pycache, S2T, .idea, manage.py, src, wdir.txt, .git, web_server]

I have tried a lot of things that I have seen in stackoverflow, for example:

I want to state again that from the views.py the src module is detected, I can import its functions, the problem comes when I launch a python script, then it stats complaining about module not found, but the os.listdir() does see it, so I am confused about what is happening.

Thanks a lot for your help!

Upvotes: 1

Views: 269

Answers (1)

Philip Ciunkiewicz
Philip Ciunkiewicz

Reputation: 2791

It seems like the problem is with the path you are providing to the import. Your src module is two levels above your script from the tree that you’ve provided, so include explicit __init__.py files in each directory to do an absolute import from the parent module, as shown here:

Python: Import file in grandparent directory

Upvotes: 1

Related Questions