Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Open multiple images in default image viewer

I am using PIL to open a single image in the default image viewer:

from PIL import Image
img = Image.open('example.jpg')
img.show() 

Does any Python module contain a function enabling opening multiple images in the current system's default image viewer? For instance when on OS X, Preview.app should open with the list of images in the sidebar. From the command line this is no problem at all:

$ open my_picture_number_*

Use case is that users should just be able to explore a few dozen images.

like image 860
kapibarasama Avatar asked Feb 09 '16 23:02

kapibarasama


2 Answers

Use subprocess.run to run the operating system's default image viewing app. subprocess.run works a lot like a command line. You just need to know what the command is for the operating system you're on. For windows, "explorer" will do; for OS X, as you point out, it's "open." I'm not sure what it is for Linux, maybe "eog"?

So, your code would look like this:

import sys
import subprocess

def openImage(path):
    imageViewerFromCommandLine = {'linux':'xdg-open',
                                  'win32':'explorer',
                                  'darwin':'open'}[sys.platform]
    subprocess.run([imageViewerFromCommandLine, path])
like image 56
jgfооt Avatar answered Oct 31 '22 14:10

jgfооt


I've tried to use @jgfoot's answer, which worked, but made my program hang after the viewer was launched. I've solved this issue by using subprocess.Popen instead, like this:

import sys
import subprocess

def openImage(path):
    imageViewerFromCommandLine = {'linux':'xdg-open',
                                  'win32':'explorer',
                                  'darwin':'open'}[sys.platform]
    subprocess.Popen([imageViewerFromCommandLine, path])
like image 20
TheTomer Avatar answered Oct 31 '22 16:10

TheTomer