Delay between for loop iteration (python) - python

Is this possible in Python? I wrote a great loop/script in Python and I’d like to add this delay to it if at all possible.
map(firefox.open, ['http://www.bing.com/search?q=' + str(i) for i in range(x))], [2] * x)
Where shall I put the sleep(6) in this?

You can do that using time.sleep(some_seconds).
from time import sleep
for i in range(10):
print i
sleep(0.5) #in seconds
Implementation
Here is a cool little implementation of that: (Paste it in a .py file and run it)
from time import sleep
for i in range(101):
print '\r'+str(i)+'% completed',
time.sleep(0.1)
map(firefox.open, ['http://www.bing.com/search?q=' + str(i) for i in range(x))], [2] * x)

Or if you want it to start on one and emulate a stopwatch:
import time
def count_to(number):
for i in range(number):
time.sleep(1)
i += 1
if i >= number:
print('Time is up')
break
print(i)

Yes it is possible in python you should use 'time' module:
>>> import time
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> for i in list1:
time.sleep(1)#sleep for 1 second
print i
output :
1
2
3
4
5
6
7
8
9
10

Related

Pressing infinite number keys in python

so I wanted to create a code in python that automatically type numbers from 1 to 100
and it doesn't work. Hope someone can help
Here's my code
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
n = 1
time.sleep(2)
while 1 == 1:
keyboard.press(n)
keyboard.release(n)
n = n + 1
(I have "pynput" and "time" installed)
I tried reading error and from what I know have I think it's the problem with this characters "", but if I'm gonna add them I will not be able to add bigger number
You can convert the type of the variable to string:
while 1 = 1:
for ch in str(n):
keyboard.press(str(ch))
keyboard.release(str(ch))
n = n + 1
But you need to put a for loop because when the number is over 9, you need to send separately all digits for each number.
check your conditions in while loop
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
n = 1
time.sleep(2)
while n <= 100:
if n <10:
press_key = str(n)
keyboard.press(str(press_key))
keyboard.release(str(press_key))
elif n>=10 and n<=99:
press_key_first_digit = str(n//10)
press_key_second_digit = str(n%10)
keyboard.press(str(press_key_first_digit))
keyboard.release(str(press_key_first_digit))
keyboard.press(str(press_key_second_digit))
keyboard.release(str(press_key_second_digit))
else:
keyboard.press("1")
keyboard.release("1")
keyboard.press("0")
keyboard.release("0")
keyboard.press("0")
keyboard.release("0")
n = n + 1

I want to loop this, and everytime it loops I want +1 so it prints ( 1 2 3.. untill infinite) But it prints 2 1 2 1 2 ... what am I doing wrong?

I want to loop this, and everytime it loops I want +1 so it prints ( 1 2 3 4 5.. untill infinite)
But it prints 1 2 1 2 1 2 1 2 ...
what am i doing wrong?
code:
import time
x = 1
def main():
print(x)
x + 1
time.sleep(1)
print(x+1)
main()
main()
Your code says main does -> print 1, 2, sleep, print 2.
You should do
x = 1
def main():
while true:
print(x)
x += 1
time.sleep(1)
main()
Your original code doesn't alter x. x += 1 means x = x + 1.
x + 1 is just 2. And that 2 doesn't get stored anywhere. And to go on infinitely you just leave a while true loop running and manually kill the code. Although you could put some cap on it like 1000 loops.
You can use an iterator.
By using next() you can ask it what the next number would be and they only get calculated once you actually need them. The limit ist the system size of python-integers in this example.
import sys
maxSize = sys.maxsize
i = iter(range(maxSize))
def main():
print(next(i))
main()
# 0
main()
# 1
main()
# 2
The mistake here is that you're restarting x every time you're caling the function main() beccause there is no loop.
def main():
x = 1
while True:
print(x)
time.sleep(1)
x += 1
main()
Inside the function when you are adding x+1 you are not storing the value back in x to update it. Here is a better implementation.
import time
x = 1
def main():
global x
print(x)
x += 1
time.sleep(1)
while True:
main()
I hope this is the best answer
import time #importing time
def infinitive_loop(): #define new function
x = 1 #making variable x equals 1
while True: #this is the loop
yield x
time.sleep(1)#wait 1 sec.
x += 1#it increases one every time
for x in infinitive_loop():
print(x)#print "x"

Python countdown not line by line

so i tried to create a countdown in python. It works fine, but I want to have a better print output. At the moment it prints the remaining time line by line, so my output is overfilled after some time. I then tried to do:
import time
def countdown(t):
while t:
print(t, end="\r")
time.sleep(1)
t -= 1
print('finished')
countdown(60)
but it outputs for me:
5
4
3
2
1
finished
I'd like to have it that it prints the countdown and the finished all in one line and deletes the number before it...
Thanks for helping :)
Here's what it should look like:
But i dont need the 00:00 format, the seconds are fine for me
almost there, below code will print your timer value side by side. not sure what 'deletes the number before it.' is!
import time
def countdown(t):
while t:
print(t, end=" ")
time.sleep(1)
t -= 1
print('finished')
countdown(60)
Delete the previous character using '\b'
import time
def countdown(t):
# how many digits
digits = int(t / 10) + 1
while t:
print('\b{}'.format(str(t).zfill(digits)), end="\r")
time.sleep(1)
t -= 1
print('finished')
countdown(10)
The following will work if called from Windows CMD
import time, sys, os
def pretty_format(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
# Here's the formatting you asked for! 00:00:59 etc...
return "%d:%02d:%02d" % (hour, minutes, seconds)
def count_down(seconds):
os.system("cls") # Windows -> clear the cmd screen
while seconds:
sys.stdout.write("{}{}".format(pretty_format(seconds), "\b"*100)) # \b replaces the previous value. if we have a bunch of values we need to do multiple \b. Here's 100!
time.sleep(1)
seconds -=1
print('finished')
count_down(60)

Change two lines dyanmically on Python

Let's say I have a counter that counts from 0 to 100000. I don't want all the numbers showed, I just want to see the number we are at end the % of completion.
I know that if I want to rewrite over the line, I must add \r at the beginning. However, if I want to do this on two lines, how am I supposed to do that ?
1
0.001%
then
2
0.002%
Also, let's say I want to add new lines for the numbers, but always keep the percentage at the bottom like this:
1
2
3
4
5
6
7
8
0.008%
Do you have any idea on how to achieve that?
Here is my code so far (doesn't work, obviously):
from sys import stdout
for i in range(100000):
stdout.write(str(i) + '\r\n')
stdout.write('%.2f' % (i / 100000 * 100) + '%\r')
stdout.flush()
stdout.write('\n')
Thank you !
you can use curses module:
import curses
import time
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
n = 100000
num_lines = 10
lst = list(range(n))
for t in [lst[i:i + num_lines] for i in range(0, len(lst), num_lines)]:
final_line = f'{t[-1] / n * 100:.4f}%'
out = '\n'.join(map(str, [*t, final_line]))
stdscr.addstr(0, 0, out)
stdscr.refresh()
time.sleep(0.005) # you can comment but will be too fast
curses.echo()
curses.nocbreak()
curses.endwin()

Python multiprocessing hangs

I am starting to learn multiprocessing in python, but have arrived to a point where my code just hangs. It is simply computing 1 000 000 factorial, using multithreading.
import multiprocessing
def part(n):
ret = 1
n_max = n + 9999
while n <= n_max:
ret *= n
n += 1
print "Part "+ str(n-1) + " complete"
return ret
def buildlist(n_max):
n = 1
L = []
while n <= n_max:
L.append(n)
n += 10000
return L
final = 1
ne = 0
if __name__ == '__main__':
pool = multiprocessing.Pool()
results = [pool.apply_async(part, (x,)) for x in buildlist(1000000)]
for r in results:
x = r.get()
final *= x
ne+= 1
print ne
print final
I have included some print functions to try to diagnose where the code hangs, and it will print the string included in the part function 100 times, as expected. The "print ne" also works 100 times.
The problem is that final won't print, and the code doesn't complete.
How do I fix this problem?
Edit: Also, since this is being downvoted, could someone explain what I am doing wrong/why I am being downvoted?
The program works fine --- until the print final. Then it spends a very large amount of time trying to print this number, which is seriously huge...

Categories

Resources