Loading message in Python 2.7? - python

I am making a personal assistant in Python 2.7 using the modules 'wikipedia', 'wolframalpha' and 'pyttsx3'. I am making so that the user can ask a question and the computer will then search Wikipedia and Wolfram and speak the answer using Pyttsx. This all works fine but the computer takes a while to fetch the results for the question and I was wondering if it would be possible to add a simple '...loading...' message while is does this. I have added the code below and it would be great if you could respond.
import wikipedia
import wolframalpha
import pyttsx3;
engine = pyttsx3.init();
while True:
my_input = raw_input("Question: ")
try:
#wolframalpha code here
app_id = "Q2HXJ5-GYYYX6PYYP"
client = wolframalpha.Client(app_id)
res = client.query(my_input)
answer = next(res.results).text
print(answer)
engine.say(answer);
engine.runAndWait();
except:
try:
#wikipedia code here
print(wikipedia.summary(my_input))
except:
print("Sorry nothing can be found from your query")

If you want to remove Loading... after the API call is completed, you can just move the cursor to the start of that line using the escape code ESC[1000D. Note that you must use sys.stdout.write() as opposed to print here, as we want this all to happen on the same line.
import sys
// Before API Call
sys.stdout.write("Loading...")
sys.stdout.flush()
// After API Call
sys.stdout.write(u"\u001b[1000D")
print "Done! "
Note the u proceeding the double-quoted string. This is required in Python 2.x, as it includes special characters, but can be omitted in Python 3.
(By the way, the extra spaces on Done are only there so that the string is longer than Loading... so that it replaces it completely, without leaving ng... on the end)

Related

Encrypt already saved files on a computer

from string import maketrans
intab = "abcdefghijklmnopqrstuvwxyz"
outtab = "nopqrstuvwxyzabcdefghijklm"
trantab = maketrans(intab, outtab)
print "Do you want to translate a random term, or a file?(Please enter file name in the code)"
RandOrFile = raw_input ("Type 1 to enter a custom term, or 2 to translate a whole file")
if RandOrFile == "1":
inputA = raw_input ("Enter a phrase to translate")
str = inputA
print str.translate(trantab);
elif RandOrFile == "2":
(Code for my program)
I am attempting to create a program which encrypts a file, and turns the letters into other letters, like an Enigma Machine (But much more simple). I have made it so that you can directly translate user entered phrases, as the top chunk of the code shows, but I cant work out how to translate already made files on the users computer.
The code is meant to go under the "elif RandOrFile == "2"" line, but I cant work out how to a) fetch the data from a specified file on a computer, and b) work out how to translate that file in the program.
I have researched, but I cant find any ways to do so. My python skills are very beginner, so if you could possibly quote relevant sources to help on this, that would also be helpful, although I have tried, i'm not really sure where to begin while looking through tutorial websites.

Python: EOFError: EOF when reading a line

This may be repeated, but none of the existing answers solved my problem.
So, I'm using Python 2.7, and I get this error (title) whenever I try this:
number = int(raw_input('Number : '))
I tried this in Sublime Text 2, compileronline.com and in codecademy; it fails in the first 2 of this sites. It works on codecademy and in the terminal compiler, but I can't understand exactly why it is failing.
The issue here is that Sublime text 2's console doesn't support input.
To fix this issue, you can install a package called SublimeREPL. SublimeREPL provides a Python interpreter that takes in input.
And as for compileronline.com, you need to provide input in the "STDIN Input" field on the lower right of the website.
try:
value = raw_input()
do_stuff(value) # next line was found
except (EOFError):
break #end of file reached
This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input.
Refer this post

Shift + Return to insert linebreak in python

I'm trying to get the behaviour of typical IM clients that use Return to send a text and Shift + Return to insert a linebreak. Is there a way to achieve that with minimal effort in Python, using e.g. readline and raw_input?
Ok, I heard it can be accomplished also with the readline, in a way.
You can import readline and set in configuration your desired key (Shift+Enter) to a macro that put some special char to the end of the line and newline. Then you can call raw_input in a loop.
Like this:
import readline
# I am using Ctrl+K to insert line break
# (dont know what symbol is for shift+enter)
readline.parse_and_bind('C-k: "#\n"')
text = []
line = "#"
while line and line[-1]=='#':
line = raw_input("> ")
if line.endswith("#"):
text.append(line[:-1])
else:
text.append(line)
# all lines are in "text" list variable
print "\n".join(text)
I doubt you'd be able to do that just using the readline module as it will not capture the individual keys pressed and rather just processes the character responses from your input driver.
You could do it with PyHook though and if the Shift key is pressed along with the Enter key to inject a new-line into your readline stream.
I think that with minimal effort you can use urwid library for Python. Unfortunately, this does not satisfy your requirement to use readline/raw_input.
Update: Please see also this answer for other solution.
import readline
# I am using Ctrl+x to insert line break
# (dont know the symbols and bindings for meta-key or shift-key,
# let alone 4 shift+enter)
def startup_hook():
readline.insert_text('» ') # \033[32m»\033[0m
def prmpt():
try:
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
readline.parse_and_bind('C-x: "\x16\n"') # \x16 is C-v which writes
readline.set_startup_hook(startup_hook) # the \n without returning
except Exception as e: # thus no need 4 appending
print (e) # '#' 2 write multilines
return # simply use ctrl-x or other some other bind
while True: # instead of shift + enter
try:
line = raw_input()
print '%s' % line
except EOFError:
print 'EOF signaled, exiting...'
break
# It can probably be improved more to use meta+key or maybe even shift enter
# Anyways sry 4 any errors I probably may have made.. first time answering

python pexpect sendcontrol key characters

I am working with pythons pexpect module to automate tasks, I need help in figuring out key characters to use with sendcontrol. how could one send the controlkey ENTER ? and for future reference how can we find the key characters?
here is the code i am working on.
#!/usr/bin/env python
import pexpect
id = pexpect.spawn ('ftp 192.168.3.140')
id.expect_exact('Name')
id.sendline ('anonymous')
id.expect_exact ('Password')
*# Not sure how to send the enter control key
id.sendcontrol ('???')*
id.expect_exact ('ftp')
id.sendline ('dir')
id.expect_exact ('ftp')
lines = id.before.split ('\n')
for line in lines :
print line
pexpect has no sendcontrol() method. In your example you appear to be trying to send an empty line. To do that, use:
id.sendline('')
If you need to send real control characters then you can send() a string that contains the appropriate character value. For instance, to send a control-C you would:
id.send('\003')
or:
id.send(chr(3))
Responses to comment #2:
Sorry, I typo'ed the module name -- now fixed. More importantly, I was looking at old documentation on noah.org instead of the latest documentation at SourceForge. The newer documentation does show a sendcontrol() method. It takes an argument that is either a letter (for instance, sendcontrol('c') sends a control-C) or one of a variety of punctuation characters representing the control characters that don't correspond to letters. But really sendcontrol() is just a convenient wrapper around the send() method, which is what sendcontrol() calls after after it has calculated the actual value that you want to send. You can read the source for yourself at line 973 of this file.
I don't understand why id.sendline('') does not work, especially given that it apparently works for sending the user name to the spawned ftp program. If you want to try using sendcontrol() instead then that would be either:
id.sendcontrol('j')
to send a Linefeed character (which is control-j, or decimal 10) or:
id.sendcontrol('m')
to send a Carriage Return (which is control-m, or decimal 13).
If those don't work then please explain exactly what does happen, and how that differs from what you wanted or expected to happen.
If you're just looking to "press enter", you can send a newline:
id.send("\n")
As for other characters that you might want to use sendcontrol() with, I found this useful: https://condor.depaul.edu/sjost/lsp121/documents/ascii-npr.htm
For instance, I was interested in Ctrl+v. Looking it up in the table shows this line:
control character
python & java
decimal
description
^v
\x16
22
synchronous idle
So if I want to send that character, I can do any of these:
id.send('\x16')
id.send(chr(22))
id.sendcontrol('v')
sendcontrol() just looks up the correct character to send and then sends it like any other text
For keys not listed in that table, you can run this script: https://github.com/pexpect/pexpect/blob/master/tests/getch.py (ctrl space to exit)
For instance, ran that script and pressed F4 and it said:
27<STOP>
79<STOP>
83<STOP>
So then to press F4 via pexpect:
id.send(chr(27) + chr(79) + chr(83))

Deleting already printed in Python

For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.
I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?
How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?
You mentioned this was a simple game so a simple solution seems fitting.
[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print '\n' * numlines
word = raw_input("Your word: ")
import sys
sys.stdout.write("\x1b[1A" + 25*" " + "\n")
This will replace the last line printed with 25 spaces.
I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.
Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.
Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline

Categories