Python does not get environment variable when using cron.

Asun Friere afriere at yahoo.co.uk
Mon Aug 18 22:36:01 EDT 2008


On Aug 19, 2:37 am, "Stephen Cattaneo" <Stephen.Catta... at u4eatech.com>
wrote:
> - What did you run in the cronjob to get back all those variables?
>
> <cron date / time> set; echo "-----------------"; echo "import os; print
> os.environ" | python
>
> Cheers,
>
> S

As I should have noted from $BASH_EXECUTION_STRING.  I'd be half
dangerous if I just ... paid ... ATTENTION!

OK, the difference between using bash's builtin 'set' and '/usr/bin/
env' is that 'env' looks at ENVIRONMENT variables, whereas 'set' looks
at SHELL variables (which in bash includes HOSTNAMES).  Since shell
variables are private to the shell, 'os.environ' can only see
environment variables.

In other words if you want 'os.environ' to see a variable 'set' sees,
you have to export it from the shell to the environment, eg.
* * * * * export HOSTNAME;echo "import os;print
os.environ['HOSTNAME']" | /usr/bin/python

But note this solution depends on the particular predilections of the
bash shell.  If you are solely concerned with finding the hostname,
the more generic solution would be the one using
'socket.gethostname' (as John Machin suggested above), which
presumably calls the C library routine of the same name.

cheers



More information about the Python-list mailing list