I am reading serial data in while loop, I want to add something in code that if I press t than something should be print otherwise while loop should work. I tried to use readchar, but it wait for me to press some key, I dont want it to wait. I want while loop to work till I press some key
Raspberry pi 2.7
while True:
data = s.recv(xxx)
print(data)
if (x == t)
print(Hello)
else:
continue
it is waiting if i use read char.
There are lots of questions already asked on similar topics which would solve your problem. Some of them include the following:
Loubo's "detect key press in python" here on SO, as well as Spae's "Python key press, detect (in terminal, no enter or pause)".
You could use:
import keyboard as kb
num = 0
while True:
if kb.is_pressed('t'):
num += 1
print (num)
Besides that, you have grammar and indentation errors.
Please consult this post on the SO Meta so further problems like this do not occur.
Related
I'm trying to write a small script with Autokey (not regular Python) on Linux Mint which presses a single key and stops after I press another specific key but I can't get it to stop the loop after I press this specific key.
I got the loop working but I can't make it stop.
import time
a = True
b = keyboard.press_key('s')
keyboard.release_key('s')
while a:
keyboard.send_key("a", repeat=5)
time.sleep(2)
if b:
break
So this outputs the letter "a" indefinitely and after I press "s" it doesn't stop and I don't know what I'm doing wrong
I read about the while function and break but all the examples I found were with a loop stopping after it reached a certain number and these examples with numbers are different than what I try to achieve with this kind of script so I hope someone can help me to figure this out.
You will have to use the keyboard module for this, because press_key is used to "press" the keys not to detect.
If you haven't already installed keyboard you can do it by going to cmd,
pip install keyboard
after that you can add the code in python as follows, pressing "q" will print "a" 5 times and pressing "s" will stop the program.
import keyboard
while True:
if keyboard.is_pressed('q'): # pressing q will print a 5 times
for i in range(5):
print("a")
break
elif keyboard.is_pressed('s'): # pressing s will stop the program
break
You can check if a key is pressed with evdev
Check your InputDevice by looking at python -m evdev.evtest
Then to check if the s key is pressed :
import evdev
from evdev import ecodes as e
device = evdev.InputDevice('/dev/input/event7')
if e.KEY_S in device.active_keys():
do_something()
At first glance your problem is that you never update the value of b and it is only assigned before the loop. You should probably try something like this:
import time
a = True
keyboard.release_key('s')
while a:
keyboard.send_key("a", repeat=5)
b = keyboard.press_key('s')
time.sleep(2)
if b:
break
I don't know how "b = keyboard.press_key('s')" affects the code, if it stops it.
I am trying to control OMXplayer during playback of a video using a Python script. I am new to Dbus on Python, and am hopefully just missing something simple.
Eventually I want to do this with a motion sensor using the GPIO pins, but first I am just trying to get control over the player. What I need to do is loop a section of the video once a certain time passes, and then jump forward to the 'second' section when the passage is interrupted. I am testing this using a key entry.
My problem is that the 'if' statement within the code does not loop unless there is an interruption from a key being inputted, or any other signal. Any key will cause an interruption, but I want the time-specific 'if' statement in the loop to trigger without any input being entered. I hope what I am saying is clear in the below code, but if not please ask any question and I'll be happy to try to clarify.
I am using Will Price's OMXplayer wrapper: https://github.com/willprice/python-omxplayer-wrapper/
My hardware is a Raspberry Pi 3B+
I have looked at similar questions including those below, but have not found the answer:
How to open and close omxplayer (Python/Raspberry Pi) while playing video?
https://www.raspberrypi.org/forums/viewtopic.php?p=533160
I have cleaned out unnecessary parts of the code so this is a basic functioning version.
from omxplayer.player import OMXPlayer #runs from the popcornmix omxplayer wrapper at https://github.com/popcornmix/omxplayerhttps://github.com/popcornmix/omxplayer and https://python-omxplayer-wrapper.readthedocs.io/en/latest/)
from pathlib import Path
import time
import RPi.GPIO as GPIO #for taking signal from GPIO
import subprocess
import logging
logging.basicConfig(level=logging.INFO)
VIDEO_PATH = Path("VIDEO.m4v")
player_log = logging.getLogger("Player 1")
player = OMXPlayer(VIDEO_PATH, dbus_name='org.mpris.MediaPlayer2.omxplayer1')
player.playEvent += lambda _: player_log.info("Play")
player.pauseEvent += lambda _: player_log.info("Pause")
player.stopEvent += lambda _: player_log.info("Stop")
positionEvent = 12
flyin = 3
flyaway = 15
'''
THE ERROR OCCURS IN THE BELOW FUNCTION!!!
the following function does not run each time
the 'while' loop below is playing, but does run
when there is a key pressed as an 'input'
I want to add a chck so that each time a certain
amount of time passes, the video jumps back
'''
def checktime():
currtime = player.position()
print("current time is " + str(currtime))
if(currtime > 3):
print("currtime is greater than 3")
try:
player.play()
print (" Ready")
while True:
'''
Below is the call for the function 'checktime'
This runs once when the video starts, and only
runs again when a key is entered.
I want this to run on a continuous loop
and call each time the video loops
'''
checktime()
key = input()
if key == 'd': #works perfectly
currtime = player.position()
player.seek(flyin-currtime)
print("player position is" + str(player.position()))
if key == 'a': #works perfectly
currtime = player.position()
player.seek(flyaway-currtime)
if key == 's': #works perfectly
player.play()
'''
in addition to the key inputs above, entering any key
and pressing return will run the checktime()
function. I understand that this is receiving an
input, therefore 'waking' the program up,
but I don't understand why the loop is not working
continuously
'''
# Wait for 10 milliseconds
time.sleep(.01)
except KeyboardInterrupt:
print (" Quit")
# Reset GPIO settings
GPIO.cleanup()
The video is controlled using the 's', 'a' and 'd' keys as inputs, and this works perfectly. However, the 'checktime()' function does not call each time the while loop goes around. My guess is that this is because once the video is playing, it is not looking for anything from the Python program until it receives another input.
I am not sure if I am using DBus correctly. Ideally, I wanted to use the seek_absolute function of omxplayer-wrapper, but I haven't been able to understand this. I have been ploughing ahead on this project and have gotten a better understanding since posting an earlier question (see here: OMXplayer-wrapper and Python - jump to a specific point in video) but I am a bit stumped here.
If anyone can help I would appreciate any suggestions!
So the question is how to have an input function or stdin.readline function waiting for an input, while having an updating prompt i.e. The prompt contains the time in format HH:MM:SS and is refreshing every second like:
while 1:
sys.stdout.write('\r' + time.strftime(TIME_FORMAT) + ' :>')
time.sleep(1.0)
But as soon as you add an input there, of course the program waits until you write some input. The version of python I am using is 3.5.
I know I should use curses, but I am planing to write a cross-platform program and the only module I have found is clint, but it didn't have anything in the documentation on the updating prompt.
I have found something that got pretty close but has different problems:
def input_thread(L):
x = input()
L.append(x)
L = []
thread = threading.Thread(target=input_thread, args=(L,))
thread.start()
while 1:
sys.stdout.write('\r' + time.strftime(TIME_FORMAT) + '>:')
time.sleep(1.0)
sys.stdout.flush()
Now the problem remains is that when you type the input but do not press ENTER, the input on the next iteration remains but when you write something, the previous input gets replaced by the current one. Of course the previous inputs are still there in the argument L, so there is no lost input. I hope I didn't describe this to confusing.
If there is no easy way of doing this as it could be done with curses, I'm open to similar cross open tools. Thanks for your time and answers!
So, I figured out what I wanted, a few months ago but didn't answered my own quesiton.
To have a prompt with updating time, you need a separate threads that:
Updates the prompt with additional input
Catches your key strokes
The second thread handles every key-stroke and you can program it how to handle the pressed keys.
When pressing a key, the thread that updates the prompt adds the pressed keys. Also you have to configure some shortcuts for Return, Backspace, etc... to work as expected
I've got it to work and unfortunately... I don't like it. If anyone would like to see the code I will happily provide.
First I want to say that I know that there is a solution with curses.
My programm is a while loop that is run every second. Every second I want to get the last key that was or is pressed. So in case you press a key while the loop sleeps I want that the key is saved so I can get the key that was pressed last even when it isnt pressed anymore. I dont want the saved key to be "deleted" after getting it. So when the user pressed the "a" key I want to get it every second until he pressed another key. If a specific key was pressed i want to print text. This text i want to write in a file using the redirection of stdout:
./test.py > file.txt
My python programm solved with curses looks like this:
import curses
from time import sleep
stdscr=curses.initscr()
stdscr.nodelay(1)
curses.noecho()
curses.cbreak()
while True:
char=stdscr.getch()
if char == 111: #111 = "o" key
print("test")
break
elif char == 97 #97 = "a" key
#code that have to be run every second
#if the a key is the last pressed key!
sleep(1)
curses.nocbreak()
curses.echo()
curses.endwin()
The problem obout this solution is that curses gives me crazy output. I only press one time the "o" key and after the programm stopped file.txt looks like this:
^[[?1049h^[[1;30r^[(B^[[m^[[4l^[[?7h^[[H^[[2Jtest
^[[30;1H^[[?1049l^M^[[?1l^[>
But it should look like this:
test
I would be very greatful if someone writes an answer. I know that python isnt the best choice for programms using keypress events. But i have reasons why i use python for this.
Thank you very much in advance for your answers.
You can install and use the getch package.
import getch
from time import sleep
while True:
char = getch.getch()
if char == 111:
print("test")
break
sleep(1)
(you might need to use getch.getche instead of getch.getch. It's not completely clear from your question)
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