Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
mailcap Namespace Reference

Functions

def getcaps
 
def listmailcapfiles
 
def readmailcapfile
 
def parseline
 
def parsefield
 
def findmatch
 
def lookup
 
def subst
 
def findparam
 
def test
 
def show
 

Variables

list __all__ = ["getcaps","findmatch"]
 

Detailed Description

Mailcap file handling.  See RFC 1524.

Function Documentation

def mailcap.findmatch (   caps,
  MIMEtype,
  key = 'view',
  filename = "/dev/null",
  plist = [] 
)
Find a match for a mailcap entry.

Return a tuple containing the command line, and the mailcap entry
used; (None, None) if no match is found.  This may invoke the
'test' command of several matching entries before deciding which
entry to use.

Definition at line 138 of file mailcap.py.

References lookup(), and subst().

139 def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
140  """Find a match for a mailcap entry.
141 
142  Return a tuple containing the command line, and the mailcap entry
143  used; (None, None) if no match is found. This may invoke the
144  'test' command of several matching entries before deciding which
145  entry to use.
146 
147  """
148  entries = lookup(caps, MIMEtype, key)
149  # XXX This code should somehow check for the needsterminal flag.
150  for e in entries:
151  if e.has_key('test'):
152  test = subst(e['test'], filename, plist)
153  if test and os.system(test) != 0:
154  continue
155  command = subst(e[key], MIMEtype, filename, plist)
156  return command, e
157  return None, None
def mailcap.findparam (   name,
  plist 
)

Definition at line 202 of file mailcap.py.

References string.lower().

203 def findparam(name, plist):
204  name = name.lower() + '='
205  n = len(name)
206  for p in plist:
207  if p[:n].lower() == name:
208  return p[n:]
209  return ''
210 
211 
212 # Part 4: test program.
def mailcap.getcaps ( )
Return a dictionary containing the mailcap database.

The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
to a list of dictionaries corresponding to mailcap entries.  The list
collects all the entries for that MIME type from all available mailcap
files.  Each dictionary contains key-value pairs for that MIME type,
where the viewing command is stored with the key "view".

Definition at line 9 of file mailcap.py.

References listmailcapfiles(), aifc.open(), and readmailcapfile().

9 
10 def getcaps():
11  """Return a dictionary containing the mailcap database.
12 
13  The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
14  to a list of dictionaries corresponding to mailcap entries. The list
15  collects all the entries for that MIME type from all available mailcap
16  files. Each dictionary contains key-value pairs for that MIME type,
17  where the viewing command is stored with the key "view".
18 
19  """
20  caps = {}
21  for mailcap in listmailcapfiles():
22  try:
23  fp = open(mailcap, 'r')
24  except IOError:
25  continue
26  morecaps = readmailcapfile(fp)
27  fp.close()
28  for key in morecaps.keys():
29  if not caps.has_key(key):
30  caps[key] = morecaps[key]
31  else:
32  caps[key] = caps[key] + morecaps[key]
33  return caps
def mailcap.listmailcapfiles ( )
Return a list of all mailcap files found on the system.

Definition at line 34 of file mailcap.py.

34 
35 def listmailcapfiles():
36  """Return a list of all mailcap files found on the system."""
37  # XXX Actually, this is Unix-specific
38  if os.environ.has_key('MAILCAPS'):
39  str = os.environ['MAILCAPS']
40  mailcaps = str.split(':')
41  else:
42  if os.environ.has_key('HOME'):
43  home = os.environ['HOME']
44  else:
45  # Don't bother with getpwuid()
46  home = '.' # Last resort
47  mailcaps = [home + '/.mailcap', '/etc/mailcap',
48  '/usr/etc/mailcap', '/usr/local/etc/mailcap']
49  return mailcaps
50 
51 
52 # Part 2: the parser.
def mailcap.lookup (   caps,
  MIMEtype,
  key = None 
)

Definition at line 158 of file mailcap.py.

References fnmatch.filter().

159 def lookup(caps, MIMEtype, key=None):
160  entries = []
161  if caps.has_key(MIMEtype):
162  entries = entries + caps[MIMEtype]
163  MIMEtypes = MIMEtype.split('/')
164  MIMEtype = MIMEtypes[0] + '/*'
165  if caps.has_key(MIMEtype):
166  entries = entries + caps[MIMEtype]
167  if key is not None:
168  entries = filter(lambda e, key=key: e.has_key(key), entries)
169  return entries
def mailcap.parsefield (   line,
  i,
  n 
)
Separate one key-value pair in a mailcap entry.

Definition at line 122 of file mailcap.py.

References string.strip().

123 def parsefield(line, i, n):
124  """Separate one key-value pair in a mailcap entry."""
125  start = i
126  while i < n:
127  c = line[i]
128  if c == ';':
129  break
130  elif c == '\\':
131  i = i+2
132  else:
133  i = i+1
134  return line[start:i].strip(), i
135 
136 
137 # Part 3: using the database.
def mailcap.parseline (   line)
Parse one entry in a mailcap file and return a dictionary.

The viewing command is stored as the value with the key "view",
and the rest of the fields produce key-value pairs in the dict.

Definition at line 91 of file mailcap.py.

References parsefield(), and string.strip().

91 
92 def parseline(line):
93  """Parse one entry in a mailcap file and return a dictionary.
94 
95  The viewing command is stored as the value with the key "view",
96  and the rest of the fields produce key-value pairs in the dict.
97  """
98  fields = []
99  i, n = 0, len(line)
100  while i < n:
101  field, i = parsefield(line, i, n)
102  fields.append(field)
103  i = i+1 # Skip semicolon
104  if len(fields) < 2:
105  return None, None
106  key, view, rest = fields[0], fields[1], fields[2:]
107  fields = {'view': view}
108  for field in rest:
109  i = field.find('=')
110  if i < 0:
111  fkey = field
112  fvalue = ""
113  else:
114  fkey = field[:i].strip()
115  fvalue = field[i+1:].strip()
116  if fields.has_key(fkey):
117  # Ignore it
118  pass
119  else:
120  fields[fkey] = fvalue
121  return key, fields
def mailcap.readmailcapfile (   fp)
Read a mailcap file and return a dictionary keyed by MIME type.

Each MIME type is mapped to an entry consisting of a list of
dictionaries; the list will contain more than one such dictionary
if a given MIME type appears more than once in the mailcap file.
Each dictionary contains key-value pairs for that MIME type, where
the viewing command is stored with the key "view".

Definition at line 53 of file mailcap.py.

References reconvert.append, dospath.join(), string.lower(), parseline(), and string.strip().

53 
54 def readmailcapfile(fp):
55  """Read a mailcap file and return a dictionary keyed by MIME type.
56 
57  Each MIME type is mapped to an entry consisting of a list of
58  dictionaries; the list will contain more than one such dictionary
59  if a given MIME type appears more than once in the mailcap file.
60  Each dictionary contains key-value pairs for that MIME type, where
61  the viewing command is stored with the key "view".
62  """
63  caps = {}
64  while 1:
65  line = fp.readline()
66  if not line: break
67  # Ignore comments and blank lines
68  if line[0] == '#' or line.strip() == '':
69  continue
70  nextline = line
71  # Join continuation lines
72  while nextline[-2:] == '\\\n':
73  nextline = fp.readline()
74  if not nextline: nextline = '\n'
75  line = line[:-2] + nextline
76  # Parse the line
77  key, fields = parseline(line)
78  if not (key and fields):
79  continue
80  # Normalize the key
81  types = key.split('/')
82  for j in range(len(types)):
83  types[j] = types[j].strip()
84  key = '/'.join(types).lower()
85  # Update the database
86  if caps.has_key(key):
87  caps[key].append(fields)
88  else:
89  caps[key] = [fields]
90  return caps
def mailcap.show (   caps)

Definition at line 235 of file mailcap.py.

References getcaps(), listmailcapfiles(), and test().

236 def show(caps):
237  print "Mailcap files:"
238  for fn in listmailcapfiles(): print "\t" + fn
239  print
240  if not caps: caps = getcaps()
241  print "Mailcap entries:"
242  print
243  ckeys = caps.keys()
244  ckeys.sort()
245  for type in ckeys:
246  print type
247  entries = caps[type]
248  for e in entries:
249  keys = e.keys()
250  keys.sort()
251  for k in keys:
252  print " %-15s" % k, e[k]
253  print
def mailcap.subst (   field,
  MIMEtype,
  filename,
  plist = [] 
)

Definition at line 170 of file mailcap.py.

References findparam().

171 def subst(field, MIMEtype, filename, plist=[]):
172  # XXX Actually, this is Unix-specific
173  res = ''
174  i, n = 0, len(field)
175  while i < n:
176  c = field[i]; i = i+1
177  if c != '%':
178  if c == '\\':
179  c = field[i:i+1]; i = i+1
180  res = res + c
181  else:
182  c = field[i]; i = i+1
183  if c == '%':
184  res = res + c
185  elif c == 's':
186  res = res + filename
187  elif c == 't':
188  res = res + MIMEtype
189  elif c == '{':
190  start = i
191  while i < n and field[i] != '}':
192  i = i+1
193  name = field[start:i]
194  i = i+1
195  res = res + findparam(name, plist)
196  # XXX To do:
197  # %n == number of parts if type is multipart/*
198  # %F == list of alternating type and filename for parts
199  else:
200  res = res + '%' + c
201  return res
def mailcap.test ( )

Definition at line 213 of file mailcap.py.

References findmatch(), getcaps(), and show().

214 def test():
215  import sys
216  caps = getcaps()
217  if not sys.argv[1:]:
218  show(caps)
219  return
220  for i in range(1, len(sys.argv), 2):
221  args = sys.argv[i:i+2]
222  if len(args) < 2:
223  print "usage: mailcap [MIMEtype file] ..."
224  return
225  MIMEtype = args[0]
226  file = args[1]
227  command, e = findmatch(caps, MIMEtype, 'view', file)
228  if not command:
229  print "No viewer found for", type
230  else:
231  print "Executing:", command
232  sts = os.system(command)
233  if sts:
234  print "Exit status:", sts

Variable Documentation

list __all__ = ["getcaps","findmatch"]

Definition at line 5 of file mailcap.py.