Iterating and keeping track of count - python

I am trying to iterate through a bit of code with a delay and also keep count of the time it's run.
I believe I have to use a while loop and a sleep loop but I'm unsure as to how they'd look together.
def download_image():
while True:
try:
image = requests.get(newmeme).content
except requests.RequestError:
print("Retrying downloading")
time.sleep(2 * 60)
else:
break
with open('image.jpg', 'wb') as f:
f.write(image)
print("Download done.")
def upload_image(count):
while True:
try:
twitter_API.update_with_media("image.jpg", status="dankmeme #{}".format(count))
except tweepy.TweepError:
print("Retrying uploading")
time.sleep(2 * 60)
else:
break
print("Image #{} uploaded at {:%H:%M}".format(count, datetime.now()))
count = 0
while True:
download_image()
upload_image()
count = count+1
time.sleep(300)

Related

i am trying to increase my number by 1 every time my code runs

the problem i'm having is that every time i go to a new function and then go back to the first one, the count starts over.yo(driver) random(driver) yo(driver). the second time i do yo(driver) the count starts over and if i place count = 0 outside of the function then it comes up as an unresolved reference inside of the function. is there any simple way i can get it keep counting and not start over?
timeout = time.time()+2
def yo(driver):
count = 0
while True:
try:
print("try 1")
count += 1
except:
print("except 1")
else:
print("else 1")
finally:
print("finally 1")
if time.time() > timeout:
print("timeout")
print("count", count)
break
def random(driver):
print("yoyo")
yo(driver)
random(driver)
yo(driver)
Try this, you can declare a method specific variable and have its state be updated each time you change it during method invocation.
def yo():
yo.count += 1
print(yo.count)
yo.count = 0
yo()
yo()
Output:
1
2
import time
timeout = time.time()+2
def yo():
while True:
try:
print("try 1")
yo.count += 1
except:
print("except 1")
else:
print("else 1")
finally:
print("finally 1")
if time.time() > timeout:
print("timeout")
print("count", yo.count)
break
yo.count = 0
yo()
You can define count as a global variable, and define it a global inside your function:
count = 0
def yo(driver):
global count
while True:
try:
print("try 1")
count += 1
except:
print("except 1")
else:
print("else 1")
finally:
print("finally 1")
if time.time() > timeout:
print("timeout")
print("count", count)
break
Or you can pass it as a function argument:
def yo(driver, count):
while True:
try:
print("try 1")
count += 1
except:
print("except 1")
else:
print("else 1")
finally:
print("finally 1")
if time.time() > timeout:
print("timeout")
print("count", count)
break
return count
count = 0
count = yo(driver, count)
random(driver)
count = yo(driver, count)

Is it possible to loop through something while an exception remains? | Python

I was wondering if you could loop through an exception until it becomes false just like this:
try:
get_element = driver.find_element_by_xpath('xpath')
except as ElementTime:
while ElementTime is True:
sleep(1)
get_element = driver.find_element_by_xpath('xpath')
What you need is something like this:
while True:
try:
get_element = driver.find_element_by_xpath('xpath')
break
except as ElementTime:
sleep(1)
You could also include a limit on the number of trials, by including a count variable and if it crosses a limit then you could break out of the loop. This would save you from an infinite loop in case the element at the xpath is not rendered.
count = 0
max_trials = 10
while count < max_trials:
try:
max_trials += 1
get_element = driver.find_element_by_xpath('xpath')
break
except as ElementTime:
sleep(1)

Is there anyway to add a Defusal Sequence whilst a countdown is happening

I am attempting to program a defusable bomb for a csgo prop and was trying to make it as close as i can to the original thing. I have got everything working smoothly. An entry code and a Timer. The only thing I need to do is add a defusable section to it. Whilst the Bombs timer is running I would need to be able to cancel that action with an Input Code. Where, and what would I put?
I have tried doing a
defuse = input("Defusal Code")
if defuse == "7355608":
break
import time
while True:
uin = input("")
try:
when_to_stop = abs(int(uin))
except KeyboardInterrupt:
break
except:
print("NAN!")
while when_to_stop > 0:
s, ms = divmod(when_to_stop, 100)
m, s = divmod(s, 60)
time_left = str(m).zfill(2) + ":" + str(s).zfill(2) + ":" + str(ms).zfill(2)
print(time_left, end="\r")
time.sleep(0.01)
when_to_stop -=1
print()
print("BOMB DETONATED")

Queue runs successfully! Exits instead of continue, after Break

I am using this script to resolve thousands of domains. It runs successfully, and ends when the queue is empty. I am trying to it to break out of the loop and continue the script by printing.
How do I get this code to break out of the loop, ans print, when the queue is empty?
q = queue.Queue()
for name in names:
q.put(name)
def async_dns():
s = adns.init()
while True:
try:
dname = q.get(False)
q.task_done()
except queue.Empty:
return
response = s.synchronous(dname,adns.rr.NS)[0]
if response == 0:
dot_net.append("Y")
print(dname + ", is Y")
elif response == 300 or response == 30 or response == 60:
dot_net.append("N")
print(dname + ", is N")
threads = []
for i in range(20):
t = threading.Thread(target=async_dns)
threads.append(t)
t.start()
print("Done !!")
You could simply move the code that does the dns lookup and prints the result into the body of the try/except block:
def async_dns():
s = adns.init()
while True:
try:
dname = q.get(False)
response = s.synchronous(dname,adns.rr.NS)[0]
if response == 0:
dot_net.append("Y")
print(dname + ", is Y")
elif response == 300 or response == 30 or response == 60:
dot_net.append("N")
print(dname + ", is N")
q.task_done()
except queue.Empty:
return
Now when the queue is empty a queue.Empty will be raised and the exception handler will simply exit the thread function, otherwise it will print out the dns values.

Repeat an iteration in loop if error occurs

Is there a command such as break and continue which could repeat recent iteration?
For example, when exception is thrown.
for i in range(0,500):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
repeat
Let's have an iteration where i variable's value is 6. During this iteration some connection error occurred. I want to repeat this iteration.
Is there a command which can do that?
Of course I can do this:
i=0
while i!=500:
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
pass
No, there is no command to "rewind" a for-loop in Python.
You could use a while True: loop inside the for-loop:
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
continue
else:
break
or without the else::
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
break
except Exception: # Replace Exception with something more specific.
continue
But I personally think that your proposed solution is better because it avoids an indentation level.
for i in range(500):
while True
try:
conn = getConnection(url+str(i))
break
except Exception: # still allows to quit with KeyboardInterrupt
continue
do_your_stuff()
This looks bit risky, however, you should at least enable some logging inside a while block.
If you expect to use it in more places, you might write a simple decorator:
def keep_trying(fn, *args, **kwargs):
def inner(*args, **kwargs):
while True:
try:
return fn(*args, **kwargs)
except Exception:
continue
return inner
# later you can use it simple like this:
for i in range(500):
conn = keep_trying(getConnection)(url+str(i))
You can use generators :
def process_connections(n_connections, url, max_tries=50):
i = 0
try_count = 0
while i < n_connections:
try:
conn = getConnection(url+str(i))
yield conn
except:
try_count += 1
if try_count > max_tries:
raise Exception("Unable to connect after %s tries" % max_tries)
else:
i += 1 # increments only if no exception
And you perform your operations :
for conn in process_connections(500, url):
do_something(conn)
You can use nested for loops to put a cap on the number of times you retry the operation. This is bascially the sam as #PierreAlex's generator answer but without the extra function definition.
for i in range(500):
for retry in range(10):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
time.sleep(1)
else:
print "iteration", i, "failed"
Why not just use an if statement?
n=6
i=0
while i!=500:
failed = False;
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
#handle error
failed = True;
#try again if n-th case failed first time
if(i == n and failed):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
#handle error
Here is one. You would need to add a logging or alert system to let you know that something is stuck:
state = "" #state of the loop
# If there is no error continue. If there is error, remain in loop
while True:
if state != "error":
try:
1/0 # command
break # no error so break out of loop
except:
state = "error" #declare error so maintain loop
continue
elif state == "error": # maintain loop
continue

Categories