Python code crashes with "cannot connect to X server" when detaching ssh+tmux session
<p>I run Python code on a remote machine (which I ssh into) and then use Tmux. The code runs fine UNTIL I disconnect from the remote machine. The whole point of my connecting via Tmux is so that the code continues to run even when I'm not connected to the remote machine. When I reconnect later, I have the error message:</p>

<pre><code>: cannot connect to X server localhost:11.0
</code></pre>

<p>Does anyone have an idea why this is happening or how I can stop it?</p>

<pre><code>cannot connect to X server localhost:11.0
</code></pre>

<p>...means that your code is trying (and failing) to connect to an X server -- a GUI environment -- presumably being forwarded over your SSH session. <code>tmux</code> provides session continuity for terminal applications; it can't emulate an X server.</p>

<hr>

<p>If you want to stop it from being able to make any GUI connection at all (and perhaps, if the software is thusly written, from even trying), unset the <code>DISPLAY</code> environment variable before running your code.</p>

<p>If this causes an error or exception, the code generating that is the same code that's causing your later error.</p>

<hr>

<p>If you want to create a <strong>fake</strong> GUI environment that will still be present, you can do that too, with Xvfb.</p>

<p>Some Linux distributions provide the <code>xvfb-run</code> wrapper, to automate setting this up for you:</p>

<pre><code># prevent any future commands in this session from connecting to your real X environment
unset DISPLAY XAUTHORITY

# run yourcode.py with a fake X environment provided by xvfb-run
xvfb-run python yourcode.py
</code></pre>

<p>By the way, see the question <a href="http://stackoverflow.com/questions/30332137/xvfb-run-unreliable-when-multiple-instances-invoked-in-parallel">xvfb-run unreliable when multiple instances invoked in parallel</a> for notes on a bug present in xvfb-run, and a fix available for same.</p>

<hr>

<p>If you want an X server you can actually detach from and reattach to later, letting you run GUI applications with similar functionality to what tmux gives you for terminal applications, consider using <a href="https://en.wikipedia.org/wiki/X11vnc" rel="nofollow">X11vnc</a> or a similar tool.</p>

python ssh tmux