0

There is path/to/folder/, where users write programs in Jupyter notebooks and save them in path/to/folder/program_name.py files. Users use relative addressing to import modules or open files (for example, from path/to/), and scripts run successfully because Jupyter starts program "from" location of .ipynb. I have to schedule launch of resulting program_name.py, so I do smth like 30 12 * * * python path/to/folder/program_name.py in cron. Problem is that program_name.py launches from home folder and it can't import modules because of relative addressing. Is there way to launch .py in one console command, like cd path/to/folder/ AND python program_name.py? What is best practice for this? Forse users to use absolute addressing?

tima
  • 51
  • 1
  • 1
  • 8
  • 1
    Do you mean just using "&&" or "&"? Like this: https://stackoverflow.com/questions/4510640/what-is-the-purpose-of-in-a-shell-command – Geo Jul 31 '21 at 14:25
  • 1
    Rather than invoking Python directly from cron, write a shell script that does all the necessary directory changes, environment variable settings etc and get cron to run that –  Jul 31 '21 at 14:27
  • @AndyKnight you mean to create program_name.sh with `cd path/to/folder/` `python program_name.py` and add program_name.sh to cron? – tima Jul 31 '21 at 14:33
  • Yes that's exactly what I mean –  Jul 31 '21 at 14:51

1 Answers1

0

When you import modules the interpreter searches through a set of directories for the module specified. The list of directories that it searches is stored in sys.path. You can see that list like this:

import sys
print(sys.path)

If you want to import modules that exist elsewhere then add that directory to the PYTHONPATH environment variable:

export PYTHONPATH='/my/other/modules/are/here'

Any directory added to the PYTHONPATH variable will be added to sys.path when running your program.

So by doing this your script should be able to import modules from anywhere assuming that the directory containing the modules is in sys.path.

flomo2023
  • 1
  • 2