如何让 python 脚本监听来自另一个脚本的输入 [英] How to get a python script to listen for inputs from another script

查看:24
本文介绍了如何让 python 脚本监听来自另一个脚本的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我需要一个 python 脚本在一个连续循环中运行,我需要从另一个脚本传递参数到它,该脚本将在一个动作发生时运行.

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.

第二个脚本将由使用 cgi 的网站触发,我可以正常工作.连续循环应该接受cgi脚本读取的参数(然后通过串口发送信息).

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).

对于特定问题,我不能让 cgi 脚本直接通过串行发送数据,因为每次运行它都会重置串行端口.

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?

推荐答案

我会使用套接字连接.本质上,您正在编写一个非常简单的服务器,一次只需要一个连接

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() 是一个阻塞调用.它等待连接.然后你阅读连接.在这种情况下,我们假设参数的长度只有 1024 字节.然后我们对从套接字接收到的数据做一些事情并等待另一个连接.

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.

客户端可能如下所示:

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()

这样做的好处是,如果将来客户端和服务器不再在同一台机器上运行,那么只需将 "localhost" 更改为实际的 IP 地址或域即可你要打的名字.

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.

这篇关于如何让 python 脚本监听来自另一个脚本的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆