1

This is my python code, I need to run it on cron job:

#!/usr/bin/env python3
from pymongo import MongoClient
import datetime
import csv


def raw_db_counts():
    client = MongoClient('host', 27017)
    user_name = 'xxx'
    password = 'ddd'
    db = client.raw_data
    db.authenticate(user_name, password, source='admin')
    current_timestamp = datetime.datetime.now()
    public_docs = db.public_docs.aggregate([
        {'$group': {'_id': '$company_id'}},
        {'$group': {'_id': 0, 'count': {'$sum': 1}}}
    ])
    public_doc = next(public_docs)
    public_docs_count = public_doc['count']
    directorship_records = db.full_directorships.aggregate([
        {'$group': {'_id': '$din_or_dpin'}},
        {'$group': {'_id': 0, 'count': {'$sum': 1}}}
    ])
    directorship_record = next(directorship_records)
    directorship_records_count = directorship_record['count']
    din_details_count = db.din_details.count()
    with open('raw_db_count.csv', 'a') as f:
        writer = csv.writer(f)
        writer.writerow([current_timestamp, public_docs_count, directorship_records_count, din_details_count])


if __name__ == '__main__':
    raw_db_counts()

In shell I run crontab -e , then I edit the file */3 * * * * /home/fullpath/raw_db_counts.py, but when I run python script cron job, the file data is not getting updated.

If I execute python script normally there is no issuse, but in cronjob execution yes.

1
  • 2
    Just a hunch… Does Cron execute the script if you change the command in crontab to /usr/bin/python3 /home/fullpath/raw_db_counts.py? I suspect that env can't find python3 because /usr/bin isn't part of PATH when run from Cron. See askubuntu.com/a/579439/175814 Nov 14, 2016 at 8:08

0

You must log in to answer this question.

Browse other questions tagged .