Hi everyone,
I am working on an app and trying to create a corrector and I am using keyboard module for the correction.
I have created two classes, one keyboard monitor, which reads pressed events and displays them to screen, and one which suppresses them.
What I want to achieve is while the app corrects user input, every text that is typed by the user is suppressed and saved in a variable, for later use.
I am struggling on the synchronization of all this.
import keyboard
import threading
import time
lock_for_listening_to_keyboard = threading.Lock()
#########################################################
def delete_and_write(times_to_delete, word_to_write):
global lock_for_listening_to_keyboard
time.sleep(2)
print("OK")
# for i in range(50):
# keyboard.write('*')
# for i in range(times_to_delete+1):
# keyboard.press_and_release('backspace')
# for i,char in enumerate(word_to_write):
# keyboard.write(char.upper())
# for i in range(40):
# keyboard.write('*')
# keyboard.write(' ')
#########################################################
class keyboard_not_suppressed_monitor(threading.Thread):
def __init__(self, threadID, keyboardSupress):
threading.Thread.__init__(self)
self.threadID = threadID
self.fstring = ""
self.counter_for_key_presses = 0
self.suppressed = False
def run(self):
while(True):
event = keyboard.read_event(suppress=self.suppressed)
if (event.event_type == keyboard.KEY_DOWN):
# print("Key pressed = {} + suppress = {}".format(event.name, self.suppressed))
if (event.name == "space"):
suppressed_monitoring = keyboard_suppressed_monitor(2, self.fstring, self.counter_for_key_presses, None)
suppressed_monitoring.start()
suppressed_monitoring.join()
print("RETURNED TO MAIN MONITOR")
self.counter_for_key_presses = 0
self.fstring = ""
elif (event.name in "abcdefghijklmnopqrstuvwxyz"):
self.fstring = ''.join([self.fstring, event.name])
self.counter_for_key_presses += 1
class keyboard_suppressed_monitor(threading.Thread):
def __init__(self, threadID, fstring, counter_for_key_presses, keyboardSupress):
threading.Thread.__init__(self)
self.threadID = threadID
self.fstring = fstring
self.counter_for_key_presses = counter_for_key_presses
self.suppressed = True
self.done = False
self.temp = ""
def stop(self):
self._is_running = False
def run(self):
self.temp = self.fstring
self.fstring = ""
thread_delete_and_rewrite = threading.Thread(
target = delete_and_write, args=(self.counter_for_key_presses, self.temp))
thread_delete_and_rewrite.start()
# thread_delete_and_rewrite.join() # join is not here
print("RETURNED FROM THE REWRITER")
while(True):
print("STATE OF THREAD IS : {}".format(thread_delete_and_rewrite.is_alive())) print("IN THE WHILE TRUE")
event = keyboard.read_event(suppress=self.suppressed)
if (event.event_type == keyboard.KEY_DOWN):
print("KEYS PRESSED WHILE SUPPRESSED = {}".format(event.name))
if (event.name == "space"):
print("THE STRING ENTERED ")
self.temp = self.fstring
self.fstring = ""
thread_delete_and_rewrite = threading.Thread(
target = delete_and_write, args=(self.counter_for_key_presses, self.temp))
thread_delete_and_rewrite.start()
self.counter_for_key_presses = 0
self.fstring = ""
elif (event.name in "abcdefghijklmnopqrstuvwxyz"):
self.fstring = ''.join([self.fstring, event.name])
self.counter_for_key_presses += 1
# thread_delete_and_rewrite.join() # join is not here
print("SUPPRESSED ENDED")
self._is_running = False
if __name__ == "__main__":
kb = keyboard_not_suppressed_monitor(1, None)
kb.start()
kb.join()
I am trying to return the control when the function of correction is done, but can't make it work.
Any help is appreciated.
* UPDATE 1*
I made one class for all and works almost perfect.
I have one little problem that when the second while loop ends it requires a key press to exit. Is there a solution to this.
import keyboard
import threading
import time
lock_for_listening_to_keyboard = threading.Lock()
global running_suppressed_monitor
running_suppressed_monitor = False
#########################################################
def delete_and_write(times_to_delete, word_to_write):
global running_suppress_monitor
print("---Deleting & Rewrite Started---")
time.sleep(2)
running_suppressed_monitor = False
print("---Deleting & Rewrite Ended---")
# for i in range(times_to_delete+1):
# keyboard.press_and_release('backspace')
# for i,char in enumerate(word_to_write):
# keyboard.write(char.upper())
# keyboard.write(' ')
def write_the_suppressed_string(string):
keyboard.write(string)
#########################################################
class keyboard_monitor(threading.Thread):
def __init__(self,thread_name, threadID, word_typed, keyboard_suppress, counter_for_key_pressed):
threading.Thread.__init__(self)
self.name = thread_name
self.threaID = threadID
self.fstring = word_typed
self.counter_for_key_presses = counter_for_key_pressed
self.suppressed = keyboard_suppress
self.temp = ""
def stop(self):
self._is_running = False
def run(self):
if (self.suppressed is False):
while(True):
event = keyboard.read_event(suppress = self.suppressed)
if (event.event_type == keyboard.KEY_DOWN):
if (event.name == "space"):
suppressed_monitor = keyboard_monitor("suppressed_monitor", 2, self.fstring, True, self.counter_for_key_presses)
suppressed_monitor.start()
suppressed_monitor.join()
print("RETURNED TO MAIN MONITOR")
self.counter_for_key_presses = 0
self.fstring = ""
elif (event.name in "abcdefghijklmnopqrstuvwxyz"):
self.fstring = ''.join([self.fstring, event.name])
self.counter_for_key_presses += 1
elif (self.suppressed is True):
self.temp = self.fstring
self.fstring = ""
thread_delete_and_rewrite = threading.Thread(
target = delete_and_write, args=(self.counter_for_key_presses, self.temp))
thread_delete_and_rewrite.start()
running_suppressed_monitor = True
# while(thread_delete_and_rewrite.is_alive()):
while(running_suppressed_monitor):
event = keyboard.read_event(suppress=self.suppressed)
if (event.event_type == keyboard.KEY_DOWN):
print("KEYS PRESSED WHILE SUPPRESSED = {}".format(event.name))
if (event.name == "space"):
self.temp = self.fstring
self.fstring = ""
thread_delete_and_rewrite = threading.Thread(
target = delete_and_write, args=(self.counter_for_key_presses, self.temp))
thread_delete_and_rewrite.start()
# thread_delete_and_rewrite.join()
self.counter_for_key_presses = 0
self.fstring = ""
elif (event.name in "abcdefghijklmnopqrstuvwxyz"):
self.fstring = ''.join([self.fstring, event.name])
self.counter_for_key_presses += 1
# NO thread_delete_and_rewrite.join()
# NO thread_delete_and_rewrite.join()
if (thread_delete_and_rewrite.is_alive() is False):
break
thread_delete_and_rewrite.join()
print("SELF.FSTRING = {}".format(self.fstring))
print("BEFORE END OF SUPPRESSED MONITOR")
if (self.fstring != ""):
thread_write = threading.Thread(
target = write_the_suppressed_string, args=(self.fstring, ))
thread_write.start()
thread_write.join()
print("SUPPRESSED ENDED")
self._is_running = False
if __name__ == "__main__":
kb_not_suppressed = keyboard_monitor("not_suppressed_monitor", 1, "", False, 0)
kb_not_suppressed.start()
kb_not_suppressed.join()
Related
I'm really new to this, and am always stuck by basic issues. Please can you show and explain my errors in this chunk of code. Right now the problem is that self is not defined, but I don't understand why.
It would be amazing if someone could clear this up.
import random
import time
class Building:
number_of_floors = 0
customer_list = []
elevator = 0
def __init__(self, floors, customers):
self.number_of_floors = floors
for customerID in range(1, customers + 1):
new = Customer(customerID,self.number_of_floors)
self.customer_list.append(new)
self.customer_list.sort(key = lambda x: x.current_floor)
self.elevator = Elevator(floors,self.customer_list)
self.run()
def run(self):
print('++++++++++++++++++++++++++ELEVATOR IS NOW STARTING+++++++++++++++')
print('Ther are %d customers in the building' % (len(self.customer_list)))
number_of_customers = len(self.customer_list)
self.output()
def output(self):
for customer in self.customer_list:
print("Customer",customer.customerID,"is on floor",customer.current_floor,"and wants to go",customer.destination_floor)
# ELEVATOR MOVING UP
while (self.elevator.current_floor <= self.number_of_floors) & (self.elevator.current_floor > 1):
self.elevator.current_floor -= 1
print(len(self.customer_list),'Customers in lift.')
print('ELEVATOR MOVING DOWN')
print('++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('FLOOR',self.elevator.current_floor)
for customer in self.customer_list:
if (customer.in_elevator == True):
customer.current_floor = self.elevator.current_floor
if (slef.elevator.current_floor == customer.destination_floor) & (customer.in_elevator == True) & (customer.customer_direction == -1):
customer.in_elevator = False
self.customer_list.remove(customer)
print('Customer',customer.customerID,'has reached their destination')
print('There are',len(self.customer_list),'trapped in the elevator')
print('There are',len(Elevator.register_list),'people left on the register')
print('Elevator run is done!!!')
print('CUSTOMERS STUCK IN LIFT ARE BELOW')
for stuck in self.customer_list:
print('Cust. ID:',stuck.customerID,'Dest. Floor:',stuck.destination_floor,'Curr. Floor:',stuck.current_floor,'In Elevator',stuck.in_elevator,'Direction',stuck.customer_direction)
class Elevator:
number_of_floors = 0
register_list = []
current_floor = 0
up = 1
down = -1
def __init__(self, number_of_floors, register_list):
self.number_of_floors = number_of_floors
self.register_list = register_list
def move(self):
pass;
def register_customer(self, customers):
for reg in customers:
self.register_list.append(reg)
def cancel_customer(self, customers):
pass;
class Customer:
current_floor = 0
destination_floor = 0
customerID = 0
in_elevator = False
finished = False
customer_direction = 0
def __init__(self, customerID, floors):
self.customerID = customerID
self.current_floor = random.randint(1, floors)
self.destination_floor = random.randint(1, floors)
while self.destination_floor == self.current_floor:
self.desination_floor = random.randint(1, floors)
if self.current_floor < self.destination_floor:
self.customer_direction = 1
else:
self.customer_direction = -1
def header(): # elevator animation at beginning of program
print(" ELEVATOR OPENING ")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print(" ")
time.sleep(.2)
print(" ELEVATOR CLOSING ")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
def main():
try:
floors = int(input('Enter the number of floors: '))
customers = int(input('Enter number of customers: '))
building = Building(floors, customers)
except ValueError:
print('YOU DIDNT ENTER A NUMBER. START AGAIN.')
main()
if __name__ == "__main__":
main()
You haven't indented the functions in your Building class.
My attempt is as below, it captures well when i'm typing, but sucks if multiple key pressed. It only capture the first pressed key.
I removed all unrelated to keylogging.
import win32console
import win32gui
import pythoncom, pyHook
import threading
import pickle
class keylogger(object):
def init(self, ifPrintDetail = False):
self.keylog_enable = False
self.ifPrintDetail = ifPrintDetail
self.log = ''
def KeyEvent(self, event):
if self.keylog_enable:
self.log += event.Key
if self.ifPrintDetail:
print ('MessageName:',event.MessageName )
print ('Message:',event.Message)
print ('Time:',event.Time)
print ('Window:',event.Window)
print ('WindowName:',event.WindowName)
print ('Ascii:', event.Ascii, chr(event.Ascii) )
print ('Key:', event.Key)
print ('KeyID:', event.KeyID)
print ('ScanCode:', event.ScanCode)
print ('Extended:', event.Extended)
print ('Injected:', event.Injected)
print ('Alt', event.Alt)
print ('Transition', event.Transition)
print ('---')
elif event.MessageName == 'key down':
print(event.Key, end='')
def threadkeylog(self):
win = win32console.GetConsoleWindow()
win32gui.ShowWindow(win, 0)
# create a hook manager object for both key up and down
self.hm=pyHook.HookManager()
#i want both up and down key event
self.hm.KeyDown = self.KeyEvent
self.hm.KeyUp = self.KeyEvent
# set the hook
self.hm.HookKeyboard()
#start sending messages, this seems not to stop except WM_QUIT
pythoncom.PumpMessages()
def go(self):
#build and start a thread
self.keylog_enable = True
self.threadkl = threading.Thread(target = self.threadkeylog)
self.threadkl.start()
def pause(self):
self.keylog_enable = False
def save(self):
pickle.dump(self.log, open('keylog.txt', 'wb'))
You may use it with
kl = keylogger()
kl.init()
kl.go()#build and run a thread
kl.pause()#"pause" the thread
kl.save()#will save what you have typed to a file in working directory
print(pickle.load(open('keylog.txt', "rb")))#take a look at it
I do this to collect key log of myself playing car racing game, for training data of my machine learning project. So, say, if I control my racing car with simple "WASD" buttons, I would probably hold "W" and "A" to turn left and accelerate. So, I would like to have both of them captured at the same time, but those keys conflicts, and it capture only one character.
Using ctypes alone you can make quite an effective keylogger.
ctypes allows you to check if a key is currently pressed, or toggled.
If you set up a dictionary where all the keys are virtual keycodes and all of the values are the keycode's respective string character then you can iterate through the dictionary, and check if the key is pressed.
Having another dictionary called TrackedKeys which is empty, you can just set TrackedKeys[key] = The bool returned by the ctypes function which sees if a key is pressed when you are ticking in your "main loop" (A while true in the main python file).
then when you update the value of trackedkeys before doing so you can see if the value in trackedkey is different from the value returned by ctypes checking if a key is pressed, and if it is then call a function and pass either "key up" or "key down" to that function.
import threading, time
from ctypes import *
class Thread():
def __init__(self, addressOf, args):
self.terminate = False
self.Instance = threading.Thread(target=addressOf, args=args)
self.Instance.daemon = True
self.Instance.start()
VKStr = {}
VKStr[0x01] = "LEFT_MOUSEE"
VKStr[0x02] = "RIGHT_MOUSE"
VKStr[0x03] = "MIDDLE_MOUSE"
VKStr[0x08] = "BACKSPACE"
VKStr[0x09] = "TAB"
VKStr[0x0D] = "ENTER"
VKStr[0x10] = "SHIFT"
VKStr[0x11] = "CTRL"
VKStr[0x12] = "ALT"
VKStr[0x14] = "CAPSLOCK"
VKStr[0x18] = "ESCAPE"
VKStr[0x20] = " "
VKStr[0x25] = "LEFT_ARROW"
VKStr[0x26] = "UP_ARROW"
VKStr[0x27] = "RIGHT_ARROW"
VKStr[0x28] = "DOWN_ARROW"
VKStr[0x2C] = "PRINT_SCREEN"
VKStr[0x30] = "0"
VKStr[0x31] = "1"
VKStr[0x32] = "2"
VKStr[0x33] = "3"
VKStr[0x34] = "4"
VKStr[0x35] = "5"
VKStr[0x36] = "6"
VKStr[0x37] = "7"
VKStr[0x38] = "8"
VKStr[0x39] = "9"
VKStr[0x41] = "a"
VKStr[0x42] = "b"
VKStr[0x43] = "c"
VKStr[0x44] = "d"
VKStr[0x45] = "e"
VKStr[0x46] = "f"
VKStr[0x47] = "g"
VKStr[0x48] = "h"
VKStr[0x49] = "i"
VKStr[0x4A] = "j"
VKStr[0x4B] = "k"
VKStr[0x4C] = "l"
VKStr[0x4D] = "m"
VKStr[0x4E] = "n"
VKStr[0x4F] = "o"
VKStr[0x50] = "p"
VKStr[0x51] = "q"
VKStr[0x52] = "r"
VKStr[0x53] = "s"
VKStr[0x54] = "t"
VKStr[0x55] = "u"
VKStr[0x56] = "v"
VKStr[0x57] = "w"
VKStr[0x58] = "x"
VKStr[0x59] = "y"
VKStr[0x5A] = "z"
ShiftEquivs={}
ShiftEquivs[0x30] = ")"
ShiftEquivs[0x31] = "!"
ShiftEquivs[0x32] = "\""
ShiftEquivs[0x33] = "£"
ShiftEquivs[0x34] = "$"
ShiftEquivs[0x35] = "%"
ShiftEquivs[0x36] = "^"
ShiftEquivs[0x37] = "&"
ShiftEquivs[0x38] = "*"
ShiftEquivs[0x39] = "("
ActiveKeys = {}
def StringToVK(string):
for key, value in VKStr.items():
if value == string:
return key
def VKToString(VK):
return VKStr[VK]
def IsKeyPressed(VK_KEYCODE):
if type(VK_KEYCODE) == str:
try:
VK_KEYCODE = StringToVK(VK_KEYCODE)
except:
raise Exception("Exception caught in sub: 'IsKeyPressed' arg VK_KEYCODE is invalid")
return
return windll.user32.GetKeyState(c_int(VK_KEYCODE)) & 0x8000 != 0
def IsKeyToggled(VK_KEYCODE):
return windll.user32.GetKeyState(c_int(VK_KEYCODE)) & 0x0001 != 0
class KeyTracker:
def __init__(self):
self.tracking = False
self.tracked_string_concat = ""
self.file_open = False
def StartTracking(self):
self.tracking = True
def StopTracking(self):
self.tracking = False
self.CompileData()
def KeyDown(self, key):
if self.tracking and VKToString(key) != "SHIFT":
if IsKeyToggled(StringToVK("CAPSLOCK")):
self.tracked_string_concat = self.tracked_string_concat + VKToString(key).upper()
elif IsKeyPressed(StringToVK("SHIFT")):
shiftEquiv = False
try:
ShiftEquivs[key]
shiftEquiv = True
except:
pass
if shiftEquiv:
self.tracked_string_concat = self.tracked_string_concat + ShiftEquivs[key]
else:
self.tracked_string_concat = self.tracked_string_concat + VKToString(key).upper()
else:
self.tracked_string_concat = self.tracked_string_concat + VKToString(key)
def KeyUp(self, key):
if self.tracking and VKToString(key) == "SHIFT":
#self.tracked_string_concat = self.tracked_string_concat + VKToString(key)
pass
def UpdateKeyState(self, key, state):
def SetKeyState(key, state):
ActiveKeys[key] = state
if state == True:
self.KeyDown(key)
elif state == False:
self.KeyUp(key)
keyExists = False
try:
ActiveKeys[key]
keyExists = True
except:
pass
if keyExists:
if ActiveKeys[key] != state:
SetKeyState(key, state)
else:
SetKeyState(key, state)
def CompileData(self):
try:
file = open("logger_data.txt", "a")
file.write("\n")
file.write("-"*15)
file.write("\n")
file.write(self.tracked_string_concat)
file.close()
except:
pass
def TrackData(self, time_length): #timeLength in seconds
KeyTracker.StartTracking()
time.sleep(time_length)
KeyTracker.StopTracking()
KeyTracker = KeyTracker()
t = Thread(KeyTracker.TrackData, [5])
while True:
for key, key_name in VKStr.items():
KeyTracker.UpdateKeyState(key, IsKeyPressed(key))
change the argument passed to the thread stored in the variable t to change how long your keylogger records data for, 5 is just a short testing value.
I am trying to make a tool that will encode/decode a string according to values in a dictionary however, I am stuck with the following code:
class edt():
e_dic = {}
def main(self):
c = "hcqnxmytwukgirzoeaspdfvlbj"
a = "abcdefghijklmnopqrstuvwxyz"
e_dic = {}
for i in range(len(c)):
e_dic[a[i]] = c[i]
e_dic[" "] = " "
self.e_dic = e_dic
e = edt()
user_input = raw_input("1.Encode\n2.Decode\n")
if user_input == "1":
e.encode()
elif user_input == "2":
e.decode()
else:
False
def encode(self):
print("test")
def decode(self):
print("test")
def run():
run_main = None
run_main = edt()
run_main.main()
I have omitted encode() and decode() as I don't think that they are causing the problem.
The problem is that this happens when I run it:
>>run()
1.Encode
2.Decode
>>
(The script pauses here to wait for the return key to be pressed, but does nothing regardless of the input given)
>>
I am given no error after this completes. Any help would be greatly appreciated
The code looks fine. But shouldn't you be using an object to call the method? like so
class edt():
e_dic = {}
def encode(self):
print "encoded "
def decode(self):
print "decoded "
def main(self):
c = "hcqnxmytwukgirzoeaspdfvlbj"
a = "abcdefghijklmnopqrstuvwxyz"
e_dic = {}
for i in range(len(c)):
e_dic[a[i]] = c[i]
e_dic[" "] = " "
self.e_dic = e_dic
e = edt()
user_input = raw_input("1.Encode\n2.Decode\n")
if user_input == "1":
e.encode()
elif user_input == "2":
e.decode()
else:
False
def run():
run_main = None
run_main = edt()
run_main.main()
Output:
>>> run()
1.Encode
2.Decode
1
encoded
Fiddle here:
http://ideone.com/9eET4T
You need to use self in encode and decode.
class edt(object):
def __init__(self):
self.e_dic = {}
def main(self):
c = "hcqnxmytwukgirzoeaspdfvlbj"
a = "abcdefghijklmnopqrstuvwxyz"
for i in range(len(c)):
self.e_dic[a[i]] = c[i]
self.e_dic[" "] = " "
user_input = raw_input("1.Encode\n2.Decode\n")
if user_input == "1":
self.encode()
elif user_input == "2":
self.decode()
else:
return False
def encode(self):
print("test")
def decode(self):
print("test")
def run():
run_main = None
run_main = edt()
run_main.main()
run()
I have written the code below to handle and collect perfomance counters (including the test lines (at the end of the code)).
However, when I call the function getAndReset(), it seems to reset the values to Zero before outputting the current value of lendingStats dictionary. This is despite the fact that within the function getAndReset() , the lendingStats value is updated first then stored in a variable theStats.
#!/usr/bin/python
import threading
import time, datetime,pytz
startTime = datetime.datetime.now(pytz.timezone('Africa/Nairobi')).strftime('%Y-%m-%d %H:%M:%S%z')
lendingStats = {'ussdRequests':{'getSubInfo':None,'loanRequests':None},'time':{'startTime':startTime,'currentTime':startTime,'last-reset-time:':startTime}}
lendingStatsNow = {'ussdRequests':{'getSubInfo':None,'loanRequests':None},'time':{'startTime':startTime,'currentTime':startTime,'last-reset-time:':startTime}}
subInfoCounter = dict()
loanRequestCounter = dict()
currentTime = startTime
lastResetTime = startTime
def synchronized(func):
func.__lock__ = threading.RLock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
#synchronized
def lastResetTimeFunc(action):
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
if action == "Get":
return lastResetTime
elif action == "Update":
lastResetTime = datetime.datetime.now(pytz.timezone('Africa/Nairobi')).strftime('%Y-%m-%d %H:%M:%S%z')
##synchronized
def getAndReset():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
# Get the values to return
theStats = dict()
theStats = getLendingStats()
resetStats()
return theStats
#synchronized
def resetStats():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
ussdSubInfoStatsFunc(action="Reset")
ussdLoanReqStatsFunc(action="Reset")
lastResetTimeFunc("Update")
#synchronized
def getLendingStats():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
# Get the values
# lendingStats['ussdRequests']['getSubInfo'] = ussdSubInfoStatsFunc(action="Get")
# lendingStats['ussdRequests']['loanRequests'] = ussdLoanReqStatsFunc(action="Get")
# lendingStats['time']['last-reset-time'] = lastResetTimeFunc("Get")
# lendingStats['time']['currentTime'] = getCurrentTimeFunc()
returnValue = dict()
for KeyName in lendingStats.iterkeys():
returnValue[KeyName] = dict()
returnValue['ussdRequests']['getSubInfo'] = ussdSubInfoStatsFunc(action="Get")
returnValue['ussdRequests']['loanRequests'] = ussdLoanReqStatsFunc(action="Get")
returnValue['time']['last-reset-time'] = lastResetTimeFunc("Get")
returnValue['time']['currentTime'] = getCurrentTimeFunc()
returnValue['time']['startTime'] = lendingStats['time']['startTime']
lendingStats = returnValue
# Return the Values
return returnValue
#synchronized
def getCurrentTimeFunc():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
currentTime = datetime.datetime.now(pytz.timezone('Africa/Nairobi')).strftime('%Y-%m-%d %H:%M:%S%z')
theTime = currentTime
return theTime
#synchronized
def ussdLoanReqStatsFunc(**kwargs):
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
if kwargs['action'] == "Add":
if loanRequestCounter.has_key(kwargs['respcode']):
if loanRequestCounter[kwargs['respcode']].has_key(kwargs['denom']):
currentcount = loanRequestCounter[kwargs['respcode']][kwargs['denom']]
loanRequestCounter[kwargs['respcode']][kwargs['denom']] = currentcount + 1
else:
loanRequestCounter[kwargs['respcode']][kwargs['denom']] = 1
else:
loanRequestCounter[kwargs['respcode']] = dict()
loanRequestCounter[kwargs['respcode']][kwargs['denom']] = 1
elif kwargs['action'] == "Reset":
for respCodeKeyName in loanRequestCounter.iterkeys():
for denomKeyName in loanRequestCounter[respCodeKeyName].iterkeys():
loanRequestCounter[respCodeKeyName][denomKeyName] = 0
elif kwargs['action'] == "Get":
theDict = loanRequestCounter
return theDict
#synchronized
def ussdSubInfoStatsFunc(**kwargs):
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
if kwargs['action'] == "Add":
if subInfoCounter.has_key(kwargs['respcode']):
currentcount = subInfoCounter[kwargs['respcode']]
subInfoCounter[kwargs['respcode']] = currentcount + 1
else:
subInfoCounter[kwargs['respcode']] = 1
elif kwargs['action'] == "Reset":
for keyname in subInfoCounter.iterkeys():
subInfoCounter[keyname] = 0
elif kwargs['action'] == "Get":
theDict = subInfoCounter
return theDict
def testSubInfoCounter(KeyName,numOfEvents):
i = 0
while i < numOfEvents:
ussdSubInfoStatsFunc(action="Add",respcode=KeyName)
i +=1
print ussdSubInfoStatsFunc(action="Get")
def testLoanReqCounter(respCodeT,theDenom,numOfEvents):
i = 0
while i < numOfEvents:
ussdLoanReqStatsFunc(action="Add",respcode=respCodeT,denom=theDenom)
i +=1
print ussdLoanReqStatsFunc(action="Get")
thread1 = threading.Thread(target = testLoanReqCounter("0","200",7767))
thread2 = threading.Thread(target = testLoanReqCounter("1","1000",55))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print "At the beginning:"
print getLendingStats()
print getAndReset()
testSubInfoCounter("9",7)
testSubInfoCounter("0",7000)
testLoanReqCounter("0","200",7767)
testLoanReqCounter("1","200",33)
testLoanReqCounter("0","1000",3928)
testLoanReqCounter("1","1000",55)
testLoanReqCounter("0","5000",492)
testSubInfoCounter("1",3000)
testSubInfoCounter("3",1000)
testSubInfoCounter("0",7000)
print "Cumulatively:"
print getAndReset()
# print getLendingStats()
# resetStats()
time.sleep(3)
print "After the Reset"
# print getLendingStats()
# resetStats()
print getAndReset()
testLoanReqCounter("0","200",7767)
testLoanReqCounter("1","200",33)
testLoanReqCounter("0","1000",3928)
testLoanReqCounter("1","1000",55)
testLoanReqCounter("0","5000",492)
print getLendingStats()
resetStats()
testSubInfoCounter("1",3230)
testSubInfoCounter("3",1901)
testSubInfoCounter("0",76887)
print getAndReset()
time.sleep(4)
print getAndReset()
# print getLendingStats()
# resetStats()
The problem here is that I needed to use a deepcopy as opposed to a simple assignment (which uses a simple copy).
Therefore the code that I needed to change was:
import copy
#synchronized
def getAndReset():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
# Get the values to return
theStats = copy.deepcopy(getLendingStats())
resetStats()
return theStats
can somebody tell me how to use this class timers from python in my code more than one time.
import MOD
class timer:
def __init__(self, seconds):
self.start(seconds)
def start(self, seconds):
self.startTime = MOD.secCounter()
self.expirationTime = self.startTime + seconds
if seconds != 0:
self.running = 1
self.expired = 0
else:
self.running = 0
self.expired = 0
def stop(self):
self.running = 0
self.expired = 0
def isexpired(self):
if self.running == 1:
timeNow = MOD.secCounter()
if timeNow > self.expirationTime:
self.running = 0
self.expired = 1
else:
self.expired = 0
return self.expired
def isrunning(self):
if self.running == 1:
timeNow = MOD.secCounter()
if timeNow > self.expirationTime:
self.running = 0
self.expired = 1
else:
self.expired = 0
return self.running
def change(self, seconds):
self.expirationTime = self.startTime + seconds
def count(self):
if self.running == 1:
timeNow = MOD.secCounter()
return (timeNow - self.startTime)
else:
return -1
they write this comment:
The following is a simple example about how to use this class:
import timers
timerA = timers.timer(0)
timerA.start(15)
while 1:
if timerA.isexpired():
print 'timerA expired'
break
but I don't know how to use it more than one time in my code, because I need to use more than one timer in my code,
should I write
timerB = timers.timer(1)
timerB.start(1800)
while 1:
if timerB.isexpired():
print 'timerA expired'
break
any help, please
Close - the argument to timers.timer is the number of seconds that the timer should time for at first. But every time you call timers.timer(), you'll get a new timer instance.
So your code could look more like:
timerB = timers.timer(1800)
while 1:
if timerB.isexpired():
print 'timerA expired'
break
Except that this is misleading - timerA and timerB are separate timers, so timerB.isexpired() won't tell you anything about timerA. Maybe you meant it to read "timerB expired"?
And I would also advise against polling timerB.isexpired() so rapidly. Maybe sleep for a second after each check?