A got a problem: .read method in this code does not return any text (returns an empty string). After the first executions it's expected result, but after that it's supposed to go by the elif branch. Instead it prints the timer is set. The file 'endtime.txt' isn't edited with hands since the program is executed once. What's the reason of such a strange behaviour?
import time
import os
FILE_PATH = 'endtime.txt'
def check_timer(duration):
timefile = open(FILE_PATH, 'w+')
endtime = timefile.read()
if not endtime:
timefile.write(str(duration + time.time()))
print('the timer is set')
elif (tmp := time.time()) < (endtime := float(endtime)):
print(f'{round(endtime)} seconds left')
else:
print("time's up")
def reset_timer():
if os.path.exists(FILE_PATH):
os.remove(FILE_PATH)
if __name__ == '__main__':
check_timer(15)
UPD: don't look at duration function param, I'll change some logic later
Related
I need a program on raspberry pi, in which I can change the value of a variable delay while the program is running and is not interrupted by any input(). I came up with only one solution: read a value from a text file and change it using another program. But my solution doesn't work very well... When I overwrite a value in a text file, sometimes it happens that the program can't convert it to a float... sometimes it works well and sometimes it prints this error:
ValueError: could not convert string to float: ''
But the value in the text file seems to be fine...
So, this is main program:
def pause():
file = open('delay.txt', 'r')
pause = file.readline()
return pause
delay = float(pause())
while True:
GPIO.output(STEP, GPIO.HIGH)
delay = float(pause())
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
delay = float(pause())
sleep(delay)
And this is the program, which is changing value in the text file:
while True:
rpm = float(input('RPM: '))
delay = (1/(rpm*60))/800
file = open('delay.txt', 'w')
file.write(str(delay))
file.close()
I really can't move with this... I'll be grateful for any advice and help in solving it.
You don't have to stick to my idea with a text file, maybe there is a better solution, but I couldn't think of anything better.
I'd suggest you use threading for this. I've made a small code example for you to get you started:
import threading
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG, filename="thread_output.txt", format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')
running = True
delay = 1
def worker(delay, running):
while running():
logging.debug(1)
sleep(delay())
logging.debug(0)
sleep(delay())
x = threading.Thread(target=worker, args=(lambda: delay, lambda: running))
x.start()
while running:
code = input("""
Make a choice:
1) Set delay
2) quit
""")
code = int(code)
if code == 1:
try:
val = input("Give up the desired delay between 0 and 10 seconds:")
val = int(val)
assert val >= 0 and val <= 10
delay = val
except ValueError:
print("Invalid input! Returning to home menu")
continue
elif code == 2:
running = False
else:
print("invalid option! Returning to home menu")
continue
print("quiting...")
x.join()
The part that helps you here is the fact that you pass the value of delay (and in the example also of running) as a lambda function. This means that every time the value is used, the value refetched. If you then were to change the value of the variable, it would get passed on :)
Hit me up if you have more questions!
I have a program which has to run a 'watcher' function in the background, which checks if the time specified on an 'alarm' object equals to the current time, and if so, it triggers the alarm. This is the function:
def watcher(this):
while this.run:
this.lock.acquire(True)
for i , a in enumerate(this.alarms):
if a.activate:
if a.repeat:
if a.dateTime.minute + (a.dateTime.hour*60) == datetime.datetime.now().minute + (datetime.datetime.now().hour*60):
this.trigger(i)
while True:
if keyboard.is_pressed('a'):
this.stop()
break
elif a.dateTime.date() == datetime.datetime.now().date() and a.dateTime.minute + a.dateTime.hour*60 == datetime.datetime.now().minute + datetime.datetime.now().hour*60:
this.trigger(i)
while True:
if keyboard.is_pressed('a'):
this.stop()
break
this.lock.release()
The lock object is created previously inside the class this function is in.
It works when i run it on a program where i set the alarms beforehand, but when i have to run another program alongside it that manipules the alarms, the other program hangs and only this one runs.
Here part of the main program:
import alarms
import datetime
import manager
import threading
import keyboard
lock = threading.Lock()
mngr = manager.manager()
print("Program Test")
tr = threading.Thread(target = mngr.watcher)
tr.start()
while True:
command = input()
if len(command) == 0:
print('')
elif command.split()[0] == "rem":
lock.acquire(True)
try:
mngr.remove_alarm(int(command.split()[1]) - 1)
except IndexError as excp:
print('Invalid alarm number. Use the command "list" to get alarms')
except Exception as excp:
print('Wrong usage of command: use like this: rem {alarmNumber}')
print('DEBUG: ' + str(excp))
finally:
lock.release()
Am i doing the synchronization wrong? Upon even instancing the Thread on the main program it halts execution.
I need assistance on the following problem that I am facing.
I have a Tkinter UI which have 3 buttons (Register, Lock the folders and unlock the folders). There is a cross button on the top right corner as in all the applications. Refer to the following snapshot.
So the idea is that when user unlocks his folder through this UI, and then press the cross button, that folder and all the folder's content which might have been opened by the user, must be closed down.
Below is the Code for closing down the folders.
def lockFolder_crossButton():
if userName.get()!='':
answer_folder = getFolderName()
#####check if the folder has already been locked or not!!!!*********
if os.path.exists('./secretFolder/'+userName.get()):
LockFolder.lockFolders(userName.get(), answer_folder)
global timer_active
timer_active = 'no'
window.destroy()
The above code is present in a class "openApplication.py" which is started when this application runs.
The following code of class Facelock.launch.pyw imports this class.
#!python2.7
import sys, os
scriptdir, script = os.path.split(__file__)
pkgdir = os.path.join(scriptdir, 'pkgs')
sys.path.insert(0, pkgdir)
os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
# APPDATA should always be set, but in case it isn't, try user home
# If none of APPDATA, HOME, USERPROFILE or HOMEPATH are set, this will fail.
appdata = os.environ.get('APPDATA', None) or os.path.expanduser('~')
if 'pythonw' in sys.executable:
# Running with no console - send all stdstream output to a file.
kw = {'errors': 'replace'} if (sys.version_info[0] >= 3) else {}
sys.stdout = sys.stderr = open(os.path.join(appdata, script+'.log'), 'w', **kw)
else:
# In a console. But if the console was started just for this program, it
# will close as soon as we exit, so write the traceback to a file as well.
def excepthook(etype, value, tb):
"Write unhandled exceptions to a file and to stderr."
import traceback
traceback.print_exception(etype, value, tb)
with open(os.path.join(appdata, script+'.log'), 'w') as f:
traceback.print_exception(etype, value, tb, file=f)
sys.excepthook = excepthook
if __name__ == '__main__':
from openApplication import self
self()
The following code is the snapshot related to the cross button of the UI window and the method calling after that button is pressed.
window = Tk()
window.title("FaceLock")
window.geometry('800x800')
####some piece of code
window.protocol('WM_DELETE_WINDOW', lockFolder_crossButton)
window.mainloop()
The following is the error that I am facing.
So is there any idea what is the issue here?
And how do you suggest to approach the problem?
Below is the code for openApplication.py
from Tkinter import *
import detector as dt
import os
import dataSetGenerator as generate
import trainData as train
import storeDictionary as save
from subprocess import Popen
import random
import pickle
import CheckFace as checkFace
import createAndHide as CreateFolder
from threading import Timer
import LockFolder, UnlockFolder
window = Tk()
window.title("FaceLock")
window.geometry('800x800')
empCode=StringVar()
userName=StringVar()
duration=StringVar()
errorLabel=Label(text="")
remaining=10
timer_active='no'
sub_folder='no'
locked=False
usertimer=StringVar()
timerLabel=Label(text="")
timerlabelcountdown=Label(text="")
def saveDictionary():
errorLabel.config(text='')
if userName.get() == '':
errorLabel.config(text="User name cant be left blank")
return
if empCode.get() == '':
errorLabel.config(text=" Employee code Cant be left blank")
return
try:
val = int(empCode.get())
except ValueError:
errorLabel.config(text="Enter a valid employee ID")
return
if duration.get() == '':
errorLabel.config(text="Duration cant be left blank")
return
try:
val = int(duration.get())
except ValueError:
errorLabel.config(text="Enter a valid Duration")
return
if int(duration.get())<1 or int(duration.get())>61:
errorLabel.config(text="Enter between 0 and 60 min")
return
if(save.findName(empCode.get())!='not' or save.findEmpCode(userName.get())!='not'):
errorLabel.config(text="User with this employee id or user name has already been registered")
return
flag=checkFace.checkFace()
if(flag==False):
errorLabel.config(text="This face is already a known face")
return
range_start = 10 ** (4 - 1)
range_end = (10 ** 4 ) - 1
rndmnumber= str(random.randint(range_start, range_end))
if len(duration.get()) == 1:
foldername=rndmnumber+'0'+duration.get()+empCode.get()
print "employee code ="+empCode.get()+" username for this is "+userName.get()
else:
foldername = rndmnumber +duration.get() + empCode.get()
dict={empCode.get():str(userName.get())}
save.store(dict)
dict2={userName.get():foldername}
save.storeFolder(dict2)
generateData()
trainData()
def recogniseFace():
flag=dt.detector()
print flag
window.destroy
print empCode.get()
def generateData():
generate.generateDataSet(empCode.get())
def trainData():
pickle_in_foldername = open('./utilities/folderdictionary.pickle','rb')
dictionary_foldername = pickle.load(pickle_in_foldername)
answer_folder = dictionary_foldername[userName.get()]
answer_folder=str(answer_folder)
CreateFolder.createFolder(answer_folder)
#Popen("./utilities/createAndHide.bat "+ userName.get() + " "+answer_folder)
flag=train.trainDataSet(empCode.get())
if(flag==True):
errorLabel.config(text="trained")
else:
errorLabel.config(text="not trained")
def defineRegister(flag,button):
if(flag):
userLabel = Label(text="enter your username")
userLabel.grid()
userEntry = Entry(textvariable=userName)
userEntry.grid()
empLabel = Label(text="enter your employeeCode")
empLabel.grid()
Entry(textvariable=empCode).grid()
Label(text="Duration for which Folder should be opened ").grid()
Entry(textvariable=duration).grid()
button = Button(text="DataSet Generation", command=lambda: lambda: saveDictionary()).grid()
def checkTime():
if getFolderName()!='not':
duration=getFolderName()[4:6]
return int(duration)
def lockFolder():
global locked
locked = True
#print 'here'
global timer_active
timer_active = 'no'
timerlabelcountdown.config(text='')
timerLabel.config(text='')
answer_folder = getFolderName()
#closeSubFolders(userName.get())
#os.system('nircmd win close title "%s"' %userName.get())
LockFolder.lockFolders(userName.get(),answer_folder)
#Popen("./utilities/lockFolder.bat "+userName.get()+" "+answer_folder)
global sub_folder
sub_folder = 'yes'
#user.configure(state=NORMAL)
unlockFolder_button.config(state=NORMAL)
userEntry.config(state=NORMAL)
empCodeEntry.config(state=NORMAL)
register_button.config(state=NORMAL)
lockFolder_button.config(state=DISABLED)
duration_box.config(state=NORMAL)
def getFolderName():
checkName = userName.get()
pickle_in_foldername = open(
'./utilities/folderdictionary.pickle',
'rb')
try:
dictionary_foldername = pickle.load(pickle_in_foldername)
answer_folder = dictionary_foldername[checkName]
except:
answer_folder = 'not'
return answer_folder
def lockFolder_crossButton():
if userName.get() != '':
answer_folder = getFolderName()
#####check if the folder has already been locked or not!!!!*********
if os.path.exists('./secretFolder/' + userName.get()):
LockFolder.lockFolders(userName.get(), answer_folder)
# Popen("./utilities/lockFolder.bat " + userName.get() + " " + answer_folder)
global timer_active
timer_active = 'no'
window.destroy()
def unlockFolder(checkName,answer_folder):
#Popen("./utilities/openFolder.bat " + checkName + " " + answer_folder)
UnlockFolder.unlock(checkName,answer_folder)
userEntry.config(state=DISABLED)
empCodeEntry.config(state=DISABLED)
unlockFolder_button.config(state=DISABLED)
lockFolder_button.config(state=NORMAL)
#duration.config(state=DISABLED)
def checkLock():
if locked==False:
lockFolder()
def countdown():
global timer_active
global remaining
if remaining <= 0 and timer_active == 'yes':
timerlabelcountdown.config(text="time's up!")
elif timer_active == 'yes':
timerlabelcountdown.config(text="%d" % remaining)
remaining = remaining - 1
timer = Timer(1, countdown)
timer.start()
def recogniseFace():
locked=False
lockFolder_button.config(state=NORMAL)
duration_box.config(state=DISABLED)
register_button.config(state=DISABLED)
errorLabel.config(text='')
timerlabelcountdown.config(text='')
if userName.get() == '':
errorLabel.config( text='User Name can not be left blank')
return
if save.findEmpCode(userName.get()) == 'not':
errorLabel.config(text='Please register yourself')
duration_box.config(state=NORMAL)
register_button.config(state=NORMAL)
return
final_time = checkTime()
if usertimer.get() != '':
try:
if int(usertimer.get()) < 1 or int(usertimer.get()) > 61:
errorLabel.config( text='Enter between 0 and 60 min')
return
final_time = int(usertimer.get())
except ValueError:
errorLabel.config( text='Enter a valid duration')
return
flag=dt.detector()
if flag==False:
errorLabel.config(text='Could not recognize you')
return
checkName=userName.get()
answer_folder = getFolderName()
print "checkName"+checkName+" flag="+flag
if(checkName==flag):
global timer_active
timer_active='yes'
timerLabel.config(text='Session is active')
global remaining
remaining=final_time*60
countdown()
unlockFolder(checkName,answer_folder)
timer = Timer(final_time * 60, checkLock)
timer.start()
Label(text="Welcome to the admin Screen").grid()
userLabel = Label(text="enter your username")
userLabel.grid()
userEntry = Entry(textvariable=userName)
userEntry.grid()
empLabel = Label(text="enter your employeeCode!")
empLabel.grid()
#empLabel.config(state=DISABLED)
empCodeEntry=Entry(textvariable=empCode)
empCodeEntry.grid()
#empCodeEntry.config(state=DISABLED)
durationLabel=Label(text="Duration for which Folder should be opened ")
durationLabel.grid()
duration_box=Entry(textvariable=duration)
duration_box.grid()
duration_box.config(state=NORMAL)
register_button=Button(text="Registeration",command=saveDictionary)
register_button.grid()
lockFolder_button=Button(text="Lock My Folder Please!",command=lockFolder)
lockFolder_button.grid()
lockFolder_button.config(state=DISABLED)
unlockFolder_button=Button(text="Unlock My Folder",command=recogniseFace)
unlockFolder_button.grid()
close_Application_Button=Button(text="Close Application",command=lambda:lockFolder_crossButton())
close_Application_Button.grid()
errorLabel.grid()
timerLabel.grid()
timerlabelcountdown.grid()
#window.protocol('WM_DELETE_WINDOW', lockFolder_crossButton)
window.mainloop()
There are a few problems with your code. Indention needs to be fixed, recogniseFace() has been defined twice in your code so you need to rename one of these functions and your import will not work due to no self() method existing in openApplication.py.
I believe your main problem is here.
if __name__ == '__main__':
from openApplication import self
self()
You are trying to import self from openApplication.py however you have not defined any method with the name self so python is unable to import self. That said you should never use self for anything other than its intended use inside of a class.
I believe what you should do is place your code inside of a function and then import that function.
In your openApplication.py file place all your code inside of a function and call it what you want. I think main() would work fine here.
Next in Facelock.launch.pyw replace your if __name__ == '__main__': section with this:
if __name__ == '__main__':
from openApplication import main
main()
This will correct the import error.
I am currently generating a python-script with the fabric framwork that is supposed to collect a backup from a remote server and store it locally on the client running fabric.
Now, since the backup file is >400MB, it takes quite some time to transfer it. And here is where my question bumps in:
Is there any kind of progressbars for the fabric get()-function? Or rather, is it possible to add a progressbar somehow?
Here's a piece of my code:
def collect_backup():
env.warn_only=True
run('uptime')
print "Copying scrips to be run..."
filename, remotepath = _getlatest()
print "Copy complete."
print "Collecting backup..."
localpath = _collect(filename, remotepath)
def _collect(filename, remotepath):
a=remotepath + filename
localpath="/home/bcns/backups/"
####Here's the get() I was talking about
get(a, localpath)
return(localpath)
The "filename" and "remotepath" variables are set in another function.
There is a lot of great info at the following site:
http://thelivingpearl.com/2012/12/31/creating-progress-bars-with-python/
Here is their solution for a console prog bar with threading:
import sys
import time
import threading
class progress_bar_loading(threading.Thread):
def run(self):
global stop
global kill
print 'Loading.... ',
sys.stdout.flush()
i = 0
while stop != True:
if (i%4) == 0:
sys.stdout.write('\b/')
elif (i%4) == 1:
sys.stdout.write('\b-')
elif (i%4) == 2:
sys.stdout.write('\b\\')
elif (i%4) == 3:
sys.stdout.write('\b|')
sys.stdout.flush()
time.sleep(0.2)
i+=1
if kill == True:
print '\b\b\b\b ABORT!',
else:
print '\b\b done!',
kill = False
stop = False
p = progress_bar_loading()
p.start()
try:
#anything you want to run.
time.sleep(1)
stop = True
except KeyboardInterrupt or EOFError:
kill = True
stop = True
Hope that helps or at least gets you started.
I was wondering if it was possible to perform an action at any given point in a basic python script, so say when it is close. I have the following code to find prime numbers (Just for fun)
number = 1
primelist = []
nonprime = []
while number < 1000:
number += 1
for i in range(number):
if i != 1 and i != number and i !=0:
if number%i == 0:
nonprime.append(number)
else:
primelist.append(number)
nonprimes = open("nonprimes.txt", "w")
for nonprime in set(primelist) & set(nonprime):
nonprimes.write(str(nonprime) + ", ")
nonprimes.close()
So basically i wanted to run the last part as the script is stopped. If this isn't possible is there a way where say i press "space" while the program is running and then it saves the list?
Cheers in advance :)
EDIT:
I've modified the code to include the atexit module as suggested, but it doesn't appear to be working. Here it is:
import time, atexit
class primes():
def __init__(self):
self.work(1)
def work(self, number):
number = 1
self.primelist = []
self.nonprime = []
while number < 20:
time.sleep(0.1)
print "Done"
number += 1
for i in range(number):
if i != 1 and i != number and i !=0:
if number%i == 0:
self.nonprime.append(number)
else:
self.primelist.append(number)
nonprimes = open("nonprimes.txt", "w")
for nonprime in set(self.primelist) & set(self.nonprime):
nonprimes.write(str(nonprime) + ", ")
nonprimes.close()
def exiting(self, primelist, nonprimelist):
primelist = self.primelist
nonprimelist = self.nonprime
nonprimes = open("nonprimes.txt", "w")
for nonprime in set(self.primelist) & set(self.nonprime):
nonprimes.write(str(nonprime) + ", ")
nonprimes.close()
atexit.register(exiting)
if __name__ == "__main__":
primes()
While I'm pretty certain the file object does cleanup and flushes the stuff to file when it is reclaimed. The best way to go about this is to use a with statement.
with open("nonprimes.txt", "w") as nonprimes:
for nonprime in set(primelist) & set(nonprime):
nonprimes.write(str(nonprime) + ", ")
The boiler plate code of closing the file and such is performed automatically when the statement ends.
Python has an atexit module that allows you to register code you want executed when a script exits:
import atexit, sys
def doSomethingAtExit():
print "Doing something on exit"
atexit.register(doSomethingAtExit)
if __name__ == "__main__":
sys.exit(1)
print "This won't get called"