How to determine from a python application if X server/X forwarding is running?

Check to see that the $DISPLAY environment variable is set - if they didn't use ssh -X, it will be empty (instead of containing something like localhost:10).


As mentioned before, you can check the DISPLAY environment variable:

>>> os.environ['DISPLAY']
'localhost:10.0'

If you're so inclined, you could actually connect to the display port to see that sshd is listening on it:

import os
import socket

def tcp_connect_to_display():
        # get the display from the environment
        display_env = os.environ['DISPLAY']

        # parse the display string
        display_host, display_num = display_env.split(':')
        display_num_major, display_num_minor = display_num.split('.')

        # calculate the port number
        display_port = 6000 + int(display_num_major)

        # attempt a TCP connection
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
                sock.connect((display_host, display_port))
        except socket.error:
                return False
        finally:
            sock.close()
        return True

This relies on standard X configuration using ports 6000 + display number.


Similar to your xclock solution, I like to run xdpyinfo and see if it returns an error.