如前所述,您可以检查 DISPLAY 环境变量:
>>> os.environ['DISPLAY']
'localhost:10.0'
如果您愿意,您实际上可以连接到显示端口以查看 sshd 正在侦听它:
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
这依赖于使用端口 6000 + 显示编号的标准 X 配置。