【发布时间】:2016-02-26 02:29:52
【问题描述】:
我有一个...非常具体的问题。真的试图找到一个更广泛的问题,但找不到。
我正在尝试使用 mplayer 作为子进程来播放音乐(在 Windows 和 linux 上),并保留将命令传递给它的能力。我在 python 2.7 中使用subprocess.Popen 和p.stdin.write('pause\n') 完成了这一点。
然而,这似乎并没有在 Python 3 之旅中幸存下来。我必须使用 'pause\n'.encode() 或 b'pause\n' 转换为 bytes,并且 mplayer 进程不会暂停。但是,如果我使用p.communicate,它似乎确实有效,但我已经排除了这种可能性,因为this question 声称每个进程只能调用一次。
这是我的代码:
p = subprocess.Popen('mplayer -slave -quiet "C:\\users\\me\\music\\Nickel Creek\\Nickel Creek\\07 Sweet Afton.mp3"', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
time.sleep(1)
mplayer.stdin.write(b'pause\n')
time.sleep(1)
mplayer.stdin.write(b'pause\n')
time.sleep(1)
mplayer.stdin.write(b'quit\n')
看到此代码在 2.7 中有效(没有 bs),我只能假设将字符串编码为 bytes 会以某种方式更改字节值,以便 mplayer 无法再理解它?但是,当我尝试查看通过管道发送的确切字节时,它看起来是正确的。也可能是 Windows 管道表现得很奇怪。我用 cmd.exe 和 powershell 都试过了,因为我知道 powershell 将管道解释为 xml。我使用这段代码来测试通过管道输入的内容:
# test.py
if __name__ == "__main__":
x = ''
with open('test.out','w') as f:
while (len(x) == 0 or x[-1] != 'q'):
x += sys.stdin.read(1)
print(x)
f.write(x)
和
p = subprocess.Popen('python test.py', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
p.stdin.write(b'hello there\ntest2\nq\n')
【问题讨论】:
标签: python subprocess cross-platform mplayer