gpt4 book ai didi

Python:从模式下向mplayer发送命令

转载 作者:行者123 更新时间:2023-11-28 21:24:32 26 4
gpt4 key购买 nike

在从属模式下运行时,我试图通过管道向 mplayer 发送命令,如下所示:

import subprocess, time
# start mplayer
song = 'mysong.mp3'
cmd = ['mplayer', '-slave', '-quiet', song]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)

# send a command every 3 seconds.
# Full command reference here: http://www.mplayerhq.hu/DOCS/tech/slave.txt
while True:
print('sleep 3 seconds ...')
time.sleep(3)
cmd = 'get_meta_artist'
print('send command: {}'.format(cmd))
p.stdin.write(cmd)
output = p.communicate()[0]
print(output)

但输出什么也没有。

我以 this question 为例.

在终端中运行相同的 mplayer 命令工作正常。我在这里缺少什么?

更新:

我将我的 cmd 从“get_meta_artist”更改为“get_meta_artist\n”,这样换行符也会发送到管道,但我仍然没有得到任何输出。

更新 2:

我把cmd改成了“\npause\n”,音乐就暂停了。所以这意味着通过 stdin 发送命令有效。这意味着“\nget_meta_artist\n”命令的输出字符串没有按预期返回......

最佳答案

您只能使用 .communicate()每个子进程一次。所以在 while 中使用它循环不起作用。

相反,您应该解析 p.stdout 的输出直接地。如果有答案,似乎每个答案只有一行。

为了防止阻塞,您有 3 个选择:

  1. 使用线程。您有一个单独的线程读取 p.stdout并将其数据发送到主线程。如果没有可用数据,它会阻止。

  2. 设置p.stdout到非阻塞模式。本质上,您必须这样做:

    import fcntl, os
    fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL,
    fcntl.fcntl(p.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)

    如果您在没有可用数据的情况下阅读,则会出现异常 ( IOError: [Errno 11] Resource temporarily unavailable)。

  3. select.select() 合作: 执行 p.stdout.readline()仅当select.select([p.stdout], [], [], <timeout>)[0]是一个非空列表。在这种情况下,给定的文件对象保证有数据可用并且不会在读取时阻塞。

为了将“垃圾输出”与“有用”输出分开,您可以这样做:

def perform_command(p, cmd, expect):
import select
p.stdin.write(cmd + '\n') # there's no need for a \n at the beginning
while select.select([p.stdout], [], [], 0.05)[0]: # give mplayer time to answer...
output = p.stdout.readline()
print("output: {}".format(output.rstrip()))
split_output = output.split(expect + '=', 1)
if len(split_output) == 2 and split_output[0] == '': # we have found it
value = split_output[1]
return value.rstrip()

然后做

print perform_command(p, 'get_meta_artist', 'ANS_META_ARTIST')
print perform_command(p, 'get_time_pos', 'ANS_TIME_POSITION')

关于Python:从模式下向mplayer发送命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15856922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com