简体   繁体   English

在crontab中使用Python subprocess.call吗?

[英]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. 关于在crontab中运行的python脚本中使用subprocess.call,我遇到了麻烦。 I have isolated this problem to be subprocess not able to find the 7z executable. 我已将此问题隔离为子进程无法找到7z可执行文件。 I'm running this on FreeBSD 10.1, but that should not make a difference. 我正在FreeBSD 10.1上运行它,但这应该没有什么不同。 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. 我尝试将PYTHONPATH = $ PATH添加到crontab,我尝试将shell = True添加到subprocess.call,并且尝试使用/ usr / loca / bin / 7z而不是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: 这是我在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): 这是我的脚本(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: 答案是crontab中的PATH变量必须使用绝对路径,如下所示:

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

That fixes everything. 这样就解决了所有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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