Forums

Importing within scheduled task

The following is the structure of my project

webapp_root
    ├── app_one
    │   └──main.py
    └── webapp_dir
        └── settings.py
        └── urls.py
        └── wsgi.py
        └── asgi.py

I'm trying to import specific variables from settings.py into main.py in the other directory. This works fine locally, and when I manually run the script via a button in my web app. But when I set this up as a scheduled task, it crashes and says it can't find a module called webapp_dir? Is there a specific way I have to import it with this file structure? Thank you

See the section on the working directory on this page: https://help.pythonanywhere.com/pages/ScheduledTasks/

I've just read the page on working directories. I'm using the import function to access a .py script, I'm not reading or writing to the file, on the page you linked it says the information about working directories does not apply if you are are using import to import code. I'm just calling methods and variables from a .py file, not reading or writing. Thank you

The working directory is also used by Python to set the root for imports.

I'm still a bit stuck, is there a way to set the root directory. The code in my python file thats causing in an error is: from webapp_dir.settings import variable. I've tried following the steps in the link, but can't seem to get it to work

Yes, add "cd /the/directory;" before your task command.

I've added the cd /the/directory like follows:

cd /home/username/webapp_root && /home/username/webapp_root/venv/bin/python3.9 /home/username/webapp_root/app_one/main.py

I added this to a scheduled task, but it still says it can't find the module

Ok. Check the contents of sys.path when your're running your code.