view raw
wim wim - 6 months ago 86
Python Question

Terminal text becomes invisible after terminating subprocess

After terminating an

subprocess, the terminal gets messed up - typed characters are invisible! The input still works in that commands can be executed, but keyboard input is not echoed to the terminal.

Issuing shell command
puts everything back to normal (or
from within ipython), so a workaround the issue is calling
inside the script.

Other things I've tried:
import curses; curses.initscr()
before spawning the subprocess and
after termination, which worked somewhat but broke other stuff. Another possibly related issue is that after spawning the child process, the interactive terminal becomes laggy and sometimes fails to capture typed characters.

The code to spawn the process looks like:

with open('/tmp/stdout.log', 'w') as o:
with open('/tmp/stderr.log', 'w') as e:
proc = subprocess.Popen([args], stdout=o, stderr=e)

And later to stop it:


What could be going wrong here?

wim wim

It appears to be resolved by changing other implementation details of the setup so that proc.terminate() is not required. I can now reliably stop my encoder more politely with


and I haven't seen the problem appear, touch wood. I guess it is due to allowing ffmpeg the chance to write whatever escape sequences it needs to restore the terminal, as bjarneh has mentioned.

edit: discovered later- another trick to make ffmpeg behave nicer in a python subprocess is to provide it subprocess.PIPE or open(os.devnull) in the stdin handle. otherwise, it seems to try to get input from the parent's stdin which can cause weird terminal behaviour (I think this is due to a running ffmpeg process listening for '?' and 'q')