There are at least two ways to approach this.
The first is to check whether your "standard input" stream has some data, without blocking to actually wait till there is some. The answers referenced in comments tell you how to approach this. However, while this is attractive in terms of simplicity (compared to the alternatives), there is no way to transparently do this portably between Windows and Linux.
The second way is to use a thread to block and wait for the user input:
import threading
import time
no_input = True
def add_up_time():
print "adding up time..."
timeTaken=float(0)
while no_input:
time.sleep(0.01)
timeTaken=timeTaken+0.01
print(timeTaken)
# designed to be called as a thread
def signal_user_input():
global no_input
i = raw_input("hit enter to stop things") # I have python 2.7, not 3.x
no_input = False
# thread exits here
# we're just going to wait for user input while adding up time once...
threading.Thread(target = signal_user_input).start()
add_up_time()
print("done.... we could set no_input back to True and loop back to the previous comment...")
As you can see, there's a bit of a dilemma about how to communicate from the thread to the main loop that the input has been received. Global variable to signal it... yucko eh?
Answer from GreenAsJade on Stack Overflowi have an assignment due tomorrow please help
base_gene = input("""what is the base gene list:
""")
name4Genelist1 = input("\nplease enter a name for the gene list: \n\n")
base_gene_list = list(base_gene.split(","))
compare_gene = input("""what is the gene list you want to compare? :
""")
name4Genelist2 = input("please enter a name for the gene list: ")
compare_gene_list = list(compare_gene.split(","))
# print(base_gene_list)
# print(compare_gene_list)
print(compare_gene_list)
print(base_gene_list)
result = []
for element in compare_gene_list:
if element not in base_gene_list:
result.append(element)
result2 = []
for element in base_gene_list:
if element not in compare_gene_list:
result2.append(element)
OutPut = ','.join(result)
OutPut2 = ','.join(result2)
print("here is the stuff the was in "+ name4Genelist1 +" gene list and wasnt in " + name4Genelist2 + """:
"""+OutPut)
print("")
print("and here is the stuff the was in "+ name4Genelist2 +" gene list and wasn't in " + name4Genelist1 + """:
"""+OutPut2)There are at least two ways to approach this.
The first is to check whether your "standard input" stream has some data, without blocking to actually wait till there is some. The answers referenced in comments tell you how to approach this. However, while this is attractive in terms of simplicity (compared to the alternatives), there is no way to transparently do this portably between Windows and Linux.
The second way is to use a thread to block and wait for the user input:
import threading
import time
no_input = True
def add_up_time():
print "adding up time..."
timeTaken=float(0)
while no_input:
time.sleep(0.01)
timeTaken=timeTaken+0.01
print(timeTaken)
# designed to be called as a thread
def signal_user_input():
global no_input
i = raw_input("hit enter to stop things") # I have python 2.7, not 3.x
no_input = False
# thread exits here
# we're just going to wait for user input while adding up time once...
threading.Thread(target = signal_user_input).start()
add_up_time()
print("done.... we could set no_input back to True and loop back to the previous comment...")
As you can see, there's a bit of a dilemma about how to communicate from the thread to the main loop that the input has been received. Global variable to signal it... yucko eh?
You should use a thread, if you are supposed to listen to input and have at the same time something else being processed.
In Python 3, use input():
input("Press Enter to continue...")
In Python 2, use raw_input():
raw_input("Press Enter to continue...")
This only waits for the user to press enter though.
On Windows/DOS, one might want to use msvcrt. The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT):
import msvcrt as m
def wait():
m.getch()
This should wait for a key press.
Notes:
In Python 3, raw_input() does not exist.
In Python 2, input(prompt) is equivalent to eval(raw_input(prompt)).
In Python 3, use input():
input("Press Enter to continue...")
In Python 2, use raw_input():
raw_input("Press Enter to continue...")
when you use the "input" function it prompts the user and waits for them to press enter;
Is there an easy way to listen for the user's keypresses in the background and then call a function when they press enter but I don't want to record them while they are not on the python terminal?
before I use the python pynput keyboard listener but that records keypresses even when you are not on the python window terminal.
Actually in the meantime (almost 10 years from the start of this thread) a cross-platform module named pynput appeared. Below a first cut - i.e. that works with lowercase 's' only. I have tested it on Windows but I am almost 100% positive that it should work on Linux.
from pynput import keyboard
print('Press s or n to continue:')
with keyboard.Events() as events:
# Block for as much as possible
event = events.get(1e6)
if event.key == keyboard.KeyCode.from_char('s'):
print("YES")
Under Windows, you need the msvcrt module, specifically, it seems from the way you describe your problem, the function msvcrt.getch:
Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.
(etc -- see the docs I just pointed to). For Unix, see e.g. this recipe for a simple way to build a similar getch function (see also several alternatives &c in the comment thread of that recipe).
I need to detect if any key is pressed but i cannot wait until the user press anything
Like he only gonna press any key if he wants to stop the program,so the program need to continue while he dont press nothing
Ps:sorry my bad english
from datetime import datetime
import os
from msvcrt import getch
from time import sleep
def get_down(time):
print('press ENTER to cancel \n')
while True:
key = ord(getch()) #the program stop wanting the user to press a key
if key == 13:
print('You cancel the operation')
break
if time == hours:
print("The system is gonna turn off")
sleep(5)
os.system("shutdown /s /t 1")
hours = datetime.now().strftime('%H:%M')
print('Now is: {}'.format(hours))
get_down(str(input('When you want to shutdown? (hh:mm):')))I'm posting this answer for a subtle variation of this issue that I encountered, where the Python console would not let me enter my input but unlike in your case, would not move on with the loop.
I solved the problem by clicking on "Edit the configurations" on the toolbar (run/debug configurations) and disabling the option "Emulate terminal in output console".
Hopefully those having the same issue will stumble upon this thread (as I did).
EDIT: In images:



I haven't tried that solution with a remote interpreter.
Your code seems fine. I suspect that what you're seeing is caused by a Run/Debug configuration issue, which can be the source of all sorts of unexpected behaviors.
Here is what I recommend you do to identify what is wrong:
Run the code with CTRL-Shift-F10 to make sure you're running the current file, and not some other file in your project. If this fixes the issue, you can simply select which file you want Shift-F10 to run by selecting it in the drop down menu at the top right of the screen, near the "play" button
Copy your code to a brand new project, and run it from there. If this fixes the issue, it means your code is fine and that the issue is most likely a Run/Debug configuration issue.
If you confirmed that your code is fine with the step above but can't start from scratch, you can edit the Run/Debug configuration by selecting "Edit" in the drop down menu at the top right of the screen, near the "play" button.
Howdy,
Do you know if there is a way to accept user's input without pressing enter?
I am trying to exit a while loop by pressing the key "q" but with the input() function I have to press enter.
I would like to use standard Python modules (if possible) and not install anything else with pip.
Thank you!
Edit: I'm using Python3.8 on Unix