简体   繁体   中英

Python subprocess PIPE that works on Python 2 but not on Python 3

I'm trying to control a software MIDI synthesizer Timidity++ with subprocess in Python. The way I'm doing it is to start a process of Timidity++ in its Ncurses UI, and then pass commands to the STDIN of the subprocess. This way I can control the playback, for example adjust keys, in real-time.

The problem is that the approach seems to work on Python 2 (specifically Python 2.7.13), but not on Python 3 (specifically Python 3.5.3). What's the reason for that? I'm testing this on Raspbian 9.

My code is like the following:

from subprocess import *
import time
a = Popen(["timidity", "-in", "MIDI_sample.mid"], stdin=PIPE, stdout=PIPE)
time.sleep(4)
a.stdin.write(b"+")
time.sleep(4)
a.stdin.write(b"s")
time.sleep(4)
a.stdin.write(b"s")
time.sleep(4)
a.stdin.write(b"q")

This seems to work well on Python 2, ie you can hear the playback, pause and unpause, and key adjustments. On Python 3 it just plays through the MIDI file until the program terminates.

As Davis pointed out in the above comment, flushing a.stdin solved the problem. So the following code works for both Python 2 and 3:

from subprocess import *
import time
a = Popen(["timidity", "-in", "MIDI_sample.mid"], stdin=PIPE, stdout=PIPE)
time.sleep(4)
a.stdin.write(b"+")
a.stdin.flush()
time.sleep(4)
a.stdin.write(b"s")
a.stdin.flush()
time.sleep(4)
a.stdin.write(b"s")
a.stdin.flush()
time.sleep(4)
a.stdin.write(b"q")
a.stdin.flush()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM