I tried to make a twitter bot to print random number but it print the same number while testing the command
import tweepy
import random
import time
import threading
import schedule
start = time.perf_counter()
while time.perf_counter() - start < 2:
random_number = random.randint(0,10000)
time.sleep(1.0)
def job():
print(random_number)
# run the function job() every 2 seconds
schedule.every(2).seconds.do(job)
while True:
schedule.run_pending()
What should I do in order to have random numbers?
Your first block defines the random_number, which is then fixed.
You should compute the random number in your job
import random
import time
import threading
import schedule
def job():
print(random.randint(0,10000))
# run the function job() every 2 seconds
schedule.every(2).seconds.do(job)
while True:
schedule.run_pending()
Related
import time
import random
def timer():
correct = 1
x = 0
while correct != 2:
time.sleep(0.1)
x = x + 0.1
def round1():
numb = random.randint(1, 100)
print(numb)
timer()
ans = input(">")
if ans == numb:
correct = 2
x = round(x)
print("you did that in", x ,"seconds!")
round1()
I was trying to get both functions to run together (have the game playing and the timer going in the background) but as soon as the timer started it would let me continue the game.
In the given program, I have created two different functions that will work at the same time. I have used threading to create thread of functions and sleep to limit the printing speed. In similar manner you can use game and timer function together.
from threading import Thread
from time import sleep
#sleep is used in functions to delay the print
#the below functions has infinite loop that will run together
#defining functions
def func1():
for x in range(20):
sleep(1)
print("This is function 1.")
def func2():
for x in range(10):
sleep(2)
print("This is function 2.")
#creating thread
thread1=Thread(target=func1)
thread2=Thread(target=func2)
#running thread
thread1.start()
thread2.start()
I am trying to run two functions in parallel:
Timer
Input field
Program should terminate either when Timer ends or when user provides an answer.
Everything is working fine, but when the time is up I still can input an answer, and I want process to terminate.
Can somebody help me with that issue ?
Thanks !
Here is my code:
import sys
import time
import threading
def countdown2(seconds):
global stop_timer
stop_timer = False
start = time.time()
while not stop_timer:
if time.time() - start >= seconds:
stop_timer = True
print(f'End of time {time.time() - start}')
print(f'End of time in {time.time() - start}')
countdown_thread = threading.Thread(target=countdown2, args=(5,))
countdown_thread.start()
while not stop_timer:
answer = input('Provide answer: ')
if answer:
stop_timer = True
break
print('End')
Here's an example of how you could do this:
from threading import Thread
import time
import signal
import os
got_input = False
def countdown(duration):
global got_input
for _ in range(duration):
time.sleep(1)
if got_input:
return
if not got_input:
os.kill(os.getpid(), signal.SIGINT)
def main():
global got_input
(t := Thread(target=countdown, args=[5])).start()
try:
answer = input('Please enter a value: ')
got_input = True
print(f'You entered: {answer}')
except KeyboardInterrupt:
print('\nToo slow')
finally:
t.join()
if __name__ == '__main__':
main()
i'd like to know how to sync datetime with system time in real time. what i mean is the code always prints the same hour same minute and same seconds if i loop the code. this is my code
from datetime import datetime
import os
from time import sleep
def clear():
os.system('cls')
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
while True:
time = print("Current Time =", current_time)
sleep(1)
clear()
i need help for this thx!
You are currently creating the date-time object only once with the line. This means the time is only looked up once and then that value is stored in the variable.
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
All you need to do is move those two lines into your loop. That way, the time is looked up on each loop iteration and you get new values. The modified code:
from datetime import datetime
import os
from time import sleep
def clear():
os.system('cls')
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
time = print("Current Time =", current_time)
sleep(1)
clear()
Thanks for the answer! i also modify the code a little bit to make it a little bit better
from datetime import datetime
from time import sleep
while True:
now=datetime.now()
current_time=now.strftime("%H:%M:%S")
time=print("Current Time : ", current_time, end=\r)
sleep(1)
I'am learning python by doing little projects on my own. I'am struggling to schedule scripts with random delay in a range.
In the code below, the delay is random but always the same ... I Really need help.
import schedule
import time
import random
import datetime
def job():
t = datetime.datetime.now().replace(microsecond=0)
print(str(t) + " hello")
i = 0
while i < 10:
delay = random.randrange(1, 5)
schedule.every(delay).seconds.do(job)
i += 1
while True:
schedule.run_pending()
time.sleep(1)
Think through your loops. Your first while loop creates a second infinite while loop. So you never continue to the function that would create a new delay.
import schedule
import time
import random
import datetime
def job():
t = datetime.datetime.now().replace(microsecond=0)
print(str(t) + " hello")
i = 0
for i in range(10):
delay = random.randrange(1, 5)
print(delay)
schedule.every(delay).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(.01)
I would like to create a different task for every specific time and it will wait for the time and continue it day over day.
Below are my code but it only for one task.
import time, datetime
time_now = time.localtime(time.time())
now = []
now = time.strftime("%H:%M:%S", time_now)
value = []
value = time.strftime("15:00:00")
print(now)
print(value)
while value == now:
time.sleep(1)
print("\nSuccess")
I have implemented in my project and it's working properly. Please have a look on below code.
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.http import condition
import time
#condition(etag_func=None)
def stream(request):
resp = StreamingHttpResponse(stream_response_generator(request))
return resp
def stream_response_generator(request):
start = time.time()
end = start + 60
while start < end:
#Here you can add your method
print ("This is test") # will print after 60 secound after frist executing of time
time.sleep(2) # sleep time added