如何使用多个参数执行os.system()

时间:2017-01-28 11:31:44

标签: python

我想用多个参数执行os.system()命令。

def playmp3(SongName, Freqency):
    os.system("sox -t mp3", SongName, "-t wav - | sudo pifmrds -freq", Freqency, "-audio", SongName)

但我总是得到这个错误:

>>> playmp3("/home/pi/music/hit_the_street2.wav", "105")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in playmp3
TypeError: system() takes exactly 1 argument (6 given)

1 个答案:

答案 0 :(得分:1)

你做不到。您必须自己编写命令行,例如使用format

os.system('sox -t mp3 "{0}" -t wav - | sudo pifmrds -freq "{1}" -audio "{0}"'.format(SongName,Frequency))

请注意01符号,它允许多次使用参数。

当你不知道它们是否包含空格时,用引号保护你的参数。

BTW这实际上是一种执行系统调用的过时方式。这很快&amp;脏,但2 subprocess.Popen次调用链接在一起,受控制的参数传递会更加清晰,如下所示:

proc1 = subprocess.Popen(["sox","-t","mp3",SongName,"-t","wav","-"],stdout=subprocess.PIPE)
proc2 = subprocess.Popen(["sudo","pifmrds","-freq",str(Frequency),"-audio",SongName],stdin=proc1.stdout)
proc2.wait()