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)