taizilongxu
1/22/2015 - 3:09 PM

test.py

#-*- encoding: UTF-8 -*-
#---------------------------------import------------------------------------
import subprocess
import time
#---------------------------------------------------------------------------
import os
import tempfile
mplayer_controller = os.path.join(tempfile.mkdtemp(), 'mplayer_controller')
os.mkfifo(mplayer_controller)
cmd = 'mplayer -slave -quiet -input file={fifo} {song_url}'
song = '6.m4a'
p = subprocess.Popen(cmd.format(fifo=mplayer_controller, song_url=song), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)  # subprocess.PIPE防止继承父进程

time.sleep(5)

p.stdin.write('get_time_pos\n')

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()

while True:
    print perform_command(p, 'get_time_pos', 'ANS_TIME_POSITION')



############################################################################