[Linux] Solve the problem that the ssh connection terminal cannot display python images without GUI [Server]

Problem environment:

  • I personally use a windows system and connect to a remote Linux server through ssh for training. However, the GUI is not installed on the remote server, so the image is not displayed when drawing using tools such as matplotlib in Python.
  • After using 'Agg' to adjust the display of mobaxterm through other online tutorials, the vscode terminal still cannot be displayed.
  • The purpose is to make the following code run remotely under Linux through ssh and display images locally:
import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
plt.show()

Solution:

Obtained from other tutorials on the Internet, replace the backend of matplotlib with 'Tkagg', as follows:

import matplotlib
matplotlib.use('tkagg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
plt.show()
  • Running in the Vscode remote terminal: the program reports an error 'Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running', and the image is not displayed. After trying to switch the backend to 'Agg', the image is not displayed, but no error is reported.
  • Running in Mobaxterm: the image is successfully displayed without error.

Logically speaking, vscode and mobaxterm run in exactly the same terminal, and one can be used universally. So I thought, maybe the program image can be output normally, but vscode cannot find the output place. After all, the remote server does not have a graphical interface. So I call the view command:

echo $DISPLAY

It is displayed as follows in mobaxterm:

The Vscode terminal displays empty. Based on this, it can be inferred that vscode is indeed caused by not being able to find the output location, so I changed the vscode output parameters to be the same as mobaxterm:

export DISPLAY=:10.0

Now both sides are consistent.

Run it in vscode again and it will show successfully!

 

 

Guess you like

Origin blog.csdn.net/weixin_42569673/article/details/111611554