How to import the google api client into python so that it runs with as a cronjob?

Viewed 49

I am trying to use the google API client to download something every day for something but I have deduced that for some reason it won't let me import googleapiclient when I run it in crontab. For example, if I run this in crontab crontab: * * * * * python3 test.py >> cron.log

test.py:

print("Hello")

cron.log outputs:

Hello

But if I then once I import it so the file look like this

from googleapiclient import discovery
print("Hello")

then the cron.log looks like this:


Its just empty. I can not figure out why this is true. The google API client I believe is installed correctly because when I run it manually then it works perfectly with no issues. The operating system I am using is macos.

1 Answers

The way I fixed it is first by changing the crontab to python3 test.py > cron.log 2>&1. This showed that the errors where. Then I realized that it was not able to import googleapiclient into python. I still did not understand why it does not, but a workaround I found was to first install the libraries into a folder and then accessing the libraries from there. To install the libraries into a folder the command I used in terminal is below:

pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib -t ./lib

Then inside the python I added whats below to the beginning of the file so it would know where to import the libraries from.

import os
import sys
file_path = os.path.dirname(__file__)
module_path = os.path.join(file_path, "lib")
sys.path.append(module_path)

This does work.

Related