Python 2.7 having multiple say commands on mac - python

I have tried many things to try to get text to speech to work in python 2.7 on a mac. I managed to write some simple codes using the system os such as:
from os import system
system('say Hello world')
This works alone:
from os import system
string2 = 'test'
string1 = 'hello world' + string2 + '.'
system("say %s" %(string1))
But if I do multiple say commands, like this:
system('say Please tell me your name.')
name = raw_input()
st = "Hello. Want pie" + name + "?"
system("say " + st)
I get this error after I enter my name:
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
Am I currently making a mistake in concept, or does having two say commands not work? If having two say commands do not work this way, then how can I use text to speech multiple times in python 2.7 with macintosh?

Trying changing the format and see if you have any better luck.
system('say Please tell me your name.')
name = raw_input()
st = "Hello. Want pie" + name + "?"
system('say %s' %(st))

Related

What could be my invalid syntax error in my code?

I am having problems with a simple program I wrote but do not know where the problem is, and it is giving me a Syntax error.
This is my code:
username = {}
temp = True
while temp:
name = input("Please input your username: ")
response = input("What is the place you want to visit? ")
username[name] = response
end = input("Do you want to end the program? Yes/No ")
if end == 'Yes':
temp = False
print("These are the results of the poll: ")
for names, responses in username.items():
print(names + " wants to go to " + responses)
This is my error:
File "<stdin>", line 1
/usr/local/bin/python3 "/Users/eric/Python Notes/Notes.py"
^
SyntaxError: invalid syntax
Check out the accepted answer here:
syntax error when using command line in python
Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.
Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.
There are also some VSCode-specific tips here:
Invalid Syntax error when running python from inside Visual Studio Code

Python running in IDLE but not terminal? [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 6 years ago.
upon looking around a bit I have still not come to the conclusion as to why the following piece of python works in IDLE but not terminal. Any help would be appreciated.
print("Hello User!")
request_list = ['']
while True:
greeting = input('')
if greeting.lower() == "hello":
print("Who is this?")
print("Welcome back " + input() +", what can I do for you?")
break
elif greeting.lower() != "hello":
print("Show some manners!")
The error
Traceback (most recent call last):
File "courtney.py", line 23, in <module>
greeting = input('')
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
you are running python3 IDLE and the terminal is set to python2.
In your computer's environmental variables, you want to change the path to the location of your Python3 installation instead of the python 2.
Take a look at the picture, the one you want to change is PATH
If you dont want to change your environmental variables so that your terminal stays using python2, then you have to change your input and print statements.
the code below is the implementation of your code in python 2.7:
print "Hello User!"
request_list = ['']
while True:
greeting = raw_input("What is your name? ")
if greeting.lower() == "hello":
print "Who is this?"
print "Welcome back " + greeting +", what can I do for you?"
break
elif greeting.lower() != "hello":
print "Show some manners!"
The problem is that you use python 2.x in your terminal. If you have installed both you should be able to use the command 'python3' to run your code instead of the command 'python'.
In python 3 'input' can take an integer or a string. In python2 'input' cannot take a string. Only other stuff. In python 2.x you should use 'raw_input' take a string.

Festival TTS viseme file generation in bash / python

Am currently working on a project that uses Festival TTS engine on the RPi.
Have used it plenty before. I have also used pyfestival to do basic stuff. I am currently trying to generate the viseme file for a piece of text. This works perfectly if done in the Festival command interpreter, I need to do the exact same but in bash or python.
festival> (set! mytext (SayText "Hello word"))
festival> (utt.save.segs mytext "hw_viseme_file")
Have searched high and low for this info but have drawn a blank. Can someone give an example of how the 2 lines of code above can be called from either bash or Python?
Many thanks.
DP.
The festival command has a --script option, so you should be able to run from bash something like:
festival --script generate_visemes
Where 'generate-visemes' contains the Festival commands (above) that you want to execute.
From python you can call an external program like this:
os.system("festival --script generate_visemes")
Perhaps to create the script file, something like this:
import os
ttsMessage = "Hello World"
ttsVisemeFile = "hw_viseme_file"
f = open('generate_visemes','w')
textParam = '(set! mytext(SayText "{0}"))\n'.format(ttsMessage)
visemeParam = '(utt.save.segs mytext "{0}")\n'.format(ttsVisemeFile)
f.write(textParam)
f.write(visemeParam)
f.close()
os.execute("festival --script generate_visemes")
Finally worked this out - is fairly involved. The following runs in Python 2.7 on RPi when Festival TTS engine is installed.
import os
#Simple example
bashcommand = "echo 'Hello World' | festival --tts"
os.system(bashcommand)
# This bash command takes the entered phrase and returns an audio .wav file and a text file of the visemes
while True:
phrase = raw_input("Enter phrase:")
bashcommand = "festival -b '(set! mytext (Utterance Text " + '"' + phrase + '"))' + "' '(utt.synth mytext)' '(utt.save.wave mytext " + '"my_wav.wav")' + "' '(utt.save.segs mytext " + '"textfile"' + ")'"
os.system(bashcommand)
You can of course also just run the bash from the command line. Hope that may help someone in the future.

invalid syntax for Python Telnet command

I am coding a script interpreter. It should generate a Telnet session to send AT commands.
Here is the script which it generated:
telentHandle = None
if telentHandle == None:
import telnetlib
telentHandle = telnetlib.Telnet(10.49.188.187, 23456)
telentHandle.read_until("login: ")
telentHandle.write(userName + "\n")
telentHandle.read_until("Password: ")
telentHandle.write(password + "\n")
telentHandle.write(AT + "\n")
When I run it, I get
File "H:/code/testgen/test_script.txt.py", line 10
telentHandle = telnetlib.Telnet(10.49.188.187, 23456)
^
SyntaxError: invalid syntax
What am I doing wrongly?
10.49.188.187 isn't a valid identifier in Python (or any language). You presumably need a string: "10.49.188.187".

Why I got "sh: 1: Syntax error: Unterminated quoted string" when I run my Python program?

I want to count how many lines of code I have written.
Here is the Python code:
import os
import sys
EXT = ['.c','.cpp','.java','.py']
def main():
l = []
if os.path.isdir(sys.argv[1]):
for root, dirs, files in os.walk(sys.argv[1]):
l.extend([os.path.join(root, name) for name in files])
else:
l.append(sys.argv[1])
params = ["'"+p+"'" for p in l if os.path.splitext(p)[1] in EXT]
result = os.popen("wc -l %s "%" ".join(params)).read()
print result
if __name__ == '__main__':
main()
Before this, it was running as expected. But today, it give me this error:
sh: 1: Syntax error: Unterminated quoted string
I don't know what happened.
Your Python script is missing a shebang line. Add the following to the top of your file:
#!/usr/bin/env python
Then you should be able to run the following, assuming your script is at /path/to/your_script.py and it has the executable bit set:
/path/to/your_script.py arg1 arg2 [...]
Alternatively:
python /path/to/your_script.py arg1 arg2 [...]
Update following comments
I suspect what has changed is that a source file containing a ' in its name has been added to the directory you are checking and the shell is choking on this.
You could add the following function to your program:
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
[Lifted from Greg Hewgill's answer to How to escape os.system() calls in Python? .]
And call it like this:
params = [shellquote(p) for p in l if os.path.splitext(p)[1] in EXT]
#Johnsyweb's updated answer seems to have the correct diagnostic, but the correct fix is to not use a shell to invoke wc. Try something like this instead:
cmd = ['/bin/wc', '-l'] # Need full path!
[cmd.extend(p) for p in l if os.path.splitext(p)[1] in EXT]
result = os.popen2(cmd).read()
Note that the subprocess module is the recommended solution now. Switching to that requires a less intrusive change to your current code, though; see http://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3
Looks like your Python program was parsed like a shell script. Add something like this at the header to indicate where your Python is:
#!/usr/bin/python
or you just run python a.py.

Categories

Resources