Search code examples
pythoncron

How to auto start python script running in virtualenv using crontab?


This is how I normally run the python script in virtualenv on Ubuntu 20.04.

source hibi/bin/activate
python -m hibiapi

Now I want to make a cronjob to make it auto start the python script on boot but I don't know the correct syntax. Can anyone correct me?

@reboot /var/www/api.adoreanime.com/htdocs/hibi/bin/python /var/www/api.adoreanime.com/htdocs/HibiAPI/hibiapi/ -m hibiapi

Error log:

Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/var/www/api.adoreanime.com/htdocs/HibiAPI/hibiapi/__main__.py", line 8, in <module>
    from . import __file__ as root_file
ImportError: attempted relative import with no known parent package

Solution

  • Use a shell script to do this.

    cd /your/module/location
    source hibi/bin/activate
    /full/path/to/python -m hibiapi
    

    Save the above in a script name it something like cron_run_hibiapi.sh.

    Make your script an executable by running:

    chmod +x /full/path/to/cron_run_hibiapi.sh
    

    Open crontab using crontab -e and add the following line to the bottom.

    @reboot /bin/bash -c "/full/path/to/cron_run_hibiapi.sh" &
    

    This is untested but I believe it should work.