【问题标题】:cURL stream as standard input for python modulecURL 流作为 python 模块的标准输入
【发布时间】:2019-11-28 13:07:13
【问题描述】:

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

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

当 curl 自己运行时(没有“| pythonmodule.py”,它每 30 秒连续传输一次数据(它连接到带有温度和湿度传感器的 Argon IoT)完美地打印实时温度和湿度。但是当我尝试要通过 | 重定向输出,它似乎只工作一次,它不会连续运行每次提供新数据时都应该运行的 python 模块。

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

有人能解释一下这个 cURL 流是如何工作的吗?

【问题讨论】:

    标签: python curl cmd python-requests


    【解决方案1】:

    我在这里假设“似乎只工作一次”是指命令在第一次收到数据后退出。可能是您的 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
    
    

    【讨论】:

      【解决方案2】:

      关于冻结请求连续流,您可以使用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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-25
        • 2015-02-02
        • 2019-09-15
        • 1970-01-01
        • 2012-02-15
        • 2020-11-13
        • 1970-01-01
        • 2011-12-04
        相关资源
        最近更新 更多