简体   繁体   中英

Using Python subprocess.call with crontab?

I'm running into a wall with regards to using subprocess.call in a python script running in a crontab. I have isolated this problem to be subprocess not able to find the 7z executable. I'm running this on FreeBSD 10.1, but that should not make a difference. I have tried adding PYTHONPATH=$PATH to crontab, I have tried adding shell=True to subprocess.call, and I have tried using /usr/loca/bin/7z rather than 7z. None of these have fixed the problem. The error that I get is the following:

/usr/local/bin/7z: realpath: not found
/usr/local/bin/7z: dirname: not found
exec: /../libexec/p7zip/7z: not found

Here is how I'm calling the script in crontab:

PATH=$PATH:/usr/local/bin
@every_minute           $HOME/test.py >> $HOME/test.error 2>&1

Here is the contents of my script (test.py):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import subprocess
import tempfile

thing = 'blahblahblah'

errors = open('/home/myuser/error', 'wb')

with tempfile.TemporaryDirectory() as tmpdirname:
    tempthing = os.path.join(tmpdirname, thing)
    fh = open(tempthing, 'wb')
    fh.write(b'123')
    fh.close()
    zipname = '{}.zip'.format(thing)
    ziptempfile = os.path.join(tmpdirname, zipname)
    zipper = subprocess.call(['7z', 'a', '-p{}'.format('something'), '-tzip', '-y', ziptempfile, tempthing], stdout=errors, stderr=subprocess.STDOUT)

The answer is that the PATH variable in crontab must use an absolute path like so:

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

That fixes everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM