Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python interact with running process

Tags:

python

linux

I have a python script that allows me to interact with my Rapsberry Pi from my phone using a simple web server (Flask).

In this script, I can call omxplayer to play a media file, I do this via a command like this:

Popen(['omxplayer '+filePath], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

This works fine but then I would like to be able to interact with this process by sending key commands. When omxplayer is running, you can press space to play/pause, arrows to skip forward/back, etc. I would like to send these keyboard inputs programatically from my python script instead of requiring a person to manually press them on the keyboard.

How can I send a key command to this process from Python after opening it with Python?

Also, how can I detect from Python if there is another instance of omxplayer running that is not being currently run from this Python script? For example, if omxplayer was called and is running from someone on an ssh connection, how can I detect this inside the python script and kill this process before calling my own omxplayer process?

like image 314
shiznatix Avatar asked Dec 24 '13 13:12

shiznatix


1 Answers

It sounds like omxplayer is reading from stdin - you can probably write to that process' stdin with your commands.

from subprocess import Popen, PIPE
p = Popen(['omxplayer', filePath], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.write(' ') # sends a space to the running process
p.stdin.flush() # if the above isn't enough, try adding a flush

Edit: To send arrow keys, try Ctrl+v and then in a terminal to see what key code is being sent - it will be ^[[D, or esc[D. You can enter this with stream.write("\x1b[D") (or "^[[D", where the ^[ is one character produced by Ctrl+v esc and waiting half a second).

like image 163
Thomas Avatar answered Oct 25 '22 05:10

Thomas