Python: Accept user input at any time - python

I am creating a unit that will do a number of things, one of them counting cycles of a machine. While I will be transferring this over to ladder logic (CoDeSys), I am putting my ideas into Python first.
I will have a count running, with just a simple
counter += 1
print("counter")
to keep track of what cycle I'm on. However, I want to be able to reset this count at any time, preferably by typing "RESET" I understand how to use the input command,
check = input()
however, I do not know how to let the program run while it is searching for an input, or whether or not this is possible at all. Thank you in advance for any answer.
If it helps to understand, here is the code. The big gap is where the problem is. http://pastebin.com/TZDsa4U4

If you only want to signal a reset of the counter, you can catch KeyboardInterrupt exception.
while True:
counter = 0
try:
while True:
counter += 1
print("counter")
except KeyboardInterrupt:
pass

Related

Why does using loop-only functions in a def section not work, even when in a loop?

I am making a small text-based game in Python. It involves many inputs and so to avoid bugs, there are a few things I have to check every time an input exists. Naturally, to speed up the process I wanted to put the code into a def in order to simplify the writing process. When I put the code in the def, it red underlines the continue and break commands (meaning they are incorrect), and if you run the code using the def name, a Traceback occurs. I have tried putting the def section at the beginning of the program, after the while True: (The program is supposed to run infinitely until a certain action is taken that breaks the loop) I have also made sure to try putting it under any variables referenced and in the loop so that no part of it is not defined and so that everything would work if I were to just put the code in there.
Here is the code I am trying to put into a def.
def input_bugs():
if letter_one.lower() == "done" and total_count == 0:
print("You have to play at least one game!")
continue
elif letter_one.lower() == "done":
break
elif len(letter_one) > 1:
print("Sorry, you gotta pick a single letter, no more. Otherwise, type 'done' to end the game and see your stats.")
continue
Here is the Traceback I get every time I try to run it.
line 20
continue
^^^^^^^^
SyntaxError: 'continue' not properly in loop
At this point, I don't even care if I have to write it out every time, I can just copy and paste. I am simply curious as to why it doesn't work so that I know in the future. In case you could not tell, I am pretty new to programming so I want to learn from any mistake I make. Also sorry if I referred to some things in the wrong way. Hopefully, you understood what I meant.

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()

How to streamline while loops for infinite cycle with pyautogui

I've lurked on SO for a little while, but all of the existing posts I've seen haven't been able to help me. I'm currently teaching myself python, so I apologize if this is an easy fix I'm not seeing.
My objective with this piece of code is to cycle through tabs in a browser using pyautogui.hotkey. It takes user input for number of tabs to cycle through, and executes the pyautogui command.
My issue, however, is that I can't manage to create a looping for or while loop.
I've played around with should_restart variables, for i in range(x) etc etc, but I'm just not seeing my fix.
The code below is essentially what I want to streamline together.
My idealized flow is:
Take input -> increase tabcounter by 1 until it equals input -> reset tabcounter-> rinse & repeat.
numberofTabs = input('How many tabs do you have? \n')
tabcounter = 0
while int(tabcounter) < int(numberofTabs):
tabcounter = tabcounter+1
pyautogui.hotkey('alt', str(tabcounter))
break
while int(tabcounter) == int(numberofTabs):
tabcounter = 0
I want this code to loop until I interrupt it, or for a lengthy period of time.
Thank you in advance. I appreciate the help!
EDIT: After reworking it, and wrapping my code in a loop, I came up with this:
loopcount = input('How many times do you want this to loop?')
time.sleep(5)
count = 0
for i in range(int(loopcount)):
while count < int(numberofTabs):
count += 1
pyautogui.hotkey('alt', str(count))
time.sleep(1)
else:
count = 0```

Looping a whole program in python using true and false statements

I have written a program but I do not know how to loop it. Help would be appreciated.
Here is the program I need help with.
There are two types of loops: indefinite (while) loops and definite (for) loops. If you want to loop your program a specific amount of times, then use the for loop:
for count in range(0, <number of repetitions minus one>):
# code
If you want to loop the program until the user enters "QUIT" or some other string, use this:
sentinel = input("Enter QUIT to exit or anything else to continue: ")
while sentinel.upper() != "QUIT":
# code
Here are some helpful links to tutorials:
http://www.learnpython.org/en/Loops
http://www.python-course.eu/python3_for_loop.php
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html#while-statements
If you're talking about an infinite loop (i.e it has to go on and on without stopping) then simply use
white True:
<Your code here>
If it's not an infinite loop and only till a certain value comes true then you can do something like:
counter = 0
while counter <= 10:
print "This will continue till counter = 10"
counter += 1
You should make a function of the program, this function you can put in a loop. For further help, please post your code!

Running a function in Python every time any key is pressed?

First off, forgive me, because I'm incredibly new at this Python thing (I'm really an HTML/CSS kind of guy, but I'm trying to branch out). This is probably an elementary sort of question, but we all have to start somewhere, right?
I'm putting together a very basic Python program that will select a random letter from a string of letters and print it out every time someone hits the any key. The whole thing is pretty simple, and currently returns a random letter, but doesn't wait for a keypress to do so, and stops after completing the function runs once.
import random
letterlist = 'abcd'
def random_letter(letters):
print ('Press enter for a random letter...')
print random.choice(letters)
random_letter(letterlist)
Output should look like this:
Press enter for a random letter.
'b'
Press enter for a random letter.
(and so on...)
It's clear that whatever I need to do ought to fall inside of random_letter someplace. I've been googling around and have found lots of references to raw_input and mvscrt, but I'm not entirely sure what I need. It's entirely possible that I'm just asking the question wrong.
I'm assuming assuming that I need some sort of loop going on to keep this running indefinitely.
Thanks in advance!
For starters, you need a loop somewhere to continue prompting the user. You also need some sort of exit condition for the loop. This loop can be inside the function like so:
def random_letter(letters):
while True:
x = raw_input('Press enter for a random letter...')
if x == 'done':
break
print random.choice(letters)
random_letter('abcdef')
Notice that inside the loop we use raw_input to prompt the user to type something, anything, then press enter. When the user types done and hits enter, we break out of the loop using break.
An alternative would be to wrap your existing function in a loop and take care of the prompting outside the function.
def random_letter(letters):
print random.choice(letters)
while True:
x = raw_input('Press enter for a random letter...')
if x == 'done':
break
random_letter('abcdef')
If you don't have to use a loop, and thinking of capturing keyboard events, then there are no cross-platform ways of doing it: Is there a cross-platform python low-level API to capture or generate keyboard events?
For Windows, there is pyHook: http://pyhook.wiki.sourceforge.net/
You can look into the code of pyKeyLogger: http://pykeylogger.wiki.sourceforge.net/
Or a dirty way, capture interrupts: Capture keyboardinterrupt in Python without try-except

Categories

Resources