subprocess.communicate messes things up

K

KingShivan

please could you take a look at this piece of code ?

what I'd like is typically a sound boc : press one key, and get the
associated sound.
for this I place the sound files in different directories (easy to
move and modify) and when a key is pressed I grab the first file of
the corresponding directory.

problem is that the first time I press a key, it works, but after it
just print the keys I press, the annoying line being the one with
communicate, any idea of what is happening ?

thank you for reading

import os,subprocess, tty, termios,sys,time
FNULL = open('/dev/null', 'w')
def getkey():
file = sys.stdin.fileno()
mode = termios.tcgetattr(file)
try:
tty.setraw(file, termios.TCSANOW)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(file, termios.TCSANOW, mode)
return ch

def main():
child1 = subprocess.Popen("/usr/bin/mplayer -slave -quiet -
idle",stdin=subprocess.PIPE,stdout=FNULL,stderr=FNULL,shell=True)
while 1:
ch=getkey()
name=os.listdir("/home/shivan/"+ch)
file_to_load = "/home/shivan/"+ch+"/"+name[0]
print "loadfile "+file_to_load
output, errors = child1.communicate("loadfile "+file_to_load+" \n")



main()
 
G

Gabriel Genellina

problem is that the first time I press a key, it works, but after it
just print the keys I press, the annoying line being the one with
communicate, any idea of what is happening ?

child1 = subprocess.Popen("/usr/bin/mplayer -slave -quiet -
idle",stdin=subprocess.PIPE,stdout=FNULL,stderr=FNULL,shell=True)
while 1:
ch=getkey()
name=os.listdir("/home/shivan/"+ch)
file_to_load = "/home/shivan/"+ch+"/"+name[0]
print "loadfile "+file_to_load
output, errors = child1.communicate("loadfile "+file_to_load+" \n")

communicate sends its input and waits until the process finishes,
collecting all output. So it's not adequate for your needs.
You should write directly to child1.stdin: child1.stdin.write("loadfile
"+file_to_load+" \n")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top