I have posted the complete code below and I would like to be able to achieve repeated execution of audio = r.listen(source). I have gotten the code to repeat but it returns the same thing everytime. I don't really like giving up and coming here asking for answers (first time posting). What do I have to do to get the code to return new phrase every time It executes the do_again(quit) function. Basically, the program asks to say something and it works fine the first time. When I am prompted to continue or quit and I enter 'c' I want to repeat the whole thing all over. Any help would be greatly appreciated. PS I am new to python and am probably doing this completely wrong. Any tips also will be appreciated!
Here is the code (All criticism is welcome. like: is there a better cleaner way to do this?)
import speech_recognition as sr
import sys
r = sr.Recognizer()
m = sr.Microphone()
with m as source:
print('Speak clearly for better results ...')
audio = r.listen(source)
quit = 'c'
q = quit
def do_again(quit):
quit = input('Press c to continue OR press q to quit: ')
q = quit
if q == 'q':
print('Exiting program')
sys.exit()
elif q == 'c':
print('Running again...')
else:
print('ERROR! Press c to continue OR press q to quit ')
return q
response = {"success": True,
"error": None,
"transcription": None
}
while q == 'c':
try:
# I want this to return new phrase instead of returning the same phrase.
response['transcription'] = r.recognize_sphinx(audio) # I want a new 'response' here
print(f"[SPEECH RECOGNIZED] {response['transcription']}")
except sr.UnknownValueError:
print(f"[FATAL ERROR] Exiting...")
except sr.RequestError as e:
response['success'] = False
response['error'] = 'API Unavailable/unresponsive'
print(f"[FATAL ERROR] {response['error']} {e}")
do_again(quit)
I think I found my answer. I was reading the documentation in the python interpreter with the help(r.Recognizer) feature. I found a listen_in_background method. Will listen_in_background do what I need? I know it's a silly program but I plan to do something practical for myself. If this will work, you guys can close this thread. I feel very dumb haha. I'm gonna try it out and if it works ill post my solution. Thanks again!
[EDIT]
It worked! I defined this function: def callback(r,audio) which is needed for stop_listening = r.listen_in_background(m, callback). I am having a hard time understanding the purpose of this line: stop_listening(wait_for_stop=True). If someone can please explain a bit so I can use it better in the future. Finally i added a 'magic word' to quit the program (just say 'quit' and sys.quit() terminates the program.). Is there a better way to do this?
Here is the new code:
import time
import speech_recognition as sr
import sys
def callback(r, audio):
global done
try:
print(f"[PocketSphinx]: Thinks you said: '{r.recognize_sphinx(audio)}'. Read some more ")
except sr.UnknownValueError:
print(f"[PocketSphinx]: Fatal error! Unknown Value Error! Exiting program.")
except sr.RequestError as ex:
print(f"[PocketSphinx]: Fatal error! Could not process request! {ex}")
if r.recognize_sphinx(audio) == 'quit':
print(f"[PocketSphinx]: You said the magic word: 'quit'... Exiting program.")
done = True
r = sr.Recognizer()
r.energy_threshold = 4000
m = sr.Microphone()
done = False
with m as source:
r.adjust_for_ambient_noise(source)
print(f"[PocketSphinx]: Read to me... Say 'quit' to exit...")
stop_listening = r.listen_in_background(m, callback)
# 5 second delay
for _ in range(50):
time.sleep(0.1)
while not done:
time.sleep(0.1)
if done:
stop_listening(wait_for_stop=True)
sys.exit()
Related
this is the error i get for my code I cant seem to find out how to fix it
File "C:\Users\mayar\Desktop\final edge project\execute_html.py", line 19
elif a=="no":
^
SyntaxError: invalid syntax
Code -
import codecs
import subprocess
import os
while (True):
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
url = "CORONAVIRUS.htm"
#Python executes code following the try statement as a “normal” part of the program
try:
os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
except AttributeError:
try:
subprocess.call(['open', url])
except:
print('Could not open URL')
break
elif a=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")
You need to have elif directly after if. You can't have any other lines of codes between an if and the following elifs. You are probably messing up with the indentations in your code. You can edit your code to have try except to be included inside the first if statement and then it will work.
Correct code -
import codecs
import subprocess
import os
while (True):
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
url = "CORONAVIRUS.htm"
try:
os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
except AttributeError:
try:
subprocess.call(['open', url])
except:
print('Could not open URL')
break
elif corona=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")
Use this code:
import codecs
import subprocess
import os
while (True):
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
url = "CORONAVIRUS.htm"
#Python executes code following the try statement as a “normal” part of the program
try:
os.startfile(url)
except AttributeError:
try:
subprocess.call(['open', URL])
except:
print('Could not open URL')
break
elif corona=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")
Right code:
import codecs
import subprocess
import os
url = "CORONAVIRUS.htm"
while True:
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
#Python executes code following the try statement as a “normal” part of the program
try:
os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
except AttributeError:
try:
subprocess.call(['open', url])
except:
print('Could not open URL')
break
elif corona=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")
I am trying to capture my keystrokes and return them back to myself. When I run the code I expect to get back what I whichever keys I pressed while the code was running in that order. I don't have an issue there, everything returns fine. But then after the code is ran it returns '-Bash: (myinput): command not found
from __future__ import print_function
import keyboard
keys = []
def keys_in():
try:
while True:
recorded = keyboard.read_key(suppress=True)
keys.append(recorded)
if recorded == 'enter':
print(sorted(set(keys),key=keys.index))
break
keys.append(recorded)
except KeyboardInterrupt:
print('done')
quit()
keys_in()
When I put 1234 in I get :['1', '2', '3', '4', 'enter']
$ 1234
-bash: 1234: command not found
And I'm not sure why it's trying to run my input afterword. Help?
import keyboard
s = set()
def keys_in():
recorded = keyboard.read_key(suppress=True)
while recorded != "enter":
s.add(recorded)
print(list(s))
keys_in()
Try this out. Sets are already sorted. you dont need to add. Does this do it?
I am not familiar with the keyboard module but it appears that, while it does indeed pass the input to the python program, it does it in such a way that the shell gets the input when the python program exits, as if it had been entered on the command line. Here are two options (which do not require installing the keyboard module):
Using sys.stdin.read
from __future__ import print_function
import sys
keys = []
def keys_in():
try:
while True:
recorded = sys.stdin.read(1)
keys.append(recorded)
if recorded == '\n':
print(sorted(set(keys),key=keys.index))
break
keys.append(recorded)
except KeyboardInterrupt:
print('done')
quit()
keys_in()
Using 'input'
from __future__ import print_function
import sys
keys = []
def keys_in():
try:
input_string = input('')
for recorded in input_string:
keys.append(recorded)
except KeyboardInterrupt:
print('done')
quit()
print(sorted(set(keys),key=keys.index))
keys_in()
With the help of https://stackoverflow.com/a/22391379/9088305 and APT command line interface-like yes/no input? I have been able to build a little script that wait for a while but can be interrupted by pressing enter.
import sys, select, os, time
from distutils.util import strtobool
for i in range(100):
sys.stdout.write("\r")
sys.stdout.write("Wait for {:2d} seconds. Press Enter to continue".format(i))
sys.stdout.flush()
time.sleep(1)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
check = 0
while not check:
userin = raw_input("Are you sure you want to continue? (yes/no)")
try:
bool = strtobool(userin)
if bool:
check = 1
break
else:
print("Let's continue then")
time.sleep(1)
break
except ValueError:
check = 0
print("Choose either yes or no, please")
if check == 1:
break
print "\nDone!"
However, upon execution, it will alway give the question once, with an ""Choose either yes or no, please" after that:
Are you sure you want to continue? (yes/no)Choose either yes or no, please Are you sure you want to continue? (yes/no)
I haven't been able to figure out why this is. Can someone help me out? So that I can just get "Are you sure you want to continue? (yes/no)" once and I can put in yes or no.
Thanks in advance!
I'm trying to make a password system for a program. I have the first half working so when I punch in the code it opens my file. After that the program asks for the password again instead of moving on to the next module which is supposed to close the file. Here's what I have
import os
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
except Exception as e:
print (str(e))
while True:
choice = int(input("Close? (y/n): "))
if (choice<='y'):
if choice =='y':
os.system('TASKKILL /F /IM C:\\restriced access')
I want it to kind of appear as an "if/then" kinda statement. For example if the password is entered correctly it opens the file `os.startfile('C:\restriced access') then points to the next module to give the option to close.
"While True" just keeps looping infinitely. As soon as you open the file it'll go back to the beginning of that loop and ask for your password again. If you want it to break from that loop if they get the password correct you need to add a "break" after your startfile line. I'm also not sure why you check their password twice. If you want it to exit the loop after attempting to open the file whether it succeeds or not, add a "finally" block after your exception handler.
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
Your while loop is while True:. This will never exit unless you explicitly exit from it. You want to add a break in it like so:
os.startfile('C:\\restriced access')
break
Great to see you learn python.
The reason is because the while loop doesn't have a break in it.
Then again avoid opening files in a loop.
Also the nested if makes it hard to debug.
Also checkout pep8.
havent made any code changes.
import os
while True:
choice = int(input("Enter Password: "))
if (choice<1124):
continue
if choice ==1124:
try: os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
break
while True:
choice = input("Close? (y/n): ")
if (choice=='y'):
break
Hi I have troubles using sys.exit in a python console. It works really nice with ipython. My code looks roughly like this:
if name == "lin":
do stuff
elif name == "static":
do other stuff
else:
sys.exit("error in input argument name, Unknown name")
If know the program know jumps in the else loop it breaks down and gives me the error message. If I use IPython everything is nice but if I use a Python console the console freezes and I have to restart it which is kind of inconvenient.
I use Python 2.7 with Spyder on MAC.
Is there a workaround such that I the code works in Python and IPython in the same way? Is this a spyder problem?
Thanks for help
Not sure this is what you should be using sys.exit for. This function basically just throws a special exception (SystemExit) that is not caught by the python REPL. Basically it exits python, and you go back to the terminal shell. ipython's REPL does catch SystemExit. It displays the message and then goes back to the REPL.
Rather than using sys.exit you should do something like:
def do_something(name):
if name == "lin":
print("do stuff")
elif name == "static":
print("do other stuff")
else:
raise ValueError("Unknown name: {}".format(name))
while True:
name = raw_input("enter a name: ")
try:
do_something(name)
except ValueError as e:
print("There was a problem with your input.")
print(e)
else:
print("success")
break # exit loop
You need to import sys. The following works for me:
import sys
name="dave"
if name == "lin":
print "do stuff"
elif name == "static":
print "do other stuff"
else:
sys.exit("error in input argument name, Unknown name")