Getting crontab on MAC to run anaconda installed python script (module not found)

自闭症网瘾萝莉.ら 提交于 2021-01-29 05:42:35

问题


I am trying to set up crontab for a script written in python which is intalled via Anaconda. The simple .py runs (it just loads a module for a demo) and can be run in terminal with python a.py . The problem is getting crontab the path for python and imported modules.

I have been trying to set the PATH and PYTHONPATh to the python directory and also where pandas is located. I think this is a env issue but have no idea what that means. Any ideas?

The crontab is:

SHELL=/bin/sh
PYTHONPATH=/Users/Esel/anaconda3/bin/python
* * * * *  cd /Users/Esel/Documents/x/y/z && python a.py

The python (test) script:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 21:36:34 2019

@author: Esel
"""

import pandas

print('hello kitty')
# This is a test 

Crontab mails the following statement:

Traceback (most recent call last): File "a.py", line 3, in import pandas ImportError: No module named pandas


回答1:


You're setting an env.var, cd'ing to a directory, and calling an interpreter, all from crontab.

Under those circumstances, personally I'd find it more elegant to just create a small wrapper script (here called pyscript) that does all that, and call that script from crontab:

$> cat /home/me/bin/pyscript
#!/bin/bash
# a.py needs module pandas in /foo/bar
export PYTHONPATH=/foo/bar
cd /Users/Esel/Documents/x/y/z || exit
python a.py

$> chmod ug+rx /home/me/bin/pyscript

$> cat /var/spool/cron/crontabs/me
...
* * * * *  /home/me/bin/pyscript



回答2:


With some ideas from a roadowl (thanx) and another SOverflow question (54564187) I think I got it running.

SHELL=/bin/sh
PATH=$PATH/Users/Esel/anaconda3/bin:/Users/Esel/anaconda3/condabin:/Applications/anaconda3/bin:/Applications/anaconda3/bin:/Users/Esel/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
* * * * *  cd /Users/Esel/Documents/x/y/z && python a.py

The path came from

echo $PATH


来源:https://stackoverflow.com/questions/57101742/getting-crontab-on-mac-to-run-anaconda-installed-python-script-module-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!