user9604534
user9604534

Reputation:

Passing arguments to a running python script

I have a script running on my raspberry, these script is started from a command from an php page. I’ve multiple if stetements, now I would like to pass new arguments to the script whithout stopping it. I found lots of information by passing arguments to the python script, but not if its possible while the svpcript is already running to pass new arguments. Thanks in advance!

Upvotes: 1

Views: 59

Answers (2)

JustDanyul
JustDanyul

Reputation: 14044

You need some sort of IPC mechanism really. As you are executing/updating the script from a PHP application, I'd suggest you'll look into something like ZeroMQ which supports both Python and PHP, and will allow you to do a quick and dirty Pub/Sub implementation.

The basic idea is, treat your python script as a subscriber to messages coming from the PHP application which publishes them as and when needed. To achieve this, you'll want to start your python "script" once and leave it running in the background, listening for messages on ZeroMQ. Something like this should get you going

import zmq

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")

while True:
    #  Wait for next message from from your PHP application
    message = socket.recv()
    print("Recieved a message: %s" % message)

    #  Here you should do the work you need to do in your script

    #  Once you are done, tell the PHP application you are done
    socket.send(b"Done and dusted")

Then, in your PHP application, you can use something like the following to send a message to your Python service

$context = new ZMQContext();

//  Socket to talk to server

$requester = new ZMQSocket($context, ZMQ::SOCKET_REQ);
$requester->connect("tcp://localhost:5555");

$requester->send("ALL THE PARAMS TO SEND YOU YOUR PYTHON SCRIPT");
$reply = $requester->recv();

Note, I found the above examples using a quick google search (and amended slightly for educational purposes), but they aren't tested, and purely meant to get you started. For more information, visit ZeroMQ and php-zmq

Have fun.

Upvotes: 0

Recoba20
Recoba20

Reputation: 324

The best option for me is to use a configuration file input for your script. Some simple yaml will do. Then in a separate thread you must observe the hash of the file, if it gets changed that means somebody has updated your file and you must re/adjust your inputs.

Basically you have that constant observer running all the time.

Upvotes: 0

Related Questions