Search code examples
pythonlinuxcronposix

Path on subprocess check_output


When executing a python script with crontab, the script lacks environment variables.

The script calls an executable which some Linux distributions ship under /usr/bin and other under /sbin.

subprocess.check_output() doesn't account for this.

Can I assume that which is always under /usr/bin/which? Is Popen the better alternative with env=os.environment.copy()?

I've tried with shell=True and sh -c in the crontab.

#read the Kernel's routing table by calling /usr/bin/route -n
routes = str(subprocess.check_output(["route", "-n"]), "utf-8")

see https://github.com/pzillmann/wireguard-dynamic-routing/blob/master/wg-dynroute.py#L32

I expect the script to show equal behavior when called in a bash session and called in crontab.

FileNotFoundError: [Errno 2] No such file or directory: 'route'

Solution

  • When executing a python script with crontab, the script lacks environment variables.

    It probably depends on which cron we're talking about. Vixie cron sets PATH, HOME and SHELL and LOGNAME.

    Any but LOGNAME can be overridden in /etc/crontab or your own crontab file. So set up a proper PATH in your crontab file.