使用Python更新存储的信息

时间:2018-09-30 17:34:02

标签: python linux lcd

我正在使用pi设备,将其ip显示在液晶屏上。该代码大部分都起作用。通过linux(cron守护程序)中的自动化过程来重复该过程。这足够好,但是重复脚本时,ip信息不会更新。我在网上查看过有关如何清除存储的字符串的信息,但是我被卡住了。请有人帮忙。

这是代码的主要部分。

#!/usr/bin/python
import time
import sys
import Adafruit_CharLCD as LCD

from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime

cmd = "ip -4 addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1"

cmd2 = "ip -4 addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1"

def run_cmd(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()[0]
    return output

lcd_rs        = 25  
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 17
lcd_d6        = 18
lcd_d7        = 22
lcd_backlight = 4

lcd_columns = 16
lcd_rows    = 2


lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                       lcd_columns, lcd_rows, lcd_backlight)

# Display Wlan0 IP
time.sleep(2.0)
lcd.clear()
lcd.message('Wlan0')
time.sleep(2.0)

lcd.clear()
ipaddr = run_cmd(cmd)
lcd.message(datetime.now().strftime('%b %d  %H:%M:%S\n'))
lcd.message('IP %s' % (ipaddr))
sleep(2)

# Display Eth0 IP
time.sleep(2.0)
lcd.clear()
lcd.message('Eth0')
time.sleep(2.0)
lcd.clear()
ipaddr = run_cmd(cmd2)
lcd.message(datetime.now().strftime('%b %d  %H:%M:%S\n'))
lcd.message('IP %s' % (ipaddr))
sleep(2)
time.sleep(5.0)


lcd.clear()
lcd.blink(True)
lcd.message('Clearing\nCache')
sys.stdout.flush()
time.sleep(5.0)

1 个答案:

答案 0 :(得分:0)

最好创建一个将信息发送到设备的函数。另外,您需要创建函数get_cmd(interface)以获得给定接口的ip地址。您两次请求相同的cmd,而我想,您只能获得一个接口的信息。

import time
import sys
import Adafruit_CharLCD as LCD

from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import Popen, PIPE
from time import sleep, strftime
from datetime import datetime

cmd = "ip -4 addr show {interface} | grep inet | awk '{{print $2}}' | cut -d/ -f1"


def run_cmd(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()[0]
    return output


def get_cmd(interface):
    return cmd.format(interface=interface)


def lcd_show(lcd, interface):
    cmd = get_cmd(interface)
    ipaddr = run_cmd(cmd)

    lcd.clear()
    lcd.message(interface)
    time.sleep(2)

    lcd.clear()
    lcd.message(datetime.now().strftime('%b %d  %H:%M:%S\n'))
    lcd.message('IP %s' % (ipaddr))
    time.sleep(2)


lcd_rs        = 25  
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 17
lcd_d6        = 18
lcd_d7        = 22
lcd_backlight = 4

lcd_columns = 16
lcd_rows    = 2
lcd = LCD.Adafruit_CharLCD(
    lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
    lcd_columns, lcd_rows, lcd_backlight)

time.sleep(2)
try:
    while True
        lcd_show(lcd, 'Wlan0')
        lcd_show(lcd, 'Eth0')
        sleep(5)
except KeyboardInterrupt:
    lcd.clear()
    lcd.blink(True)
    lcd.message('Clearing\nCache')