I'm trying to write a script so that when I press "0" I will get an output, but I want to work without restarting the script, and I haven't been successful using the keyboard module which I've seen as being the most commonly used for detecting key inputs in Python.
What I have so far is
import keyboard
def goto(linenum):
global line
line = linenum
line = 1
if line == 1:
while True:
if keyboard.is_pressed('0'):
print('pressed 0')
break
goto(1)
What I tried doing was after the loop breaks to refer back to the beginning of the loop and try again from there, however the script ends after I press 0. If I remove the break then it constantly outputs "pressed 0", which is not what I want to happen.
You can use pynput to detect key input.
I would do something like this:
from pynput.keyboard import Key, Listener
def on_press(key):
if str(key).replace("'","") == '0':
print('pressed 0')
listener = Listener(on_press=on_press)
listener.start()
Once you start the listener, it will be always waiting for the key press and you can still add code after. In fact, with this example I recommend to add something after, maybe an input() so the script won't close immediately.
I think there are a few problems going on here.
goto is a pretty bad pattern to use and I don't think there's anything here to make your implementation work. It kinda sounds like you're going for some kind of recursion like approach here where when 0 is pressed, then it does some 'reset' and starts looping again. If that is the case you could do something like this:
def wait_for_zero():
# wait for press here
# Should add some sort of exit check too
# 'reset' logic, if any here
wait_for_zero()
looping with a weak condition is pretty fast cycling and generally a bad idea without some time delay. This is mentioned in the documentation for keybaord. There also is an example in the documentation for keyboard to wait for a keypress: https://github.com/boppreh/keyboard#waiting-for-a-key-press-one-time
I created a simple bind script. It works on IDLE Python but it doesn't work in CS:GO. Do you know why?
Mayby it must be on background to work?
import keyboard
import pyautogui
import time
def EventListen():
while True:
try:
if keyboard.is_pressed('n'):
pyautogui.press('`')
pyautogui.typewrite('say EZ')
pyautogui.press('enter')
pyautogui.press('`')
EventListen()
except:
EventListen()
EventListen()
I don't see the need to use pyautogui since you are already using keyboard which is sufficient to perform the tasks you need. I have made some changes to your code
import time
import keyboard
def EventListen():
while True:
try:
if keyboard.is_pressed('n'):
keyboard.press('`')
keyboard.write('say EZ')
keyboard.press('enter')
keyboard.press('`')
elif keyboard.is_pressed('/'): #add something to end the process
break
except:
EventListen()
time.sleep(0.001)
EventListen()
There is no need to call the function in the while loop, as it will anyway be executed infinitely unless you kill the process. I don't see why the script wouldn't run in the background, in fact I am typing this
n`say EZ
`
using the script. What might be possible is that your previous program ran continuously, causing high CPU usage which might have competed with the game's demand. I recomend you to add a small delay before every iteration of the while loop, in this case I have added 1 ms delay, which will cause significant reduction in CPU usage. I am not sure if that solved your problem as I am unable to reproduce your exact case, let me know if it helped.
EDIT : I forgot to mention, I have added another binding of keyboard.is_pressed('/') which will make the program break out of the loop and hence terminate it when / key is pressed. You can change this as you like. If you don't want any other binding as such (which I don't recommend) then you can rely on manually killing the task.
you should make an exe with pyinstaller and you run it background
I am using Windows. I want take user input without pressing enter key and I found many examples, but somehow they are not working on me. I do not press any key and still msvcrt.getch() function is getting input(or atleast it is printing something) all the time. My code below:
import msvcrt
from time import sleep
while True:
print(msvcrt.getch())
sleep(1)
This is printing b'\xff' all the time. And if I press something, it does not care, it still print same string. I am using python 3.6
Problem solved. If using msvcrt: Code has to run in console. I was running that with IDLE.
https://www.reddit.com/r/learnpython/comments/3ji6ew/ordgetch_returns_255_constantly/
Thanks to ingolemo.
I am not looking for input() or raw_input(). I am looking for what sounds like is available in the msvcrt module, specifically msvcrt.kbhit() and msvcrt.getch(), but am unable to get it working.
I tried example 1, here:
http://effbot.org/librarybook/msvcrt.htm
and the chosen answer here:
Python Windows `msvcrt.getch()` only detects every 3rd keypress?
both of which put me into infinite loops from which I am unable to escape by pressing 'esc' and 'q' respectively.
import msvcrt
while True:
pressedKey = msvcrt.getch()
if pressedKey == 'x':
break
I would like to avoid downloading and installing new modules, like pyhook suggested below, if possible:
How do I get realtime keyboard input in Python?
I found the answer here: Python kbhit() problems
Basically, you need to run the program from a console window instead of from the IDE (Python in my case).
I've been using the input function as a way to pause my scripts:
print("something")
wait = input("Press Enter to continue.")
print("something")
Is there a formal way to do this?
It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")
For Windows only, use:
import os
os.system("pause")
So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:
import os
import system
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
print("Think about what you ate for dinner last night...")
pause()
Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.
NOTE: For Python 3, you will need to use input as opposed to raw_input
I assume you want to pause without input.
Use:
time.sleep(seconds)
I have had a similar question and I was using signal:
import signal
def signal_handler(signal_number, frame):
print "Proceed ..."
signal.signal(signal.SIGINT, signal_handler)
signal.pause()
So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.
I use the following for Python 2 and Python 3 to pause code execution until user presses Enter
import six
if six.PY2:
raw_input("Press the <Enter> key to continue...")
else:
input("Press the <Enter> key to continue...")
print ("This is how you pause")
input()
As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:
Python 3.x:
input('Press <ENTER> to continue')
Python 2.x:
raw_input('Press <ENTER> to continue')
For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on
Python 2.x) to prompt the user, rather than a time delay. Fast readers
won't want to wait for a delay, slow readers might want more time on
the delay, someone might be interrupted while reading it and want a
lot more time, etc. Also, if someone uses the program a lot, he/she
may become used to how it works and not need to even read the long
text. It's just friendlier to let the user control how long the block
of text is displayed for reading.
Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard :)
Very simple:
raw_input("Press Enter to continue ...")
print("Doing something...")
By this method, you can resume your program just by pressing any specified key you've specified that:
import keyboard
while True:
key = keyboard.read_key()
if key == 'space': # You can put any key you like instead of 'space'
break
The same method, but in another way:
import keyboard
while True:
if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space'
break
Note: you can install the keyboard module simply by writing this in you shell or cmd:
pip install keyboard
cross-platform way; works everywhere
import os, sys
if sys.platform == 'win32':
os.system('pause')
else:
input('Press any key to continue...')
I work with non-programmers who like a simple solution:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:
Paused. Press ^D (Ctrl+D) to continue.
>>>
The Python Debugger is also a good way to pause.
import pdb
pdb.set_trace() # Python 2
or
breakpoint() # Python 3
I think I like this solution:
import getpass
getpass.getpass("Press Enter to Continue")
It hides whatever the user types in, which helps clarify that input is not used here.
But be mindful on the OS X platform. It displays a key which may be confusing.
Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?
user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke).
By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer.
import readchar
readchar.readkey()
For cross Python 2/3 compatibility, you can use input via the six library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )
I think that the best way to stop the execution is the time.sleep() function.
If you need to suspend the execution only in certain cases you can simply implement an if statement like this:
if somethinghappen:
time.sleep(seconds)
You can leave the else branch empty.