0

I have a cronjob to run a Python program, test.py, and save its output to test.log.

Output of sudo crontab -l:

* * * * * python3 /path/to/test.py/ >> /path/to/test.log 2>&1

Contents of test.py:

import os
import datetime
NOW = datetime.datetime.now()
print(NOW)
print(os.environ['some_var_in_bashrc']) # export some_var_in_bashrc="99999"

Contents of ~/.bashrc:

...

export some_var_in_bashrc="99999"

When running from terminal, output is as expected...

$ python3 test.py
2021-02-01 15:49:02.165106
99999

When the cronjob runs I get this in test.log:

2021-02-01 15:49:01.341941
Traceback (most recent call last):
  File "/path/to/test.py/", line 8, in <module>
    print(os.environ['some_var_in_bashrc'])
  File "/usr/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'some_var_in_bashrc'

Why does this happen?

I am on Ubuntu 18.04.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
huy giang
  • 3
  • 1
  • Does this answer your question? [Where can I set environment variables that crontab will use?](https://stackoverflow.com/questions/2229825/where-can-i-set-environment-variables-that-crontab-will-use) – mkrieger1 Feb 02 '21 at 10:11
  • yes, thank you i was searching for a few days but couldnt find. – huy giang Feb 02 '21 at 18:59

1 Answers1

0

The problem is that cron doesn't have access to shell's Env var by default. So try adding your cronjob like this:

* * * * * some_var_in_bashrc="99999" python3 /path/to/test.py/ >> /path/to/test.log 2>&1
0xMH
  • 1,825
  • 20
  • 26
  • how can i set another variable? will this work? * * * * * some_var_in_bashrc="99999";another_variable="111111" python3 /path/to/test.py/ >> /path/to/test.log 2>&1 – huy giang Feb 03 '21 at 23:51