I am writing a program in Python to run on my Raspberry Pi. As many people knows, Raspberry can receive many ways of input. I am using a keyboard and another external input source. This is just for contextualize, not really important for the question itself.
On my program, I wait for a keyboard input and if there is none during a short period of time, I skip and look for the input from the other source. In order to do this I am using the following code:
import sys
import time
from select import select
timeout = 4
prompt = "Type any number from 0 up to 9"
default = 99
def input_with(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
s = int(sys.stdin.read().replace('\n',''))
else:
s = default
print s
return s
I am going to run the Raspberry Pi without a full keyboard, this means I won't have the return key. It will be impossible to validate the keyboard input on this way.
My doubt is if it is possible to get the user input without pressing enter and keeping the timeout for the input.
I've seen many topics talking about both issues (timeout and input without pressing return) but nothing with both together.
Thanks in advance for any help !
I don't think it is straightforward to do it the way you want i.e. to read the waiting contents on the line, even if enter hasn't been pressed (that's right?).
The best suggestion I can offer is that you capture each character as it is pressed, and invoke once the time has passed. You can capture input on a per character basis by setting cbreak mode: tty.setcbreak()
import sys
from select import select
import tty
import termios
try:
# more correct to use monotonic time where available ...
from time33 import clock_gettime
def time(): return clock_gettime(0)
except ImportError:
# ... but plain old 'time' may be good enough if not.
from time import time
timeout = 4
prompt = "Type any number from 0 up to 9"
default = 99
def input_with(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
# store terminal settings
old_settings = termios.tcgetattr(sys.stdin)
buff = ''
try:
tty.setcbreak(sys.stdin) # flush per-character
break_time = time() + timeout
while True:
rlist, _, _ = select([sys.stdin], [], [], break_time - time())
if rlist:
c = sys.stdin.read(1)
# swallow CR (in case running on Windows)
if c == '\r':
continue
# newline EOL or EOF are also end of input
if c in ('\n', None, '\x04'):
break # newline is also end of input
buff += c
sys.stdout.write(c) # echo back
sys.stdout.flush()
else: # must have timed out
break
finally:
# put terminal back the way it was
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
if buff:
return int(buff.replace('\n','').strip())
else:
sys.stdout.write('%d' % default)
return default
Related
I am having a raspberry pi 4 (RPI) with python 2.7 installed. Within a python script, I am executing a shell script, which flashes a µController (µC) connected to the pi. The shell script prints some stuff and reaches idle after printing "Connecting". Note that the script does not finish at this point!
Now I want to use subprocess (or any other function) to forward me all the prints from the shell script. I do then want to check if the keyphrase "Connecting" has been printed. Besides, I need a timeout if the shell script gets stuck before printing "Connecting".
However, I am quite new to python, thus I dont know how to use the subprocess correctly to be able to retrieve the prints from the shell script and set a timeout for the script as well.
Here is some sort of pseudo code:
output = subprocess.Popen(["./prebuilt/bin/bbb_cc13xx-sbl /dev/ttyACM0 {hexfileName} cc13x2 -e -p -v"], \
stdout=subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
expression_found = False
for i in range(5)
if(output.stdout.find('Expression') != -1):
expression_found = True
break
time.sleep(1)
if(expression_found):
do that..
else:
do this...
Is there an easy way to implement my two needs?
EDIT: Adding the prints to the terminal like os.system() does would be great, too.
Best wishes
Slev1n
I actually found a simple solution, the mistake is to pipe stderr instead of stdout. The first one being empty all/most of the time.
Here is a solution where the prints from the child process where displayed on the terminal in real time and where I was able to search for a keyword within the stdout pipe. I was also able to terminate the child process without errors. I could also add a timeout as well for terminating the child process. The codes was also validated on raspberry pi 4B with python 2.7.
Here the main process:
import subprocess, sys
import time
cmd = "contprint.py"
p = subprocess.Popen( cmd , shell=True,
stdout=subprocess.PIPE,
universal_newlines=True)
startTime = time.time()
maxTime = 8
while True:
currentTime = time.time()
if (currentTime - startTime) > maxTime:
p.terminate()
break
else:
output = p.stdout.readline()
print(output)
keyWord = "EOF"
if keyWord in output:
print("Keyword {} has be found".format(keyWord))
p.terminate()
break
if len(output) == 0:
print("Output is empty")
p.terminate()
break
if p.poll() is not None:
print("p.poll is not none")
p.terminate()
break
And here the child process:
import time, sys
count = 0
while(1):
count += 1
print(count)
try:
sys.stdout.flush()
except:
print("Escape Error!")
time.sleep(0.5)
if(count == 10):
print("EOF")
if(count == 20):
pass`enter code here`
Any comments are welcome.
I am trying to write a script that reads from a text file and outputs the content using a type writer effect. I have been able to acheive this using the following code
import sys
from time import sleep
f=open("test.txt", "r")
words = f
for char in words:
sleep(0.5)
sys.stdout.write(char)
sys.stdout.flush()
Which works, however I would like to turn this into a loop so that the text prints, the screen (output) is cleared, a one second pause and then the text prints again (with same keyboard effect).
I have tried this
import sys
from time import sleep
f=open("test.txt", "r")
while True:
words = f
for char in words:
sleep(0.5)
sys.stdout.write(char)
sys.stdout.flush()
break
But this prints the text and then 'hangs' at the end.
All suggestions welcome!
I aim to make my jarvis, which listens all the time and activates when I say hello. I learned that Google cloud Speech to Text API doesn't listen for more than 60 seconds, but then I found this not-so-famous link, where this listens for infinite duration. The author of github script says that, he has played a trick that script refreshes after 60 seconds, so that program doesn't crash.
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_streaming_indefinite.py
Following is the modified version, since I wanted it to answer of my questions, followed by "hello", and not answer me all the time. Now if I ask my Jarvis, a question, which while answering takes more than 60 seconds and it doesn't get the time to refresh, the program crashes down :(
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Cloud Speech API sample application using the streaming API.
NOTE: This module requires the additional dependency `pyaudio`. To install
using pip:
pip install pyaudio
Example usage:
python transcribe_streaming_indefinite.py
"""
# [START speech_transcribe_infinite_streaming]
from __future__ import division
import time
import re
import sys
import os
from google.cloud import speech
from pygame.mixer import *
from googletrans import Translator
# running=True
translator = Translator()
init()
import pyaudio
from six.moves import queue
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "C:\\Users\\mnauf\\Desktop\\rehandevice\\key.json"
from commands2 import commander
cmd=commander()
# Audio recording parameters
STREAMING_LIMIT = 55000
SAMPLE_RATE = 16000
CHUNK_SIZE = int(SAMPLE_RATE / 10) # 100ms
def get_current_time():
return int(round(time.time() * 1000))
def duration_to_secs(duration):
return duration.seconds + (duration.nanos / float(1e9))
class ResumableMicrophoneStream:
"""Opens a recording stream as a generator yielding the audio chunks."""
def __init__(self, rate, chunk_size):
self._rate = rate
self._chunk_size = chunk_size
self._num_channels = 1
self._max_replay_secs = 5
# Create a thread-safe buffer of audio data
self._buff = queue.Queue()
self.closed = True
self.start_time = get_current_time()
# 2 bytes in 16 bit samples
self._bytes_per_sample = 2 * self._num_channels
self._bytes_per_second = self._rate * self._bytes_per_sample
self._bytes_per_chunk = (self._chunk_size * self._bytes_per_sample)
self._chunks_per_second = (
self._bytes_per_second // self._bytes_per_chunk)
def __enter__(self):
self.closed = False
self._audio_interface = pyaudio.PyAudio()
self._audio_stream = self._audio_interface.open(
format=pyaudio.paInt16,
channels=self._num_channels,
rate=self._rate,
input=True,
frames_per_buffer=self._chunk_size,
# Run the audio stream asynchronously to fill the buffer object.
# This is necessary so that the input device's buffer doesn't
# overflow while the calling thread makes network requests, etc.
stream_callback=self._fill_buffer,
)
return self
def __exit__(self, type, value, traceback):
self._audio_stream.stop_stream()
self._audio_stream.close()
self.closed = True
# Signal the generator to terminate so that the client's
# streaming_recognize method will not block the process termination.
self._buff.put(None)
self._audio_interface.terminate()
def _fill_buffer(self, in_data, *args, **kwargs):
"""Continuously collect data from the audio stream, into the buffer."""
self._buff.put(in_data)
return None, pyaudio.paContinue
def generator(self):
while not self.closed:
if get_current_time() - self.start_time > STREAMING_LIMIT:
self.start_time = get_current_time()
break
# Use a blocking get() to ensure there's at least one chunk of
# data, and stop iteration if the chunk is None, indicating the
# end of the audio stream.
chunk = self._buff.get()
if chunk is None:
return
data = [chunk]
# Now consume whatever other data's still buffered.
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
return
data.append(chunk)
except queue.Empty:
break
yield b''.join(data)
def search(responses, stream, code):
responses = (r for r in responses if (
r.results and r.results[0].alternatives))
num_chars_printed = 0
for response in responses:
if not response.results:
continue
# The `results` list is consecutive. For streaming, we only care about
# the first result being considered, since once it's `is_final`, it
# moves on to considering the next utterance.
result = response.results[0]
if not result.alternatives:
continue
# Display the transcription of the top alternative.
top_alternative = result.alternatives[0]
transcript = top_alternative.transcript
# music.load("/home/pi/Desktop/rehandevice/end.mp3")
# music.play()
# Display interim results, but with a carriage return at the end of the
# line, so subsequent lines will overwrite them.
# If the previous result was longer than this one, we need to print
# some extra spaces to overwrite the previous result
overwrite_chars = ' ' * (num_chars_printed - len(transcript))
if not result.is_final:
sys.stdout.write(transcript + overwrite_chars + '\r')
sys.stdout.flush()
num_chars_printed = len(transcript)
else:
#print(transcript + overwrite_chars)
# Exit recognition if any of the transcribed phrases could be
# one of our keywords.
if code=='ur-PK':
transcript=translator.translate(transcript).text
print("Your command: ", transcript + overwrite_chars)
if "hindi assistant" in (transcript+overwrite_chars).lower():
cmd.respond("Alright. Talk to me in urdu",code=code)
main('ur-PK')
elif "english assistant" in (transcript+overwrite_chars).lower():
cmd.respond("Alright. Talk to me in English",code=code)
main('en-US')
cmd.discover(text=transcript + overwrite_chars,code=code)
for i in range(10):
print("Hello world")
break
num_chars_printed = 0
def listen_print_loop(responses, stream, code):
"""Iterates through server responses and prints them.
The responses passed is a generator that will block until a response
is provided by the server.
Each response may contain multiple results, and each result may contain
multiple alternatives; for details, see https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#streamingrecognizeresponse. Here we
print only the transcription for the top alternative of the top result.
In this case, responses are provided for interim results as well. If the
response is an interim one, print a line feed at the end of it, to allow
the next result to overwrite it, until the response is a final one. For the
final one, print a newline to preserve the finalized transcription.
"""
responses = (r for r in responses if (
r.results and r.results[0].alternatives))
music.load(r"C:\\Users\\mnauf\\Desktop\\rehandevice\\coins.mp3")
num_chars_printed = 0
for response in responses:
if not response.results:
continue
# The `results` list is consecutive. For streaming, we only care about
# the first result being considered, since once it's `is_final`, it
# moves on to considering the next utterance.
result = response.results[0]
if not result.alternatives:
continue
# Display the transcription of the top alternative.
top_alternative = result.alternatives[0]
transcript = top_alternative.transcript
# Display interim results, but with a carriage return at the end of the
# line, so subsequent lines will overwrite them.
#
# If the previous result was longer than this one, we need to print
# some extra spaces to overwrite the previous result
overwrite_chars = ' ' * (num_chars_printed - len(transcript))
if not result.is_final:
sys.stdout.write(transcript + overwrite_chars + '\r')
sys.stdout.flush()
num_chars_printed = len(transcript)
else:
print("Listen print loop", transcript + overwrite_chars)
# Exit recognition if any of the transcribed phrases could be
# one of our keywords.
if re.search(r'\b(hello)\b', transcript.lower(), re.I):
#print("Give me order")
music.play()
search(responses, stream,code)
break
elif re.search(r'\b(ہیلو)\b', transcript, re.I):
music.play()
search(responses, stream,code)
break
num_chars_printed = 0
def main(code):
cmd.respond("I am Rayhaan dot A Eye. How can I help you?",code=code)
client = speech.SpeechClient()
config = speech.types.RecognitionConfig(
encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=SAMPLE_RATE,
language_code='en-US',
max_alternatives=1,
enable_word_time_offsets=True)
streaming_config = speech.types.StreamingRecognitionConfig(
config=config,
interim_results=True)
mic_manager = ResumableMicrophoneStream(SAMPLE_RATE, CHUNK_SIZE)
print('Say "Quit" or "Exit" to terminate the program.')
with mic_manager as stream:
while not stream.closed:
audio_generator = stream.generator()
requests = (speech.types.StreamingRecognizeRequest(
audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config,
requests)
# Now, put the transcription responses to use.
try:
listen_print_loop(responses, stream, code)
except:
listen
if __name__ == '__main__':
main('en-US')
# [END speech_transcribe_infinite_streaming]
You can call your functions after recognition in different thread. Example:
new_thread = Thread(target=music.play)
new_thread.daemon = True # Not always needed, read more about daemon property
new_thread.start()
Or if you want just to prevent exception - you can always use try/except. Example:
with mic_manager as stream:
while not stream.closed:
try:
audio_generator = stream.generator()
requests = (speech.types.StreamingRecognizeRequest(
audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config,
requests)
# Now, put the transcription responses to use.
listen_print_loop(responses, stream, code)
except BaseException as e:
print("Exception occurred - {}".format(str(e)))
I have a list of commands saved in text file ('command.log') which I want to run against a unit connected to 'COM5' and save the response for each command in a text file ('output.log'). The script gets stuck on the first command and I could get it to run the remaining commands. Any help will be appreciated.
import serial
def cu():
ser = serial.Serial(
port='COM5',
timeout=None,
baudrate=115200,
parity='N',
stopbits=1,
bytesize=8
)
ser.flushInput()
ser.flushOutput()
## ser.write('/sl/app_config/status \r \n') #sample command
fw = open('output.log','w')
with open('data\command.log') as f:
for line in f:
ser.write(line + '\r\n')
out = ''
while out != '/>':
out += ser.readline()
fw.write(out)
print(out)
fw.close()
ser.close()
print "Finished ... "
cu()
The bytes problem
First of all, you're misusing the serial.readline function: it returns a bytes object, and you act like it was a str object, by doing out += ser.readline(): a TypeError will be raised. Instead, you must write out += str(ser.readline(), 'utf-8'), which first converts the bytes into a str.
How to check when the transmission is ended ?
Now, the problem lays in the out != '/>' condition: I think you want to test if the message sent by the device is finished, and this message ends with '/<'. But, in the while loop, you do out += [...], so in the end of the message, out is like '<here the message>/>', which is totally different from '/>'. However, you're lucky: there is the str.endswith function! So, you must replace while out != '\>' by while not out.endswith('\>'.
WWhatWhat'sWhat's theWhat's the f*** ?
Also, in your loop, you write the whole message, if it's not already ended, in each turn. This will give you, in output.log, something like <<me<mess<messag<messag<message>/>. Instead, I think you want to print only the received characters. This can be achieved using a temporary variable.
Another issue
And, you're using the serial.readline function: accordingly to the docstrings,
The line terminator is always b'\n'
It's not compatible with you're code: you want your out to finish with "\>", instead, you must use only serial.read, which returns all the received characters.
Haaaa... the end ! \o/
Finally, your while loop will look as follows:
# Check if the message is already finished
while not out.endswith('/>'):
# Save the last received characters
# A `bytes` object is encoded in 'utf-8'
received_chars = str(ser.read(), 'utf-8')
# Add them to `out`
out += received_chars
# Log them
fw.write(received_chars)
# Print them, without ending with a new line, more "user-friendly"
print(received_chars, end='')
# Finally, print a new line for clarity
print()
How can I print out the output of an external command by characters or at least by lines?
This code prints it in one block after the command returns.
import subprocess as sub
output, errors = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True).communicate()
print output + errors
You can access to the standart output stream as
p = sub.Popen("cmd", stdout=sub.PIPE, stderr=sub.PIPE)
print(p.stdout.readline()) # This read a line
You can perform any operation o the file streams.
When you use readline in a standart output of a proccess the main thread of the app wait for that proccess to write some thing on the ouput. When that process write to the output you program continue.
You must know that before read a line from the proceess you need to call flush() on the stream. Because the streams have a cache time before the real values are written to it.
You can see this post, this is a good explanation of how this work on python
http://www.cyberciti.biz/faq/python-execute-unix-linux-command-examples/
import subprocess
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
It prints out the output of the cmd character by character.