Linux环境下Python Pillow库Img.show()调用报错求助
问题:Linux下Pillow的im.show()报错TypeError
我在Linux环境下使用Python的Pillow库编写代码,期望通过图片查看器打开图片,代码如下:
from PIL import Image im = Image.open('hi.png') im.show()
但运行时出现报错,错误信息如下:
Traceback (most recent call last): File "/home/kd/Documents/python/modules/pillow_image.py", line 3, in <module> im.show() File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2146, in show _show(self, title=title, command=command) File "/usr/lib/python3/dist-packages/PIL/Image.py", line 3085, in _show _showxv(image, **options) File "/usr/lib/python3/dist-packages/PIL/Image.py", line 3091, in _showxv ImageShow.show(image, title, **options) File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 47, in show if viewer.show(image, title=title, **options): File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 67, in show return self.show_image(image, **options) File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 87, in show_image return self.show_file(self.save_image(image), **options) File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 168, in show_file subprocess.Popen(args) File "/usr/lib/python3.8/subprocess.py", line 858, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.8/subprocess.py", line 1639, in _execute_child self.pid = _posixsubprocess.fork_exec( TypeError: expected str, bytes or os.PathLike object, not NoneType [Finished in 178ms with exit code 1]
解决办法
这个错误是因为Pillow无法找到系统中的图片查看器程序,导致调用subprocess时传入了None值。可以通过以下方式解决:
安装系统图片查看器
根据你的Linux发行版选择对应命令安装:- Debian/Ubuntu系:
sudo apt update && sudo apt install eog - Fedora/RHEL系:
sudo dnf install eog - Arch系:
sudo pacman -S eog
也可以选择轻量查看器feh:
# Debian/Ubuntu sudo apt install feh # Fedora sudo dnf install feh # Arch sudo pacman -S feh- Debian/Ubuntu系:
手动指定查看器命令
修改代码,在show()方法中直接指定要用的查看器:from PIL import Image im = Image.open('hi.png') # 用eog打开 im.show(command='eog') # 或者用feh # im.show(command='feh')设置环境变量指定默认查看器
临时设置(当前终端有效):export PIL_IMAGE_VIEWER=eog运行脚本前执行上述命令即可。若要永久生效,可将该命令添加到
~/.bashrc或~/.zshrc文件中。
也可以在Python脚本内直接设置:import os from PIL import Image os.environ['PIL_IMAGE_VIEWER'] = 'eog' im = Image.open('hi.png') im.show()
内容的提问来源于stack exchange,提问作者Nirjhar Das
相关产品推荐
相关产品推荐

