staging.inyokaproject.org

battery.py

Status: Ungelöst | Ubuntu-Version: Nicht spezifiziert
Antworten |

Yanneck

Avatar von Yanneck

Anmeldungsdatum:
25. September 2009

Beiträge: 1192

Ich habe ein kleines Python-Skript geschrieben, das mir den aktuellen Ladestand des Akkus in Prozent ausgibt. Es war eine kleine Einsteigerübung, und ich bin offen für Kritik. Gut möglich, dass es nicht mit jeder Hardware funktioniert; ich benutze das überwiegend auf einem Netbook. Vielleicht kann es jemand brauchen. ☺

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def get_state_path():
    """Return a list of battery state paths"""
    state_files = ['charge_now', 'charge_full']
    state_dir = '/sys/class/power_supply/BAT0/'
    state_path = []
    for state in state_files:
        state_path.append(state_dir+state)
    return state_path

def get_battery_states():
    """Return battery states as tuple"""
    first_path, second_path = get_state_path()
    with open(first_path) as charge:
        charge_state = charge.read()
    with open(second_path) as full:
        full_charge = full.read()
    return charge_state, full_charge

def main():
    """Print battery state in percent to stdout 
    or exit if the battery state cannot be read
    """
    try:
        charge_state, battery_full = get_battery_states()
    except IOError, message:
        sys.exit(message)
    battery_quotient = float(charge_state) / float(battery_full) 
    print '{:.2%}'.format(battery_quotient) 

if __name__=="__main__":
    main()

Yanneck

(Themenstarter)
Avatar von Yanneck

Anmeldungsdatum:
25. September 2009

Beiträge: 1192

Ich habe versucht, es noch ein bisschen schöner zu machen (vielleicht auch verschlimmbessert). ☺

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def get_state_path():
    """Return a list of battery state paths"""
    target = ['charge_now', 'charge_full']
    directory = '/sys/class/power_supply/BAT0/'
    state_path = []
    for state_file in target:
        state_path.append(directory+state_file)
    return state_path

def read_state_file(path):
    """Read state file and return content"""
    with open(path) as content:
        state = content.read()
        return state

def main():
    """Print battery state in percent to stdout 
    or exit if the battery state cannot be read
    """
    try:
        charge = float(read_state_file(get_state_path()[0])) 
        full = float(read_state_file(get_state_path()[1]))
    except IOError, message:
        sys.exit(message)
    print '{:.2%}'.format(charge/full)

if __name__=="__main__":
    main()

Wir sehen uns. ☺

Antworten |