Why does python raw_input function gives questionline twice as output? - python

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!

Related

Multiple phrases with SpeechRecognition in python

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()

Making a GUI File Downloader with Python 3 and Tkinter

(I am using python 3.6.6 if that matters to anyone)
I am making a GUI installer for a game that is currently in private alpha and is constantly updating.
I already made a console version:
from tqdm import tqdm
import requests, os, sys, zipfile, shutil, subprocess
chunk_size = 1024
url = "{LINK TO FILE YOU WANT TO DOWNLOAD}"
r = requests.get(url, stream = True)
total_size = int(r.headers['content-length'])
print("Are you sure you want to download the newest version of RFMP?")
print("y/n", end=': ')
answer = input()
while True:
if answer == 'y':
if os.path.exists("RFMB6_WINDOWS"):
print('')
print('')
print('Removing old RFMP files...')
subprocess.check_call(('attrib -R ' + 'RFMB6_WINDOWS' + '\\* /S').split())
shutil.rmtree('RFMB6_WINDOWS')
print('')
print('Removed old files.')
break
else:
break
elif answer == 'n':
sys.exit()
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
print('')
print('')
print('Downloading:')
with open('RFMB6_WINDOWS.zip', 'wb') as f:
for data in tqdm(iterable = r.iter_content(chunk_size = chunk_size), total = total_size/chunk_size, unit = 'KB'):
f.write(data)
print('')
print("Download Complete.")
print('')
print('')
print("Would you like to extract it?")
print("y/n", end=': ')
answer2 = input()
while True:
if answer2 == 'y':
print('')
print('')
print('Extracting...')
zip_ref = zipfile.ZipFile("RFMB6_WINDOWS.zip", 'r')
zip_ref.extractall("RFMB6_WINDOWS")
zip_ref.close()
print('')
print('Extraction Complete')
print('')
print('')
print('Cleaning up...')
os.remove("RFMB6_WINDOWS.zip")
print('')
print('Done! You have succesfully installed the newest version of the Ravenfield Multiplayer Private Alpha.')
break
elif answer2 == 'n':
print('')
print('Done! You have succesfully downloaded the newest Zip of the Ravenfield Multiplayer Private Alpha.')
break
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
os.system('pause')
I will only be using this to download 1 specific link so ignore the url variable.
I am trying to make a GUI that does the same thing when I click a button that says 'Download'. I want to make a progress bar, and a text box that tells you what is going on e.g. Downloading, extracting etc. I have no need for a directory option. I just need it to download where ever the file is located and delete the old file if it is still there.
So here is my question: How do I learn how to do this? I have looked at tkinter tutorials and other questions but I only find stuff for python 2 or stuff that is to developed to modify and call my own work. What I am looking for are links and/or examples that can tell me how I go about creating something like this. Thanks in advance to anyone who helps me out.
P.S. I am a noob when it comes to coding so whatever you explain please do it thoroughly.
P.S.S. In order to run the console application you need to run it through terminal and add your own link in the 'url' variable.
Take a look at PySimpleGUI. You can build a layout with a download button, an output window and a progress bar easily. Stop by the GitHub and post an issue if you run into trouble.
The documentation for Tkinter with Python3:
https://docs.python.org/3/library/tk.html
This answer might help you out:
How to create downloading progress bar in ttk?
documentation: https://tkdocs.com/tutorial/morewidgets.html#progressbar

How to point from one module to the next

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

Python 3.4 How do you limit user input

I have made a program which requires the user to go and come back after completing the command, I would like the user to press ENTER to then continue the programme, to do this I used a normal Input command that does not record the answer. However I would like it if the user cannot enter any text, the only thing they can do is press ENTER to proceed.
input("Please charge your device, when you are finished, press ENTER on the keyboard")
You can try to write an if loop that checks whatever the input is enter: For example:
import tty
import sys
import termios
orig_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin)
x = input("Text")
while x != chr(13): # Enter
x=sys.stdin.read(1)[0]
print("ERROR PLEASE TRY AGAIN")
x = input("Text")
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)
You might like to check this answer by #Turn at the question here: https://stackoverflow.com/a/34497639/2080764

How to turn my if statement into a while or for loop?

So the program I'm trying to make is that an user can enter a path WHICH HAS TO BE CORRECT to continue. I thought that I would make a simple prompt to tell the user it is either a valid path or not.
This is my prompt code:
if Path.find("Global") == -1:
continue
else:
print "Not a valid path."
Of course I can't use continue in there but I just don't get how to make this prompt as a loop. The idea was that if the Path contains the word "Global" the program continues with another action and if it doesn't contain the word it will tell the user a message and tell the program to stop (break).
def get_path():
Path = raw_input("Please select the correct path: ")
if Path.find("Global") == -1:
# "Tell the user a message and tell the program to stop".
print('{0} is not a correct path.'.format(Path))
return
# "the program continues with another action."
print('{0} is a correct path.'.format(Path))
You can break the loop unless your input matches condition, like this:
while True:
if 'Global' in raw_input('Enter a valid path: '):
continue
else:
print 'Not a valid path.'
break
Try this:
Path = raw_input("Please enter a valid Path")
while Path.find("Global") == -1:
print "This is not a valid Path."
Path = raw_input("Please enter a valid Path")

Categories

Resources