Forums

Need help scheduling task in virtualenv

I'm trying to schedule a task in a virtualenv for a Django site. In the task, I run a Django management command named 'process_league_event', which takes a single argument (a day of the week). Currently, the command simply logs a message in a log file.

My virtualenv is named 'League', and my Django app directory structure looks roughly like this:

/home
    /mon
        /League
            /website
                /logs
                    - league.log
                /website
                    - settings.py
                - manage.py

If I do the following, it works, and I get the expected message in league.log:

~ $ workon League
(League) ~ $ cd ~/League/website
(League) ~/League/website (master)$ python3 manage.py process_league_event MONDAY

However, if I try to run this as a scheduled task, no message is logged in league.log. This is what my task looks like:

 /home/mon/.virtualenvs/League/bin/python /home/mon/League/website/manage.py process_league_event MONDAY

Any ideas?

As it turns out, the task is running just fine. The problem is in my LOGGING settings - the logfile filename is specified with a relative path: "./logs/league.log".

Right, that would make sense. If you want to write to a specific location, I'd recommend using the __file__ magic variable to work out the location of the file containing the current executing code. So, for example, if your code is in /home/mon/something/somethingelse/foo.py, then you can get the directory /home/mon/something/somethingelse/ with code like this:

import os
....
my_directory = os.path.dirname(os.path.abspath(__file__))

...and then you can use os.path.join to go from there to your desired logging directory, and use the resulting absolute path when opening your logfile.