¿Cómo configuro el reloj de hardware con Python en los sistemas Linux incorporados?Establecer el reloj de hardware en Python?
Respuesta
Probablemente no sea una manera sencilla que no sea hacer una llamada a os.system().
import os
os.system('hwclock --set %s' % date_str)
o utilizando el comando 'date'
import os
os.system('date -s %s' % date_str)
o si se muere por hacer algo de código C, envolviendo el sistema llama con trago ... pero creo que sería más trabajo que merece la pena.
una versión actualizada en Ubuntu 16.04:
import subprocess
import shlex
subprocess.call(shlex.split("timedatectl set-ntp false")) # May be necessary
subprocess.call(shlex.split("sudo date -s '2 OCT 2006 18:00:00'"))
subprocess.call(shlex.split("sudo hwclock -w"))
Nota importante: puede que tenga que cambiar la configuración de hora/fecha para establecer manualmente (set-ntp false
) o de lo contrario inmediatamente cambiará de nuevo a la corriente hora.
hwclock -w
ajusta el reloj de hardware basado en la hora actual del sistema (fijado por date
)
Se requiere que date
& hwclock
se ejecutan como sudo
también.
Esto usa ioctl
para configurar el reloj del hardware según lo solicitado (pero no el reloj del sistema). Evita procesos extra pero está más involucrado. Estoy usando pytz
y dateutil
para manejar las conversiones locales/utc. Siéntase libre de usar el código (licencia BSD de 3 cláusulas). Obtener el reloj con get_hwclock()
y configurarlo con set_hwclock()
...
from collections import namedtuple
from datetime import datetime
from fcntl import ioctl
import struct
from dateutil.tz import tzutc
from pytz import timezone
# From `uapi/asm-generic/ioctl.h`
_IOC_NRBITS = 8
_IOC_TYPEBITS = 8
_IOC_SIZEBITS = 14
_IOC_DIRBITS = 2
_IOC_NRMASK = (1 << _IOC_NRBITS) - 1
_IOC_TYPEMASK = (1 << _IOC_TYPEBITS) - 1
_IOC_SIZEMASK = (1 << _IOC_SIZEBITS) - 1
_IOC_DIRMASK = (1 << _IOC_DIRBITS) - 1
_IOC_NRSHIFT = 0
_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS
_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS
_IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS
_IOC_NONE = 0
_IOC_WRITE = 1
_IOC_READ = 2
def _IOC(dir, type, nr, size):
return ((dir << _IOC_DIRSHIFT) |
(type << _IOC_TYPESHIFT) |
(nr << _IOC_NRSHIFT) |
(size << _IOC_SIZESHIFT))
def _IOC_TYPECHECK(t):
return len(t)
def _IO(type, nr):
return _IOC(_IOC_NONE, type, nr, 0)
def _IOR(type, nr, size):
return _IOC(_IOC_READ, type, nr, _IOC_TYPECHECK(size))
def _IOW(type, nr, size):
return _IOC(_IOC_WRITE, type, nr, _IOC_TYPECHECK(size))
def to_utc(dtobj):
if dtobj.tzinfo is None:
dtobj = timezone("UTC").localize(
dtobj.replace(tzinfo=None) - tzlocal().utcoffset(dtobj))
return dtobj.astimezone(timezone("UTC"))
class RtcTime(namedtuple(
# man(4) rtc
"RtcTime",
"tm_sec tm_min tm_hour "
"tm_mday tm_mon tm_year "
"tm_wday tm_yday tm_isdst" # Last row is unused.
)):
_fmt = 9 * "i"
def __new__(cls, tm_sec=0, tm_min=0, tm_hour=0,
tm_mday=0, tm_mon=0, tm_year=0,
tm_wday=0, tm_yday=0, tm_isdst=0):
return super(RtcTime, cls).__new__(cls, tm_sec, tm_min, tm_hour,
tm_mday, tm_mon, tm_year,
tm_wday, tm_yday, tm_isdst)
def __str__(self):
return self.to_datetime().isoformat()
@classmethod
def from_datetime(cls, dtobj):
dt = to_utc(dtobj)
return cls(tm_sec=dt.second, tm_min=dt.minute, tm_hour=dt.hour,
tm_mday=dt.day, tm_mon=dt.month - 1, tm_year=dt.year - 1900)
def to_datetime(self):
# From `hwclock.c`.
return datetime(
year=self.tm_year + 1900, month=self.tm_mon + 1, day=self.tm_mday,
hour=self.tm_hour, minute=self.tm_min, second=self.tm_sec,
tzinfo=tzutc())
def pack(self):
return struct.pack(self._fmt, *self)
@classmethod
def unpack(cls, buffer):
return cls._make(struct.unpack(cls._fmt, buffer))
# From `uapi/linux/rtc.h`
rtc_time = RtcTime().pack()
RTC_RD_TIME = _IOR(ord("p"), 0x09, rtc_time) # 0x80247009
RTC_SET_TIME = _IOW(ord("p"), 0x0a, rtc_time) # 0x4024700a
del rtc_time
def get_hwclock(devrtc="/dev/rtc"):
with open(devrtc) as rtc:
ret = ioctl(rtc, RTC_RD_TIME, RtcTime().pack())
return RtcTime.unpack(ret).to_datetime()
def set_hwclock(dt, devrtc="/dev/rtc"):
with open(devrtc) as rtc:
ioctl(rtc, RTC_SET_TIME, RtcTime.from_datetime(dt).pack())
muchas gracias. ¿Está disponible también como biblioteca? Me dijeron que copiar y pegar es un mal patrón. – guettli
@guettli: biblioteca: no que yo sepa. En lo que a mí respecta, consideraría copiar y pegar ** dentro de una base de código ** un mal patrón. Pero copiar el código de un tercero, guardarlo en un archivo con la licencia adecuada y usarlo en el código de producción es una bestia diferente: se mantiene tan SECO como lo obtendrás ... –
- 1. ¿Cómo establece programáticamente el reloj de hardware en Linux?
- 2. ¿Está roto el reloj time.h() en mi hardware?
- 3. Implementación de señales de reloj de hardware en Linux Kernel
- 4. Programación con hardware en python
- 5. Establecer productos en Python
- 6. Establecer el punto de observación del hardware GDB/cómo configurar el punto de observación del software
- 7. ¿Hay alguna manera de acceder al hardware directamente en Python?
- 8. No se puede establecer el reloj usando SetSystemTime en Windows 8
- 9. reloj() precisión en time.h
- 10. Reloj dinámico en java
- 11. Reloj preciso en Erlang
- 12. Comprender el hardware de printf
- 13. jQuery reloj para cambios en el domo?
- 14. ¿Reloj constantemente actualizado en el prompt zsh?
- 15. Cómo usar el reloj() en C++
- 16. Obtener información de hardware en el servidor
- 17. QGL ¿Aceleración de hardware y hardware?
- 18. Establecer python virtualenv en vim
- 19. Python: diagrama polar en el sentido de las agujas del reloj
- 20. reloj de arena android
- 21. El reloj del emulador no coincide con el reloj del sistema host
- 22. numpy en hardware multinúcleo
- 23. Simulando hardware de baja precisión en Java
- 24. ¿Conocimiento de hardware en informática?
- 25. ¿Cómo establecer el tamaño inicial de un diccionario en Python?
- 26. ¿Cómo establecer el valor de forma oculta en Mechanize/Python?
- 27. Establecer virtualenv para python en el compañero de texto 2
- 28. Cómo establecer variables de entorno en Python
- 29. Simulando abrir/cerrar el teclado de hardware en el emulador
- 30. Establecer firma de función en Python
Debería ser posible hacer - siempre que el controlador RTC o RTCN está presente - a través de ioctl, en fcntl por http: //docs.python .org/library/fcntl.html y rtc (4) (o la Documentation/rtc.txt del kernel) - sin embargo, si tienes Python en el sistema, hwclock debería ser una opción fácil. –
Zdav, gracias por la ayuda. Solo una nota: estoy usando busybox, y primero necesito cambiar el reloj del sistema con "os.system ('date -s% s'% date_str)", y luego configurar el reloj hw desde el reloj del sistema con os.system ('hwclock -w). Saludos –