forcing to end a function that accepts input using a timer - python

I've tried using the the solution posted here:
How would I stop a while loop after n amount of time?
but that loop doesn't end with the function im running that accepts inputs. How do I force function5 to exit?
while True:
test = 0
if test == 5 or time.time() > timeout:
print "time's out!"
break
test = test - 1
function5()
def function5():
receiver = raw_input("enter something: ")

You've already identified your problem. This won't work because when you call raw_input() the program will wait forever until the user types something, and what you want is for the timeout to somehow interrupt raw_input().
Here is a *nix-only solution:
Keyboard input with timeout in Python

Related

Is there a way to cancel an input() in Python 3.8 after a certain period of time? [duplicate]

This question already has answers here:
Keyboard input with timeout?
(28 answers)
Closed 2 years ago.
I'm writing a program in Python 3.8. I'd like to make an input, let's say variable v. If v is input as "n," then some code is run. Any other input does nothing. Additionally, if the time runs out and nothing is inputted for v, then the "n" code is run.
I've tried a couple of different timers which work alright, but I'm struggling on how to cancel the input, since it stops my whole program and won't proceed onto the code I want to run.
Here's what I have:
def timerMethod():
timeout = 10
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose: are you feeling ok? y/n: \n" % timeout
answer = input(prompt)
if (answer == "n"):
feelingBad = True
t.cancel()
The two problems that I've encountered are 1. feelingBad (global variable) will never be made true. I feel like this is a basic Py principle that I've forgotten here, and I can change the way the code is written here, but if you'd like to point out my error please do. The main problem 2. is that if there is no input for the answer variable, the timer will end but the program will not proceed. If someone could please help me on the right track as on how to cancel the input prompt when the timer runs out, I'd greatly appreciate it.
Check the multithreading
here. I wish there was a better explanation on how it works. In my own words, one thread starts and sets the start time which is taken up by the second. Instead of a timer that counts down, it runs an if statement which compares the time taken with the time limit, which gives a space for any code to be run before the program exits.
You can try this:
import time
from threading import Thread
user = None
def timeout():
cpt = 0
while user == None:
time.sleep(1); cpt += 1
if user != None:
return
if cpt == 10:
break
print("Pass")
Thread(target = timeout).start()
user = input()

Python - Checking if there is an input from user without stopping the loop

I have a small script where I have a continuous loop. The loop runs and I expect that the user will give an input whenever he wants. I want to check if the user wrote something in the console, if yes, I will do something extra, if not, the loop continues.
The problem is that when I call the input() function, the program waits for user input.
The code that I will use here will be just a simple version of my code to show better what is my problem.
i=0
while True:
i+=1
if 'user wrote a number':
i+= 'user's input'
The objective is to not stop the loop if the user do not input anything. I believe this is a simple thing but I didn't find an answer for this problem.
Thank you for your time!
You can execute the background task (the while True) on a separate thread, and let the main thread handle the input.
import time
import threading
import sys
def background():
while True:
time.sleep(3)
print('background task')
def handling_input(inp):
print('Got {}'.format(inp))
t = threading.Thread(target=background)
t.daemon = True
t.start()
while True:
inp = input()
handling_input(inp)
if inp == 'q':
print('quitting')
sys.exit()
Sample execution (lines starting with >> are my inputs):
background task
>> a
Got a
>> b
Got b
background task
>> cc
Got cc
background task
background task
>> q
Got q
quitting
Process finished with exit code 0
The only caveat is if the user takes longer than 3 seconds to type (or whatever the value of time.sleep in background is) the input value will be truncated.
I'm don't think you can do that in one single process input(), because Python is a synchronous programming languaje,the execution will be stoped until input() receives a value.
As a final solution I'd recommend you to try implement your functions with parallel processing so that both 'functions' (input and loop) can get executed at the same time, then when the input function gets it's results, it sends the result to the other process (the loop) and finish the execution.

How to terminate exec() function in python if it takes too long?

I am trying to make a function that takes in user's code and runs it:
code = input("Your code: ")
def execute(c):
exec(c)
execute(code)
However, if the user enters in an infinite loop, the function runs forever.
Is there a way to terminate the exec() function if the function takes too long? For example, if the code takes longer than 15 seconds to execute, the programme terminates.
Thanks in advance.
There are multiple solutions,
For example you could pass a global variable stop condition and raise exception from inside the exec once condition has met.
Other solution would be to run exec in a separate thread/process and sending some stop signal once desired.
You can use wrapt_timeout_decorator
from wrapt_timeout_decorator import *
#timeout(15)
def execute(c):
exec(c)
code = input("Your code: ")
execute(code)
This will throw an exception if the function takes more than 15 sec to finish - TimeoutError: Function execute timed out after 15.0 seconds

Python does't run some lines of code as it should

can someone help me with this code? It's use is to make timed input for 2 seconds and it needs to print the last line even if the user did or didn't type something in the console (for that time). When I don't type in anything, after printing "Too Slow" it asks me for the same input, so I added IF, but it doesn't really notice it. I hope that someone can help me. Thanks!
import time
from threading import Thread
i = 0
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow") #prints this if nothing is typed in (for 2 seconds)
if i == 0:
i = 1
Thread(target = check).start()
answer = input("Input something: ") #program doesn't even notice IF and asks me the second time for input
print("This should be printed instantly after printing Too Slow (when user doesn't input anything)")
The return in the check function only causes the thread to be completed, but the call to input is independent of that thread and thus not interrupted when the check function completes. See this answer for an alternative solution using the signal module.

How to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

Categories

Resources