Systemd服务未将python脚本写入文件,从cli执行时python脚本正常运行

时间:2019-03-26 16:25:43

标签: python raspberry-pi systemd

使用覆盆子pi零w,设置脚本来监视bme280传感器,并将其值写入文件。当从命令行启动脚本时,当通过systemd启动脚本时,此文件未写入,这非常有用。请在下面的脚本和systemd服务中找到。

已将Standard输出设置为没有运气的绝对路径,并且python脚本write指令也设置为绝对路径。

系统服务:

[Unit]
Description=bme280 sensor log startup
After=network.target

[Service]
ExecStart=/usr/bin/python3 -u /home/pi/bme.py
WorkingDirectory=/home/pi
StandardOutput=file:/home/pi/senselog.csv
StandardError=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

python脚本:

import time
from time import strftime
import board
import busio
import adafruit_bme280

# Create library object using our Bus I2C port
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c,address=0x76)

# OR create library object using our Bus SPI port
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
#bme_cs = digitalio.DigitalInOut(board.D10)
#bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)

# change this to match the location's pressure (hPa) at sea level
bme280.sea_level_pressure = 1013.25

with open("/home/pi/senselog.csv", "a") as log:
    while True:

        temp_h = bme280.temperature
        humidity = bme280.humidity
        pressure = bme280.pressure
        log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str([temp_h,humidity,pressure])))
        time.sleep(60)

如果我删除了senselog.csv文件,则在引导时systemd服务将创建文件新鲜但没有数据的文件,请提供任何帮助。

2 个答案:

答案 0 :(得分:0)

file的{​​{1}}属性仅在StandardOutput 236版本中可用。您拥有哪个版本?

systemd

如果版本低于236,并且您不希望升级,只需将pi@wifi-relay:~ $ systemd --version systemd 232 +PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN 行更新为:

ExecStart

...然后将/usr/bin/python3 -u /home/pi/bme.py >1 /home/pi/senselog.csv 行放回默认行。

答案 1 :(得分:0)

因此解决方案是在python脚本中实际调用要写入的文件上的.close(),然后systemd服务按预期工作。对这个线程大喊:https://askubuntu.com/questions/83549/python-script-wont-write-data-when-ran-from-cron最后一个答案= f.close()

和工作脚本文件:

from time import strftime
import board
import busio
import adafruit_bme280

# Create library object using our Bus I2C port
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c,address=0x76)

# OR create library object using our Bus SPI port
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
#bme_cs = digitalio.DigitalInOut(board.D10)
#bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)

# change this to match the location's pressure (hPa) at sea level
bme280.sea_level_pressure = 1013.25

with open("/home/pi/senselog.csv", "w") as log:
    while True:

        temp_h = bme280.temperature
        humidity = bme280.humidity
        pressure = bme280.pressure
        log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str([temp_h,humidity,pressure])))
        log.close()
        time.sleep(60) ```