Search code examples
pythonraspberry-picronraspbian

Crontab doesn't updates variable in .txt file


I've got problem with my python script.

#!/usr/bin/python
import sys
import MySQLdb
import os
import time
import datetime
import glob
jaki = 0
plik = open('aktualny.txt')
otwarcie = open('Pomiary.txt')
try:
    pomiar = plik.read()
    czest = otwarcie.read()
except:
    print ("nie ma takiego pliku")
finally:
    czestotliwosc = int(czest)
    ile = int(pomiar)       
    if ile == czestotliwosc-1:
        ile = 0
        plik = open('aktualny.txt','w')
        pomiar = str(ile)
        plik.write(pomiar + '\n')
        plik.close()
        otwarcie.close()
        jaki = ile
    else:
        ile = ile + 1
        plik = open('aktualny.txt','w')
        pomiar = str(ile)
        plik.write(pomiar + '\n')
        plik.close()
        otwarcie.close()
        jaki = ile
plik = open('aktualny.txt','w')
plik.write(pomiar + '\n')
plik.close

If I run this script from terminal, everything is OK (that means in "aktualny.txt" is current value), but if I use crontab to do this script every 1 minute, "aktualny.txt" is blank, there is no variable. I give all permisions to all files and scripts, but it doesnn't solve the problem.

In "Pomiary.txt" I've got constant "2".

What is wrong with it?


Solution

  • Followed Martijn Pieters's post: "You are using relative paths for the files you open. The current directory when running a crontab will differ from when you run it directly. Use absolute paths for the files and you'll see the script is working fine."