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

我的梦境 提交于 2019-12-09 16:20:00

问题


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

The second script will be triggered by a website using cgi, I have this working fine. The continuous loop should take in parameters read out by the cgi script (and then send info via a serial port).

For the specific problem I can't have the cgi script sending the data via serial directly as each time it runs it resets the serial port.

I can't seem to find any information on this kind of setup. Are there any methods or libraries I could look into for this or better ways of approaching it?


回答1:


I would use a socket connection. Essentially you are writing a very simple server that only takes 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. It waits for a connection. Then you do a read on the connection. In this case we are assuming the length of the parameters are only 1024 bytes. Then we do something with the data we received from the socket and wait for another connection.

The client could 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 nice thing about this is that in the future if the client and server are no longer running on the same machine then it's a simple matter of changing "localhost" to the actual ip address or domain name you are going to hit.




回答2:


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

In python this can be done by sockets and signals.

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



来源:https://stackoverflow.com/questions/18616226/how-to-get-a-python-script-to-listen-for-inputs-from-another-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!