Input with time limit/countdown [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm pretty new to Python and would like to write a (not computer) language trainer for my students. Just something like where a timer runs in the background and the student has to input words quickly to slow down/revert the countdown - otherwise the countdown reaches zero and displays some "game over" message. (Just like when a special agent has to defuse a bomb while the timer races towards zero.)
There are tons of explanations of threading which sounds like the right way to do it, sure, but so far I haven't found anything where a timer is combined with a (time-limited) raw_input. Could any of you pros give me a pointer to the tutorial/discussion I have overlooked?

import threading
import time
import os
def ask():
"""
Simple function where you ask him his name, if he answers
you print message and exit
"""
name = raw_input("Tell me your name, you have 5 seconds: ")
exit_message = "Wohoho you did it..Your name is %s" % name
exit(exit_message)
def exit(msg):
"""
Exit function, prints something and then exits using OS
Please note you cannot use sys.exit when threading..
You need to use os._exit instead
"""
print(msg)
os._exit(1)
def close_if_time_pass(seconds):
"""
Threading function, after N seconds print something and exit program
"""
time.sleep(seconds)
exit("Time passed, I still don't know your name..")
def main():
# define close_if_time_pass as a threading function, 5 as an argument
t = threading.Thread(target=close_if_time_pass,args=(5,))
# start threading
t.start()
# ask him his name
ask()
if __name__ == "__main__":
main()

You don't have to do it via threading, you could in a single thread run through your 'logic' at a specific frequency and each iteration recalculate the countdown via a time-delta method. This is how many video games are produced.
Lets say you run this pseudo-code method at 60hz:
delta = timenow-timelast;
countdown -= delta;
if(input)
processInputHere;
You should be able to convert the pseudo-code to python code to make it work

Related

Replace while true loops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I was the other day trying to create on python a little program who would detect if the key x is pressed, if yes the program continue and do it's task. i found the way to do it with the package keyboard :
while True :
if keyboard.is_pressed("x"):
...
But it appears that the while true loop after a long time, start bugging, and that brought to ask you, if it is possible to do a loop or something to detect a key press without causing lags like the window system events when you click on a shortcut then a program appears.
Thank you.
The keyboard documentation specifically says NOT to use the method you are using:
import keyboard
# Don't do this!
#
#while True:
# if keyboard.is_pressed('x'):
# print('x was pressed!')
#
# This will use 100% of your CPU and print the message many times.
# Do this instead
while True:
keyboard.wait('x')
print('x was pressed! Waiting on it again...')
# or this
keyboard.add_hotkey('x', lambda: print('x was pressed!'))
keyboard.wait()
I would recommend reading the documentation for your specific needs.
Note:
If you are looking to bind the specific key to a function, you could do something like this:
import keyboard
def on_x_key_press():
print("'x' key pressed")
keyboard.on_press_key("x", on_x_key_press)
Now your computer runs through that loop as fast as it can. I think you could add a limit on how many times the keyboard press is checked.
import time
while True:
if keyboard.is_pressed("x"):
...
time.sleep(0.001) # the program just sleeps for 0.001 seconds
If the program still lags, try to increment the value of seconds to wait (for example: from 0.001 to 0.005).

Is there any way to execute 2 infinite loops at the same time in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
im use speechrecognition, and tkinter, i have speech recognition in a inifinte loop, because i want them to recognize my voice all the time together with a GUI of tkinter, i need I need them to run in the same program since I want the gui to change along with the voice recognition but if anyone can give me another solution is welcome
you can use multithreading, you can visit this link to find out how to do that.
https://www.geeksforgeeks.org/multithreading-python-set-1/
Maybe Timers could work?
from threading import Timer
from time import sleep
x0 = 0
x1 = 0
def process1():
global x0
print(x0)
x0 = x0 + 1
Timer(0, process1, []).start()
def process2():
global x1
print(x1)
x1 = x1 - 1
Timer(0, process2, []).start()
Timer(0, process1, []).start()
Timer(0, process2, []).start()
In a similar fashion to javascript's setTimeout.
Eg instead of an infinite loop, you break your loop down into steps, and have it do a timer to do the next step, allowing the other "process" do its thing. This would behave like multithreading on a single thread.

Function doesn't work in another function with sleep [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a function that scrapes websites and returns a statement that is depending if it found certain keywords. This function is called checksite. When I run the function on its own it works great but I can't get it to work inside another function together with time.sleep.
This works great
checksite()
This does not work
while True:
checksite()
time.sleep(10)
I want the checksite-function run every 10 second. All help is appreciated!
Your code should work. To check what is wrong, you could use this:
def checksite():
#blahblah
while True:
print('starting')
checksite()
print('site checked')
time.sleep(10)
print('sleep function complete')
Then maybe you will get an idea of what is wrong.
It is important to know what the checktime() execution does.
If you dont see anything happening after 10 seconds and the script still executing more than expected, my first suggestion would be to know how much time the execution takes.
You can run this and get the amount of time:
import time
import datetime
def checktime():
#Doing some execution
print('execution...')
#Use:
while True:
started = datetime.datetime.now()
checktime()
time.sleep(10)
executed = datetime.datetime.now()
print('The script runtime is: {0}'.format(executed - started))

Get input whilst looping code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I currently have a Twitter bot that streams tweets from Twitter in my timeline. Regardless of what it does, how could I also send Tweets (get keyboard input) at the same time as receiving Tweets (looping code).
This isn't a question about the Twitter API, just a general question on how to get input while looping code.
I'd create a specific thread for it, when used would call your Twitter API post function. (But it depends how your code is structured)
import threading
t1 = threading.Thread(target=post_from_keyboard)
t1.start()
t1.join()
# Loop exits when users writes quit.
# Obviously it won't post any Tweets with the word "quit"
def post_from_keyboard():
while(True):
kb_tweet = input("Enter Tweet or write "quit" to exit")
if kb_tweet != "quit"
your_tweet_api_call( kb_tweet )
else:
break
I understand that you don't want your loop to wait for you to enter a tweet in each iteration, so you can't use the most common method raw_input.
In this case, it is platform specific. For Unix systems, you should use the select module, while in Windows, you have the msvcrt one.
With select, the idea is to check stdin inside every iteration, and process the message when you get one.
Something like:
import sys
import select
while True:
message = select.select([sys.stdin], [], [], timeout=0.1)[0]
if message:
print(message)
Perhaps,you are looking for something like this
userInput = raw_input()
while(userInput != q):
#do something
userInput = raw_input()

How Can I Print Running Text? For Example to Print "Stack" Python Will Print S then t then a then c and then k? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using notepad++ for writing codes and then seeing output using Windows Power Shell. Now lets say I want to print this...
"Stack Overflow"
But not all at once. First of all it will print S then t then a then c then k then a space and then O ...... ?
So is there any function/method to post the text as we type in old PCs?
If the question is not complete let me know what more information I can provide you.
Update
#uʍop ǝpısdn Yes, you understood my requirement. And many thanks for the answer. :)
Well I didn't know that it calls Emulating text. :)
Here you go:
import time, sys
for letter in "Stack Overflow":
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(1) # that's in seconds, adjust at will
sys.stdout.write('\n')
Why stdout.flush?
Output from a running program is usually buffered (i.e. held waiting) until certain conditions are met. The call to sleep() will not fulfill these conditions, and the text will not appear. By calling flush() after each letter, you force it out.
from __future__ import print_function # only needed for Python 2.x
import random
from time import sleep
def delay_print(s, min_delay=0.1, max_delay=0.8):
for ch in s:
delay = min_delay + random.random() * (max_delay - min_delay)
sleep(delay)
print(ch, end="")
print('')
delay_print("StackOverflow")

Categories

Resources