How to get a python script to listen for inputs from another script

I have a situation where I need one python script to work in a continuous loop, and I need to pass parameters to it from another script, which will be run when an action occurs.

The second script will be launched by the website using cgi, I have it ok. A continuous loop should take the parameters read by the cgi script (and then send information via the serial port).

For a specific problem, I cannot force the cgi script to send data via the serial interface, since every time it starts, it resets the serial port.

I can't seem to find any information about this setting. Are there any methods or libraries that I could study for this or better ways to approximate it?

+6
source share
2 answers

I would use a socket connection. Essentially, you are writing a very simple server that only accepts one connection at a time.

import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("localhost", 9988)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024) conn.close() my_function_that_handles_data(data) 

s.accept() is a blocking call. He is waiting for a connection. Then you read about the connection. In this case, we assume that the length of the parameters is only 1024 bytes. Then we do something with the data received from the socket and expect another connection.

A client might look like this:

 import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", 9988)) s.sendall('My parameters that I want to share with the server') s.close() 

The best part is that in the future, if the client and the server will no longer work on the same machine, then simply changing "localhost" to the actual IP address or domain name that you are about to hit.

+8
source

The general concept of what you are describing is called Inter-Process Communication ( Python IPC ).

In python, sockets and signals can do this.

There are also higher-level interfaces built on top of / using sockets; asyncore and asynchat .

+1
source

Source: https://habr.com/ru/post/953162/


All Articles