Environment Variables when python script run by cron

后端 未结 5 2080
渐次进展
渐次进展 2020-12-16 09:56

I have been looking at other stack overflow questions but couldn\'t get any to work. I have a python script which uses environment variables. This script works exactly as pl

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 10:37

    Instead of executing the whole ~/.profile what I'd do is move the variables that must be shared between your cron jobs and the account that has the profile, then I'd source these both in ~/.profile and in the cron job.

    The last attempt you show in the question is not properly formatted. The user id should be coming right after the scheduling information, but you've added the sourcing of the profile before the user id, which surely cannot work.

    Here's an example setup that I've tested here:

    */1 * * * * someuser . /tmp/t10/setenv && /usr/bin/python /tmp/t10/test.py
    

    I've set it to execute every minute for testing purposes. Replace someuser with something that makes sense. The /tmp/t10/setenv script I used had this:

    export FOO=foovalue
    export BAR=barvalue
    

    The /tmp/t10/test.py file had this:

    import os
    
    print os.environ["FOO"], os.environ["BAR"]
    

    My cron emails me the output of the scripts it runs. I got an email with this output:

    foovalue barvalue
    

提交回复
热议问题