3

The following code was scrounged up on the Internet years ago and works quite well in python2. It supplies the current idle time on the X server.

import ctypes, os, subprocess
class XScreenSaverInfo( ctypes.Structure ):
    _fields_ = [("window",     ctypes.c_ulong), ("state",      ctypes.c_int), ("kind",       ctypes.c_int), ("since",      ctypes.c_ulong), ("idle",       ctypes.c_ulong), ("event_mask", ctypes.c_ulong)]

xlib = ctypes.cdll.LoadLibrary("libX11.so.6")
xss = ctypes.cdll.LoadLibrary("libXss.so.1")
display = xlib.XOpenDisplay(os.environ["DISPLAY"])
xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)
xssinfo = xss.XScreenSaverAllocInfo()

 xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), xssinfo)

 xssinfo.contents.idle

I can throw this into a python2.7.10 shell and get what I want. However, doing the same on a python3.4.3 shell kicks me out with a segmentation fault in this line

xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), xssinfo)

Is my py3 environment broken? Does py3 do something differently?

0

1 Answer 1

7

There was no significant change in Python 3's ctypes module. However in Python3 os.environ values are unicode strings, contrary to the byte strings of python2 and this causes the segmentation fault. So changing:

display = xlib.XOpenDisplay(os.environ["DISPLAY"])

To:

display = xlib.XOpenDisplay(bytes(os.environ["DISPLAY"], 'ascii'))

Fixes the segmentation fault.

If you want to have code that works both in python 2 and 3 you want to use the encode method:

display = xlib.XOpenDisplay(os.environ["DISPLAY"].encode('ascii'))
5
  • Thanks, this was indeed the case!
    – 1N4001
    Jun 20, 2016 at 10:36
  • @Bakuriu Still segfaults for me at xlib.XDefaultRootWindow(display)
    – cass
    Jan 22, 2017 at 21:22
  • I suspect it has to do with gtk, as it is working on KDE for me
    – cass
    Jan 22, 2017 at 21:30
  • @cass That's probably an other unrelated issue. I suggest you open a new question, specifying precisely your OS configuration and how it affects the behaviour of the program.
    – Bakuriu
    Jan 23, 2017 at 6:50
  • @cass you ever solve that other segfault?
    – 1N4001
    Aug 5, 2023 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.