Forums

Can't find file when run as a task

Running my script file individually works fine (via the Run button), but when it is run as a task it results in the error:

FileNotFoundError: [Errno 2] No such file or directory: 'data/schools/schools.json'

I know that in places like (https://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/) it's suggested to use absolute paths instead of relative ones, but why is the behavior different when running it manually vs as a task?

Have a look at https://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/

That's the help page I referenced as well. I'm just curious why relative paths work when running the file manually (in PythonAnywhere) but cause an error when the same file is run as a scheduled task. Both times they are being run in PythonAnywhere, but understanding why the task is the only one returning an error will help in planning how best to write and test scripts for this platform.

When you run a script from the editor, it's essentially the same as starting a Bash console, using cd to navigate to the directory where the script is stored, and then running pythonX.Y scriptname.py (we have some extra logic to guess what version of Python you're using so as to work out what to put in place of the X.Y).

A scheduled or always-on task, by contrast, is actually a Bash command. So you don't have to schedule a Python script, you could (if you liked) schedule a Bash command like "ls" or "echo hello". That means that in the general case we don't know what directory you would like to "cd" to before running it, so we default to using your home directory. We could perhaps have some special-case code so that if the thing that you schedule is just a path to a Python script, we "cd" to it before running it, but that could lead to confusion -- for example, it would mean that scheduling this:

/home/yourusername/something/yourscript.py

...would use Python to run yourscript.py having first used cd to change directory to /home/yourusername/something/, but scheduling this:

python3.7 /home/yourusername/something/yourscript.py

...would have to run in /home/yourusername/, which would be even more confusing than the current situation!

Got it, that makes sense! Thanks