Send Message To A Python Script
Solution 1:
There are several methods to send a message from one script/app to another:
For you application a valid method is to use a named pipe. Create it using os.mkfifo, open it read-only in your python app and then wait for messages on it.
If you want your app to do another things while waiting, I reccomend you open the pipe in non-blocking mode to look for data availability without blocking your script as in following example:
import os, time
pipe_path = "/tmp/mypipe"ifnotos.path.exists(pipe_path):
os.mkfifo(pipe_path)
# Open the fifo. We need to openin non-blocking mode or it will stalls until
# someone opens it for writting
pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)
with os.fdopen(pipe_fd) as pipe:
while True:
message = pipe.read()
if message:
print("Received: '%s'" % message)
print("Doing other stuff")
time.sleep(0.5)
Then you can send messages from bash scripts using the command
echo "your message" > /tmp/mypipe
EDIT: I can not get select.select working correctly (I used it only in C programs) so I changed my recommendation to a non-bloking mode.
Solution 2:
Is not more convenient this version?
With the with
costruct inside the while true:
loop?
In this way, all other code inside the loop is executable even in case of error in the pipe file management. Eventually I can use the try:
costuct
for catching the error.
import os, time
pipe_path = "/tmp/mypipe"ifnotos.path.exists(pipe_path):
os.mkfifo(pipe_path)
# Open the fifo. We need to openin non-blocking mode or it will stalls until
# someone opens it for writting
pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)
while True:
with os.fdopen(pipe_fd) as pipe:
message = pipe.read()
if message:
print("Received: '%s'" % message)
print("Doing other stuff")
time.sleep(0.5)
Post a Comment for "Send Message To A Python Script"