cURL 流作为 python 模块的标准输入



我正在尝试通过CMD中的以下行将cURL的输出通过管道传输到Python模块的输入:

curl https://api.particle.io/v1/devices/e00fce68515bfa5f850de016/events?access_token=ae40788c6dba577144249fec95afdeadb18e6bec | pythonmodule.py

当curl自行运行时(没有"| pythonmodule.py"(,它每30秒连续传输一次数据(它连接到带有温度和湿度传感器的氩气物联网(,完美地打印实时温度和湿度。但是当我尝试通过 |它似乎只工作一次,它不会连续运行 python模块,每次都应该在提供新数据的地方

运行。我尝试使用库requests.get()但由于它是一个连续的流,它似乎冻结在get()上。

有人可以解释一下这个 cURL 流的实际工作原理吗?

关于冻结请求连续流,您可以使用requests中的Body Content Workflow以避免等待整个内容一次下载:

with requests.get('your_url', stream=True) as response:
for line in response.iter_lines(decode_unicode=True):
if line:
print(line)

输出:

:ok
event: SensorVals
data: {"data":"{humidity: 30.000000, temp: 24.000000}","ttl":60,"published_at":"2019-11-28T13:53:04.592Z","coreid":"e00fce68515bfa5f850de016"}
event: SensorVals
data: {"data":"{humidity: 29.000000, temp: 24.000000}","ttl":60,"published_at":"2019-11-28T13:53:34.604Z","coreid":"e00fce68515bfa5f850de016"}
...

https://requests.readthedocs.io/en/master/user/advanced/#body-content-workflow

我在这里假设"似乎只工作一次"的意思是命令在第一次收到数据后退出。可能是您的 python 脚本在第一行之后停止读取。

循环访问标准可能会解决您的问题:

import sys
for n, line in enumerate(sys.stdin):
if line.strip() != "":
print(n, line)

使用如下命令:

curl -sN https://api.particle.io/v1/devices/e00fce68515bfa5f850de016/events?access_token=ae40788c6dba577144249fec95afdeadb18e6bec | python blah.py

将导致:

0 :ok
3 event: SensorVals
4 data: {"data":"{humidity: 30.000000, temp: 24.000000}","ttl":60,"published_at":"2019-11-28T13:50:34.459Z","coreid":"e00fce68515bfa5f850de016"}
9 event: SensorVals
10 data: {"data":"{humidity: 30.000000, temp: 24.000000}","ttl":60,"published_at":"2019-11-28T13:51:04.608Z","coreid":"e00fce68515bfa5f850de016"}
^CTraceback (most recent call last):
File "blah.py", line 3, in <module>
for n, line in enumerate(sys.stdin):
KeyboardInterrupt

最新更新