def data():
a=0
a+=1
print(a)
#if a==5:
#sys.exit()
b=threading.Timer(3, data)
b.start()
if __name__ == "__main__":
data()
①I want to try stop this code about 15 seconds
(Actually,I need to stop the time is about 16200 second, and it's must be very precise )
(i want to know is there a better timer code?)
i have tried many times to make i to be 5,but i don't know how to do
a will be zero everytime.
I'm not sure what the multithreading is about, but if you just want the code to stop in ~15 seconds, I would try this:
import time
import sys
def data():
start = time.time()
while (start-time.time()<=15):
#code
sys.exit()
I don't know what the i is, or what it's keeping track of, but this should work!
About stopping the code for 15 seconds, Why don't just use time.sleep() and about exit the sys.exit() will do the trick like:
import time
import sys
def data():
a=0
a+=1
print(a)
time.sleep(15) #stop the code for 15 seconds
if a==5:
sys.exit()
Related
I want my code to take some integers for some time (e.g. 10 seconds) and to count and print time every second. So it prints time permanently and i enter some numbers whenever i want. Maybe i should use async functions?
def accepting_bets():
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
def main():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
accepting_bets()
if i == 0:
break
print(list_of_bets)
You can move the timing code to a different thread.
I would recommend researching about multi-threading in Python if you aren't aware about it.
import threading
import time
def countTime():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
if i == 0:
break
print(list_of_bets)
thread1 = threading.Thread(target=countTime)
thread1.start()
# while you want to get the input
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
The countTime function will keep on running on another thread, and will not be paused by the input statement
i cant understand the logic used to build a timer that prints "ok" after every 2 seconds in python. Also the body of the while loop . please explain
import time print("start") start=time.time() while True: end = time.time() if (end-start)>=2: print("ok") start=time.time()
There is two methods of doing that:
FIRST:
import time
while True:
time.sleep(2)
print('ok')
SECOND:
import time
oldtime = time.time()
while True:
if oldtime + 2 == time.time(): #time.time() means current time
print('ok')
oldtime = time.time()
If your program must not pause(need to do other things) use the SECOND method if not try the FIRST one it is easy.
If you have any questions just comment this post.
while 1:
wat=water()
if wat==10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first=input("Drank?Y/N")
if first.lower()=="y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
Is there any way to wait for a couple of minutes and if no input is provided, then take the value "n" as input for the first variable?
Guess by default it will wait indefinitely. I tried using a timer function, but it cannot record any input.
What I am trying to do is to track my activities, so if I drink water I say y--> this records my activity and writes it to a file.
All help will be greatly appreciated
Here is how you can use a combination of pyautogui.typewrite, threading.Thread and time.sleep:
from pyautogui import typewrite
from threading import Thread
from time import sleep
a = ''
def t():
sleep(5)
if not a: # If by 5 seconds a still equals to '', as in, the user haven't overwritten the original yet
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
a = input()
b = input() # Test it on b, nothing will happen
Here is the code implemented into your code:
from pyautogui import typewrite
from threading import Thread
from time import sleep
while 1:
wat = water()
if wat == 10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first = 'waiting...'
def t():
sleep(5)
if first == 'waiting...':
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
first = input("Drank?Y/N")
if first.lower() == "y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
I have two files. One with a game with an evil gambler and the other with a loading function to play out between the lines of text. My goal is to replace the time.sleep() functions with my loading function. The first file looks like this:
import random
import time
import test
def game():
string_o = "Opponent "
string_u = "User "
input_n = ""
input_n = input('Care to try your luck?\n')
while input_n == 'yes' or input_n == 'y':
cpu = random.randint(1,6)
user = random.randint(1,6)
time.sleep(0.5)
print('\nGreat!')
time.sleep(0.2)
input_n=input("\nAre you ready?\n")
time.sleep(0.4)
print(string_o , cpu)
#If the gambler's die roll is above three he gets very happy
if cpu > 3:
print('Heh, this looks good')
time.sleep(0.2)
#...but if it's lower he gets very anxious
else:
('Oh, no!')
test.animate()
print(string_u , user)
if cpu < user:
print('Teach me, master')
else:
print('Heh, better luck next time, kid')
time.sleep()
input_n = input('\nDo you want to try again?\n')
print("Heh, didn't think so.\nPlease leave some room for thr big boys")
game()
The other file looks like this:
import itertools
import threading
import time
import sys
done = False
#here is the animation
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
if done:
break
sys.stdout.write('\rloading ' + c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\rDone! ')
t = threading.Thread(target=animate)
t.start()
#would like an x here instead that is defined in the other file
time.sleep(1)
done = True
The problem is that the function animate() plays out before the game has even started.
I would also like to set the time for the loading function in my main game file. Is that possible?
By putting t.start() outside of any function in your test.py, you are running animate as soon as you import test.py. You should put t.start() inside a function instead. Also, your done flag is also set to True when test.py is imported and will always immediately break your for loop inside animate. I don't think you really need this flag at all. Change your test.py to:
import itertools
import threading
import time
import sys
#here is the animation
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
sys.stdout.write('\rloading ' + c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\rDone! ')
def start():
t = threading.Thread(target=animate)
t.start()
And then in your first file, instead of calling test.animate() directly, call test.start() instead.
I need to say that multiprocessing is something new to me. I read some about it but it makes me more confused. I want to understand it on a simple example. Let's assume that we have 2 functions in first one I just increment 'a' variable and then assign it to 'number' variable, in second I start first function and each every one second I want to print 'number' variable. It should looks like:
global number
def what_number():
a=1
while True:
a+=1
number=a
def read_number():
while True:
--> #here I need to start 'what_number' function <--
time.sleep(1)
print(number)
if __name__ == "__main__":
read_number()
How can I do that? Is there an easy and proper way to do that ?
UPDATE:
I saw noxdafox answer I'm really thankfull but it isn't exactly what I want. First of all I don't want send value in first function ('main' in noxdafox code). Second I don't want to get all values so quene will won't work. I need to get after each second number of while loops. Code should be something like :
import multiprocessing
import time
number = 0
def child_process():
global number
while True:
number += 1
print(number)
def main():
process = multiprocessing.Process(target=child_process)
process.start()
while True:
print("should get same number:",number)
time.sleep(0.001)
if __name__ == "__main__":
main()
If u run above code you get something like:
but this blue selected values should be same ! and that's the main problem :)
P.S sorry for chaos
Ok it takes some time but I figured it out. All it was about Sharing state between processes now all it works like charm. Code :
from multiprocessing import Process, Value
import time
def child_process(number):
number.value = 0
while True:
number.value += 1
#print(number)
def main():
num = Value('i')
process = Process(target=child_process, args=(num,))
process.start()
while True:
print("should get same number:", num.value)
time.sleep(1)
if __name__ == "__main__":
main()
As processes live in separate memory address spaces, you cannot share variables. Moreover, you are using global variables incorrectly. Here you can see an example on how to use global variables.
The most straightforward way to share information between processes is via a Pipe or Queue.
import multiprocessing
def child_process(queue):
while True:
number = queue.get()
number += 1
queue.put(number)
def main():
number = 0
queue = multiprocessing.Queue()
process = multiprocessing.Process(target=child_process, args=[queue])
process.start()
while True:
print("Sending %d" % number)
queue.put(number)
number = queue.get()
print("Received %d" % number)
time.sleep(1)
if __name__ == "__main__":
main()