Page 1 of 1

Single instance Python script terminal arguments after start

Posted: Wed Feb 08, 2017 5:11 pm
by mvdm
I have a python script that can accept arguments from startup. This script is constantly doing work in the background and should not be stopped or have a second instance generated as it will cause GPIO conflicts.

How do I call this script that's already running from a terminal so that I can give it commands or ask it to return a value without starting another instance or stopping the already running script?

For instance:

Code: Select all

[email protected]:~ $  mypythonscript -t
mypythonscript:  T=44C
[email protected]:~ $  mypythonscript -s
mypythonscript:  R=2300RPM
[email protected]:~ $  mypythonscript -q
mypythonscript:  Quitting, thanks for using mypythonscript
I'm just stuck on the part where I call the script a second time in the terminal to give commands/returns values to/from the already running script without closing the running instance, or generating a new instance.

I have tried the following, however this just prevents a secondary instance from opening, my guess is this is half of the puzzle:

Code: Select all

import fcntl, sys
pid_file = 'program.pid'
fp = open(pid_file, 'w')
try:
    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    # another instance is running
    sys.exit(0)
I'm not sure if I need to be using Daemons or what this process is even called. This is a first for me
Thanks in advance.

Re: Single instance Python script terminal arguments after s

Posted: Wed Feb 08, 2017 6:43 pm
by DougieLawson
Look at "inter process control" (ipc) and "named pipes" (FIFOs).

For a simple thing you can use kill -usr1 $(pidof daemonprocess) to send a USR1 signal to something running in the background. It's trivial to trap that with a simple signal handler.

Re: Single instance Python script terminal arguments after s

Posted: Wed Feb 08, 2017 6:48 pm
by stderr
mvdm wrote:How do I call this script that's already running from a terminal so that I can give it commands or ask it to return a value without starting another instance or stopping the already running script?
There are certainly many ways to do this including dbus and a bash script which is used by omxplayer to allow control of a running instance. You could probably quickly flesh all this out though by just having your python script poll a file you've placed on a memory based file system. Inside this file could be your commands to the running python instance. These would be changed by your control program. Hide all these behind functions so you can change it to dbus or some message passing scheme or whatever other people suggest later without any changes to the rest of your program. I would, like they did with omxplayer, probably write the controlling program in bash.