如何获取python脚本以侦听其他脚本的输入 [英] How to get a python script to listen for inputs from another script

查看:76
本文介绍了如何获取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.

客户端可能看起来像这样:

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

这方面的好处是将来如果客户端和服务器不再在同一台计算机上运行,​​则只需将 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天全站免登陆