Can anyone please explain how does inputimeout() in python work? [duplicate] - python

This question already has answers here:
Skip the input function with timeout
(2 answers)
Closed 1 year ago.
I want to take a timed input. If the user doesn't give the input under a limited amount of seconds, the program moves on. So, I learned about inputimeout() but even when I am giving the input within the time limit, it just waits for the timeout. (Also I am not able to solve the problem from other similar questions and that is why I decided to mention this problem)
from inputimeout import inputimeout, TimeoutOccurred
try:
something = inputimeout(prompt = 'Enter: ', timeout=5)
except TimeoutOccurred:
print('Time Over')
Output for the above code:
Enter: e
Time Over
Process finished with exit code 0
Even if I give the input within the time limit, it shows Time Over. Can anyone please help me out?

Keeping it simple, it is a module that reads input from the user, but with a twist, it has a timeout placed by the developer, if the program doesn't detect the information from the user, it skips the input.
A simple way to use it would be:
timer = 2
var = inputtimeout(prompt='Enter: ', timeout=timer)
That would give the user 2 seconds to type, you can also increment with a trycatch block to give a message to the user in case of a timeout.

Related

How would I be able to have certain lines of code be executed randomly? [duplicate]

This question already has answers here:
Percentage chance to make action
(4 answers)
Closed 10 months ago.
I feel this should be an obvious answer, however, I am having issues coding a personal project of mine. How would I be able to have certain lines of code be executed randomly?
Not from the project itself but the principles are still, say for example I would want the following code to be executed every 1/1000 times or so.
print("Lucky!")
How would I exactly be able to do that?
Set a trace function that will have a 1/1000 chance to print:
import random, sys
def trace(frame, event, arg):
if random.random() < 1/1000:
print("Lucky!")
return trace
sys.settrace(trace)
You're welcome to test it with a 1/2 chance.
Generate a random integer in the range [0,1000). Pick any single value in the range, and check for equality to see if you should print.
import random
def lucky():
if random.randrange(1000) == 42:
print("Lucky!")

When I run my python file the normal function doesn't do anything happens, nothing is outputted, how can I display the function [duplicate]

This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I am writing a function which is supposed to get the user's response, yet when I run the file nothing happens, its just an empty screen, how do I fix that? I tried searching up in stackoverflow but I couldnt find what im looking for, thanks in advance :)
def get_user_response():
while True:
try:
print ('Enter the number of clickbait headlines to generate: (0 to exit)')
user = int(input('> '))
print ('HEADLINES')
if user == 0:
for x in range (0,4):
l = "Exiting Program" + "." * x
print (l, end="\r")
sleep(1)
break
else:
print ('a')
except:
print ('Invalid - Enter an integer')
You defined a function but never called it anywhere. That's why the program is not running in the first place. Just write
get_user_response()
anywhere outside of the function.
Also consider wrapping only the user input line into the try except statement, otherwise you will literally catch every possible error that might occur in your function without ever getting an error message.
def get_user_response(trueorfalse):
while trueorfalse:
.....your codes
get_user_response(True)
your function should have arg like thaht

Is it possible to print over already printed text? Or to clear already printed text?

I am trying to make a function that will count down from 10 to 1 and only show one number at a time.
ex: after one second the screen reads: 10;
Next second it reads: 9 (not 10 9)
Here is my code (without attempted solutions):
def countdown():
import time
for i in range(10,0,-1):
time.sleep(1)
print(i,end=" ")
I have already tried using \r,\b, and even sys.stdout.write('\033[D \033[D') and similar items to that using sys.stdout.write.
None of the solutions I have previously found on StackOverflow have worked; giving me outputs such as:
10[D 9[D 8[D etcetera.
I program in python 3.9.0 in IDLE on a mac computer.
(P.S., This countdown function is called after something else that has a print so I do not want to clear the entire screen.)
Thanks in advance to anyone who tries to help!

Python3 prompt user input for a limited time, then enter a default if user doesn't respond

Python3: I'm trying to allow a user a given amount of time to enter a response into an input, but after a given amount of time if they haven't entered anything, I want to abort the input and assign a default value to the variable that is storing the input, or otherwise feed default values into the input statement after the given time period.
I've tried this:
from threading import Timer
timeout = 2
t = Timer(timeout, print, ["\nSorry, time is up"])
t.start()
answer = input("You have 2 seconds to answer:")
t.cancel()
print(answer)
from a different stack overflow post, but the problem is that the interpreter still prompts the user for input even after the final line is executed and answer is printed, and this won't work for what I'm trying to do (essentially, a command line game that needs to keep going when the player isn't giving it input but update when it does receive input).
What is the best way to do this? I know python doesn't really have a timeout function or something like that, but is there any way to achieve this via system commands or a module?
There are several plausible approaches (some of which are probably Unix-specific):
Read the input in a subprocess that can be killed after the timeout. (Many functions, including subprocess.run, accept a timeout parameter to automate this.)
Use alarm or similar to send your own process a signal (and install a signal handler that throws an exception).
Have another thread close the descriptor being read after the timeout; this sounds drastic but is generally said to work, so long as you don’t accidentally open a file on the closed descriptor before restoring it with dup2.
Read the input with lower-level facilities like non-blocking read and select—which will unfortunately disable nice things like readline.
In any case, you have to decide what to do with incomplete but non-empty input entered before the timeout. The terminal driver will likely transfer it invisibly to the next input prompt by default.
Using a select call may be a easier way.
import sys, select
print "You have ten seconds to answer!"
i, o, e = select.select( [sys.stdin], [], [], 10 )
if (i):
print "You said", sys.stdin.readline().strip()
else:
print "You said nothing!"
Refer to Keyboard input with timeout?

Pausing a while loop [duplicate]

This question already has answers here:
How do I make a time delay? [duplicate]
(13 answers)
Closed 8 years ago.
I have a query for a small program that I am running. I was wondering if there was any way to pause a while loop in python for an amount of time? Say for example if I wanted it to print something out, then pause for say (1) second, then print it out again?
There is not really a point to this program I am more doing it for something to do while bored.
I have checked other questions and none seemed to really answer what I was asking.
import time
while ...
print your line
time.sleep(1) # sleep for one second
time sleep method
Yes. There is a function called sleep that does exactly what you want:
while true:
print "Hello!\n"
time.sleep(1)

Categories