如何在docker集装箱中使用matplotlib.pyplot?

我在一个名为deep的docker镜像中对Python进行了一定的设置。 我曾经运行python代码

 docker run --rm -it -v "$PWD":/app -w /app deep python some-code.py 

有关信息, -v-w选项将当前path中的本地文件链接到容器。

但是,我不能使用matplotlib.pyplot 。 假设test.py

 import matplotlib.pyplot as plt plt.plot([1,2], [3,4]) plt.show() 

我得到这个错误。

 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3147, in plot ax = gca() File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 928, in gca return gcf().gca(**kwargs) File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 578, in gcf return figure() File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 527, in figure **kwargs) File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 84, in new_figure_manager return new_figure_manager_given_figure(num, figure) File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 92, in new_figure_manager_given_figure window = Tk.Tk() File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1818, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable 

通过解决schemesearch, 我只有一个解决scheme 。 我想如果我能做到

 $ xauth list xxxx/unix:0 yyyy 5nsk3hd # copy this list $ docker run --rm -it -v "$PWD":/app -w /app \ --net=host -e DISPLAY \ -v /tmp/.X11-unix:/tmp/.X11-unix \ deep bash inside-container$ xauth add xxxx/unix:0 yyyy 5nsk3hd # paste the list inside-container$ python test.py # now the plot works!! 

我的问题是,而不是所有那些启动bash ,设置xauth ,并容器中运行Python, 我可以做这样的设置与docker run以便我可以运行在容器外的代码

我试过了

 docker run --rm -it -v "$PWD":/app -w /app \ --net=host -e DISPLAY \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e "xauth add xxxx/unix:0 yyyy 5nsk3hd" \ deep python test.py 

使用--entry参数,但它没有工作。 请帮忙。

有趣的是,我在ROS社区find了相当不错的解决scheme。 http://wiki.ros.org/docker/Tutorials/GUI

对于我的问题,我最后的select是本教程中的第二种方法:

 docker run --rm -it \ --user=$(id -u) \ --env="DISPLAY" \ --workdir=/app \ --volume="$PWD":/app \ --volume="/etc/group:/etc/group:ro" \ --volume="/etc/passwd:/etc/passwd:ro" \ --volume="/etc/shadow:/etc/shadow:ro" \ --volume="/etc/sudoers.d:/etc/sudoers.d:ro" \ --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \ deepaul python test.python