Re: Python does not get environment variable when using cron.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Shawn Milochik

    Re: Python does not get environment variable when using cron.

    Here's a more "English" version of what people are trying to explain:

    When you log into a Unix session, certain files in your home directory
    are read and add environment variables to your session. When you run a
    cron job, it does not do this. It still runs as "you" as far as
    permissions go, but it is not identical to you typing the command in
    an interactive session.

    The easiest solution (in my opinion) is to write a bash script to
    execute your Python script, and use that bash script to add those
    environment variables. The most likely file you'll want to run is
    ..bashrc in your home directory. If you're on a Mac, it's .bash_login
    instead.

    Example:

    #/usr/bin/env bash

    source ~/.bashrc
    path/my_script.py

    Something like that should take care of it. If not, get creative --
    add the "env" command to your bash script and have it send the output
    to a file: env cron_env.txt

    Then run env in your interactive session and look for differences.

    Shawn
  • Asun Friere

    #2
    Re: Python does not get environment variable when using cron.

    On Aug 18, 11:17 pm, "Shawn Milochik" <Sh...@Milochik .comwrote:
    <snip>
    >
    The easiest solution (in my opinion) is to write a bash script to
    execute your Python script, and use that bash script to add those
    environment variables.
    Agreed. Wrap it in a shell script, easier to read and grow than a
    oneliner on the crontab.
    The most likely file you'll want to run is
    .bashrc in your home directory. If you're on a Mac, it's .bash_login
    instead.
    >
    Example:
    >
    #/usr/bin/env bash
    >
    source ~/.bashrc
    path/my_script.py
    >
    I for one don't have $HOSTNAME defined in my .bashrc file. I doubt
    this is likely to give him much joy.
    Something like that should take care of it. If not, get creative --
    add the "env" command to your bash script and have it send the output
    to a file: env cron_env.txt
    >
    Again no. The reason os.environ can't find HOSTNAME is that it is NOT
    defined in the environment, if env can find it os.environ should be
    able to as well.


    Comment

    Working...