question: Add the Question.multimedia attribute
[quizzer.git] / quizzer / ui / util.py
1 # Copyright
2
3 """View files using mailcap-specified commands
4 """
5
6 import logging as _logging
7 import mailcap as _mailcap
8 import mimetypes as _mimetypes
9 import shlex as _shlex
10 if not hasattr(_shlex, 'quote'):  # Python < 3.3
11     import pipes as _pipes
12     _shlex.quote = _pipes.quote
13 import subprocess as _subprocess
14
15
16 _LOG = _logging.getLogger(__name__)
17 _CAPS = _mailcap.getcaps()
18
19
20 def mailcap_view(path, content_type=None, background=False):
21     if content_type is None:
22         content_type,encoding = _mimetypes.guess_type(path)
23         if content_type is None:
24             return 1
25         _LOG.debug('guessed {} for {}'.format(content_type, path))
26     match = _mailcap.findmatch(
27         _CAPS, content_type, filename=_shlex.quote(path))
28     if match[0] is None:
29         _LOG.warn('no mailcap viewer found for {}'.format(content_type))
30         raise NotImplementedError(content_type)
31     _LOG.debug('view {} with: {}'.format(path, match[0]))
32     process = _subprocess.Popen(match[0], shell=True)
33     if background:
34         return process
35     return process.wait()