【问题标题】:Piping data from a python script into a .csv or .txt file将 python 脚本中的数据通过管道传输到 .csv 或 .txt 文件中
【发布时间】:2020-04-16 17:21:07
【问题描述】:

我想监测我公寓内的空气质量(楼下的邻居是个狂热的吸烟者)。为此,我有一个与 Enviro+ 连接的 Raspberry Pie 3 Model B+。

在终端中,我可以运行测量小粒子的脚本。 python particulates.py 参见。 https://github.com/pimoroni/enviroplus-python/blob/master/examples/particulates.py

然后它运行并在终端中显示数据,如下图所示:(是的,我更擅长乐高积木,而不是编码)。

我有兴趣在文本文件或 csv 中记录数据,所以我在想是否有办法将屏幕上显示的数据直接通过管道传输到 csv 或 txt 文件中。我知道,我可能可以编写一个简单的 Python 脚本,让它变得又好又紧,但是我听到了很多关于在 Linux 中使用 pipping 的赞誉,我想尝试一下。此外,我在一个论坛上看到:

AwkSed 是您的 Shell 脚本朋友。 在 Linux 中,一切都是文件,Awk 和 Sed 可以写入/编辑文件。 每个 Linux 操作系统都附带了可怕的旧东西,并且可以正常工作。

如果您使用网络服务器,则不需要所有 x11 桌面膨胀的东西,只需一个无头 Linux 操作系统。 轻松将所有这些安装在 128MB 卡上。 Busybox 有一个网络服务器,或者您可以从一堆选项中进行选择。 我使用 shell 脚本和 Awk/Sed 即时重写 CGI/HTML 文件。

来源:https://www.raspberrypi.org/forums/viewtopic.php?t=248733

我在终端中输入了以下内容:

python Particulates.py > data.csv

我也试过了:

python Particulates.py | data.csv

数据显示在屏幕上,创建了一个 csv 文件,但两个选项的 data.csv 都是空的。如果我的理解是正确的,我需要把particles.py的stdout放到data.csv中。那里应该缺少一些东西,因为我得到的与这个 awk/sed 倡导者在论坛上宣传的相差甚远。

有什么线索可以完成这项工作吗?如果我要绘制结果,我应该使用 gnuplot 吗?我可以在同一行中使用它吗,比如在管道链中?

感谢您的帮助。

【问题讨论】:

  • 你能把你的代码放在问题中,而不仅仅是一个链接吗?
  • 听起来你在写标准错误还是什么?是的,需要minimal reproducible example 中的实际代码。
  • 这允许您登录到文件并在终端中查看数据:python Particulates.py 2>&1 | tee -a data.csv
  • 你的缓冲模式设置正确了吗?
  • 您可以在脚本中将其保存为 csv 文件,而不是将其通过管道传输到命令行。为此,您可以使用 csv 模块或 pandas

标签: python shell csv pipe raspberry-pi3


【解决方案1】:

检查库代码https://github.com/pimoroni/pms5003-python/blob/master/library/pms5003/init.py#L66 以了解每列中的值:

    def __repr__(self):
        return """
PM1.0 ug/m3 (ultrafine particles):                             {}
PM2.5 ug/m3 (combustion particles, organic compounds, metals): {}
PM10 ug/m3  (dust, pollen, mould spores):                      {}
PM1.0 ug/m3 (atmos env):                                       {}
PM2.5 ug/m3 (atmos env):                                       {}
PM10 ug/m3 (atmos env):                                        {}
>0.3um in 0.1L air:                                            {}
>0.5um in 0.1L air:                                            {}
>1.0um in 0.1L air:                                            {}
>2.5um in 0.1L air:                                            {}
>5.0um in 0.1L air:                                            {}
>10um in 0.1L air:                                             {}
""".format(*self.data[:-2], checksum=self.checksum)

并使用此数据写入 CSV:

import csv
from datetime import datetime


pms5003 = PMS5003()
time.sleep(1.0)

try:
    while True:
        try:
            with open('pms5003.csv', 'a', newline='') as csvfile:
                writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
                data = pms5003.read()  # PMS5003Data instance
                dt = datetime.now()
                writer.writerow([dt.isoformat()] + list(data.data[:-2]))
        except ReadTimeoutError:
            pms5003 = PMS5003()
except KeyboardInterrupt:
    pass

【讨论】:

  • 谢谢,这实际上是我更需要的。但是,如果我想从收集数据的时间开始,我该如何实现呢?我一直在尝试这样做至少 2 个小时,而且很好。它不工作。我无法弄清楚初始微粒.py 文件中显示时间的内容以及为什么不能将其放入 writerow 中。
  • 在通过 Python 日志记录的文件数据日志中,您可以在其中看到 %(asctime) 格式化参数,即日志时间。我添加了日期时间作为 ISO 格式的第一列。
  • 啊,我明白了,需要使用list() 进行最小化编辑才能兼容类型。
  • 省略换行符,它可能没有在您的 Python 版本中实现。您必须使用 strftime 设置您喜欢的任何格式:dt.strftime("%Y-%m-%d %H:%M:%S")
  • list(readings2.data[]) 应该是 [readings2.oxidising, readings2.reducing, readings2.nh3, readings2.adc]。可惜了,这么糟糕的设计,同一个数据读取界面中的不同格式(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2012-09-06
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多