Can Julia detect that it is running in headless machine?

Hi,

I have a small project that I am running on my computer, as well as on a remote server. On my laptop, I typically use Plots.jl or Makie.jl for visualization, but on the server I am typically interested in saving my results as a txt or jld2 file.

Now, I am wondering if there is an is_headless() function somewhere that would tell you whether you are in headless machine/environment or not. This will save me some time since I do not have to plot anything on the server, and I do not have to rewrite my code.

Here’s a simple example of what I am imagining is_headless() would do

f(x)=sin(x) #example 
x=range(0,10,1000)
y=f.(x)

if is_headless() #no gui 
    using DelimitedFiles
    writedlm("y.txt",y)

else #there is a gui
    using Plots
    plt=plot(x,y)
    savefig(plt,"plot.png") #or display(plt)
end

For Linux, try this:

is_headless() = !(ENV["XDG_SESSION_TYPE"] in ("wayland", "x11"))

Explanation: the function returns false if you’re running either Wayland or X11, the two common graphical systems on Linux.

Neat! It worked on my Arch and Debian 12 servers. However, I got ERROR: KeyError: key "XDG_SESSION_TYPE" not found when running it on Ubuntu 22.04 and RHEL 8.10 (all using the latest v1.10.5)

For now, it seems like this works fine

is_headless() = !(haskey(ENV,"XDG_SESSION_TYPE") && (ENV["XDG_SESSION_TYPE"] in ("wayland", "x11")))

Having said that, I am curious as to why XDG_SESSION_TYPE is not an environment variable on some systems.

How does this work?

is_headless() = !Sys.iswindows() && isempty(get(ENV, "DISPLAY", ""))
4 Likes

Thanks! This worked flawlessly.