0

I am trying to use Python to select a variable from a list, then speak it outloud using the bash command. Right now I have something like this

foo = ["a","b","c","d"]
from random import choice
x = choice(foo)
foo.remove(x)
from os import system
system('say x')

This says "x", what I need is for it to say the value of the x variable.

4

4 Answers 4

4

I suppose you can use os.system, but better might be subprocess:

import subprocess
subprocess.call(['say',x])
Sign up to request clarification or add additional context in comments.

Comments

2

you are passing astring you can use value of x like

sytem('say {0}'.format(x))

When passing strings you can use string formatting. As you realized you need to get the value of x in the string not the variable x http://docs.python.org/library/string.html#format-examples

1 Comment

Note that this is the old style of string formatting, and in new software, str.format() is the recommended method - e.g: system('say {0}'.format(x)).
0

You can use format:

system('say {}'.format(x))

Comments

0

use string formatting:

In [9]: x="ls -ld"

In [10]: os.system("{0}".format(x))
drwxr-xr-x 41 monty monty 4096 2012-10-10 22:46 .
Out[10]: 0

2 Comments

os.system is inflexible and can be error-prone and insecure. The subprocess module provides much better functionality for this.
"{0}".format("value") is just an incredibly complex way to say "value".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.