How to send Python variable to bash variable?

我的未来我决定 提交于 2021-02-17 06:42:08

问题


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.


回答1:


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

import subprocess
subprocess.call(['say',x])



回答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




回答3:


You can use format:

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



回答4:


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


来源:https://stackoverflow.com/questions/12826250/how-to-send-python-variable-to-bash-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!