Exit try attempt after a given time in Python - python

I have a function which sends a request to a server. But sometimes the server doesn't reply and my code doesn't seem to continue. Now I wanted to implement, that the code continues to run, if no reply is received after a given amount of time. Below the code:
for attempt in range (3):
try:
print('Attempt: ' + str(attempt+1))
print('DUT: ' + str(x))
time.sleep(1)
response = request("http://" + ipEntry.get() + port, "temperature_test", x)
time.sleep(1)
print(response.text)
print(response.data.result)
answer = response.data.result
logFile.write(time.strftime("%Y_%m_%d-%H_%M_%S\t\t") + str(x) + "\t\t" + str(answer) + "\t\t" + str(readVoltage()) + "\t\t" + str(readCurrent()) + "\n")
except:
print('An error occured!')
else:
if (response.data.result==False):
print("Attempt " + str(attempt + 1) + " failed!")
else:
break
else:
print('All 3 attempts failed')
Is it possible to start a counter after the beginning of this function and check with an "if" statement if it has elapsed?
Thanks for any hints and best regards!

Related

discord.py message.channel.send not working

I am making a blackjack game using discord.py, I am changing the value of Ace from 11 to 1 instead but no message is being sent to the channel and I am not getting any errors.
def ask_A(self):
num_A = []
for c in range(0, len(self.deck)):
if self.deck[c].get_value() == "A" and self.deck[c].get_points() == 11:
num_A.append(c)
for i in num_A:
message.channel.send(
"Your current cards are " + str(self.print_cards()) + ", Total is " + str(self.sum_cards()) + "\n")
self.deck[i].change_points(1)
message.channel.send("Changed value of Ace to prevent loss")
message.channel.send("Your cards are " + str(self.print_cards()) + ", Total is " + str(self.sum_cards()) + "\n")
You're forgetting to await your statements. Anything in the docs that is a coroutine needs to have await expression.
Example:
await message.channel.send("Hello! This is my message")
Read up about Async IO here.

Python notification

Is there a way for me to bring what is inside of 'a' into the message?
a = print("You have shown",top1.value,"and",top2.value)
notification.notify(title="Facial Expression" , message =" ", app_icon=None, timeout=3,)
The print() method does not return a value.
a = "You have shown " + top1.value + " and " + top2.value
print(a)
notification.notify(title="Facial Expression", message=a, app_icon=None, timeout=3,)

How to make this loop succesful after a succesful attempt?

The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently the code will keep executing the function even if it succeeds. Modify the code so that it stops trying after the operation succeeded.
def retry(operation, attempts):
for n in range(attempts):
if operation():
print("Attempt " + str(n) + " succeeded")
else:
print("Attempt " + str(n) + " failed")
retry(create_user, 3)
retry(stop_service, 5)
Add a break to exit the loop when the operation() i successful:
def retry(operation, attempts):
for n in range(attempts):
if operation():
print("Attempt " + str(n) + " succeeded")
break
else:
print("Attempt " + str(n) + " failed")
Try break to exit from the loop if operation() is successful.
def retry(operation, attempts):
for n in range(attempts):
if operation():
print("Attempt " + str(n) + " succeeded")
break
else:
print("Attempt " + str(n) + " failed")
retry(create_user, 3)
retry(stop_service, 5)
Your result should look like :
Attempt 0 failed
Attempt 1 failed
Attempt 2 succeeded
Attempt 0 succeeded
Attempt 0 failed
Attempt 1 failed
Attempt 2 failed
Attempt 3 succeeded
None
I believe there is some issues with this question, the marked correct output for this question is:
Attempt 0 failed
Attempt 1 failed
Attempt 2 succeeded
Attempt 0 succeeded
Attempt 0 failed
Attempt 1 failed
Attempt 2 failed
Attempt 3 succeeded
None
There are two function calls, one with create_user and one with stop_service, however, even after the first two "succeeded" occurred, the program continues to go.
def retry(operation, attempts):
for n in range(attempts):
if operation():
print("Attempt " + str(n) + " succeeded")
break # will stop the loop when or if this is line reached
else:
print("Attempt " + str(n) + " failed")
retry(create_user, 3)
retry(stop_service, 5)
You should use break keyword to stop the loop when needed, or even return would be suitable in that situation.
Python loop reference
Try using a try and except block
def retry(operation,attempts):
for attempt in range(attempts):
try:
if operation():
operation()
print('Attempt '+str(attempt)+' succeded')
break
else:continue
except:
continue
retry(create_user,4)
This will catch any exception if any was thrown.
Use break after the if before the else. There is a problem with the question (or it is misleading), but break is correct.
def retry(operation, attempts):
for n in range(attempts):
if operation():
print("Attempt " + str(n) + " succeeded")
break
else:
continue
print("Attempt " + str(n) + " failed")
retry(create_user, 3)
retry(stop_service, 5

How to fix this AttributeError

I am trying to access a variable within a function in a class and print it. Whenever I try I keep getting the error: AttributeError: 'NoneType' object has no attribute 'job_ID'.
def driver():
q = my_queue.Queue_()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
print("The prority of the job is: " + q.new_item.job_priority)
print("The job type is: " + q.new_item.job_type)
if 'respond' in line:
q.dequeue()
print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
if 'active' in line:
q.active_jobs()
print("Total number of jobs: " + str(len(q.temp)))
print("Average priority: " + str(q.average))
if 'modify' in line:
q.modify(line)
print("Modified job " + q.current.job_ID)
The error is coming from the last print statement in this code.
This is the function within the class that is being used here:
def modify(self, x): # need to fix printing bug
self.current = self.head
while self.current != None:
if x[1] in self.current.get_data():
self.current.data[2] = x[2]
self.current.data[3] = x[3]
break
# print("Modified job " + current.job_ID)
else:
# print('The job details cannot be modified.')
pass
self.current = self.current.get_next()
The exit condition for the loop in the modify function that you have provided is self.current == None.
When you call modify() in this last conditional statement:
if 'modify' in line:
q.modify(line) // here
print("Modified job " + q.current.job_ID)
You are making q.current evaluate to None. Therefore, the reason why you are getting an AttributeError is because q.current is None, which has no such attribute called job_ID.
To fix your problem, you must ensure that q.current is not None before printing q.current.job_ID. I can't give you any help beyond this, since I don't know what the purpose of your program is.

Python Multiprocessing - Too Slow

I have built a multiprocessing password cracker (using a wordlist) for a specific function, it halved the time needed compared to using a single process.
The original problem being that it would show you the cracked password and terminate the worker, but the remaining workers would carry on until they ran out of words to hash! not ideal.
My new step forward is to use Manager.Event() to terminate the remaining workers, this works as I had hoped (after some trial and error), but the application now takes far longer that it would take as a single process, I'm sure this must be due to the if function inside pwd_find() but I thought I would seek some advice.
#!/usr/bin/env python
import hashlib, os, time, math
from hashlib import md5
from multiprocessing import Pool, cpu_count, Manager
def screen_clear(): # Small function for clearing the screen on Unix or Windows
if os.name == 'nt':
return os.system('cls')
else:
return os.system('clear')
cores = cpu_count() # Var containing number of cores (Threads)
screen_clear()
print ""
print "Welcome to the Technicolor md5 cracker"
print ""
user = raw_input("Username: ")
print ""
nonce = raw_input("Nonce: ")
print ""
hash = raw_input("Hash: ")
print ""
file = raw_input("Wordlist: ")
screen_clear()
print "Cracking the password for \"" + user + "\" using "
time1 = time.time() # Begins the 'Clock' for timing
realm = "Technicolor Gateway" # These 3 variables dont appear to change
qop = "auth"
uri = "/login.lp"
HA2 = md5("GET" + ":" + uri).hexdigest() # This hash doesn't contain any changing variables so doesn't need to be recalculated
file = open(file, 'r') # Opens the wordlist file
wordlist = file.readlines() # This enables us to use len()
length = len(wordlist)
screen_clear()
print "Cracking the password for \"" + user + "\" using " + str(length) + " words"
break_points = [] # List that will have start and stopping points
for i in range(cores): # Creates start and stopping points based on length of word list
break_points.append({"start":int(math.ceil((length+0.0)/cores * i)), "stop":int(math.ceil((length+0.0)/cores * (i + 1)))})
def pwd_find(start, stop, event):
for number in range(start, stop):
if not event.is_set():
word = (wordlist[number])
pwd = word.replace("\n","") # Removes newline character
HA1 = md5(user + ":" + realm + ":" + pwd).hexdigest()
hidepw = md5(HA1 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2).hexdigest()
if hidepw == hash:
screen_clear()
time2 = time.time() # stops the 'Clock'
timetotal = math.ceil(time2 - time1) # Calculates the time taken
print "\"" + pwd + "\"" + " = " + hidepw + " (in " + str(timetotal) + " seconds)"
print ""
event.set()
p.terminate
p.join
else:
p.terminate
p.join
if __name__ == '__main__': # Added this because the multiprocessor module sometimes acts funny without it.
p = Pool(cores) # Number of processes to create.
m = Manager()
event = m.Event()
for i in break_points: # Cycles though the breakpoints list created above.
i['event'] = event
a = p.apply_async(pwd_find, kwds=i, args=tuple()) # This will start the separate processes.
p.close() # Prevents any more processes being started
p.join() # Waits for worker process to end
if event.is_set():
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
else:
screen_clear()
time2 = time.time() # Stops the 'Clock'
totaltime = math.ceil(time2 - time1) # Calculates the time taken
print "Sorry your password was not found (in " + str(totaltime) + " seconds) out of " + str(length) + " words"
print ""
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
Edit (for #noxdafox):
def finisher(answer):
if answer:
p.terminate()
p.join()
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
def pwd_find(start, stop):
for number in range(start, stop):
word = (wordlist[number])
pwd = word.replace("\n","") # Removes newline character
HA1 = md5(user + ":" + realm + ":" + pwd).hexdigest()
hidepw = md5(HA1 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2).hexdigest()
if hidepw == hash:
screen_clear()
time2 = time.time() # stops the 'Clock'
timetotal = math.ceil(time2 - time1) # Calculates the time taken
print "\"" + pwd + "\"" + " = " + hidepw + " (in " + str(timetotal) + " seconds)"
print ""
return True
elif hidepw != hash:
return False
if __name__ == '__main__': # Added this because the multiprocessor module sometimes acts funny without it.
p = Pool(cores) # Number of processes to create.
for i in break_points: # Cycles though the breakpoints list created above.
a = p.apply_async(pwd_find, kwds=i, args=tuple(), callback=finisher) # This will start the separate processes.
p.close() # Prevents any more processes being started
p.join() # Waits for worker process to end
You can use the Pool primitives to solve your problem. You don't need to share an Event object which access is synchronised and slow.
Here I give an example on how to terminate a Pool given the desired result from a worker.
You can simply signal the Pool by returning a specific value and terminate the pool within a callback.
I think your hunch is correct. You are checking a synchronization primitive inside a fast loop. I would maybe only check if the event is set every so often. You can experiment to find the sweet spot where you check it enough to not do too much work but not so often that you slow the program down.

Categories