Back to index

python3.2  3.2.2
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.

00138 
00139 def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
00140     """Find a match for a mailcap entry.
00141 
00142     Return a tuple containing the command line, and the mailcap entry
00143     used; (None, None) if no match is found.  This may invoke the
00144     'test' command of several matching entries before deciding which
00145     entry to use.
00146 
00147     """
00148     entries = lookup(caps, MIMEtype, key)
00149     # XXX This code should somehow check for the needsterminal flag.
00150     for e in entries:
00151         if 'test' in e:
00152             test = subst(e['test'], filename, plist)
00153             if test and os.system(test) != 0:
00154                 continue
00155         command = subst(e[key], MIMEtype, filename, plist)
00156         return command, e
00157     return None, None

Here is the call graph for this function:

Here is the caller graph for this function:

def mailcap.findparam (   name,
  plist 
)

Definition at line 202 of file mailcap.py.

00202 
00203 def findparam(name, plist):
00204     name = name.lower() + '='
00205     n = len(name)
00206     for p in plist:
00207         if p[:n].lower() == name:
00208             return p[n:]
00209     return ''
00210 
00211 
00212 # Part 4: test program.

Here is the caller graph for this function:

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.

00009 
00010 def getcaps():
00011     """Return a dictionary containing the mailcap database.
00012 
00013     The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
00014     to a list of dictionaries corresponding to mailcap entries.  The list
00015     collects all the entries for that MIME type from all available mailcap
00016     files.  Each dictionary contains key-value pairs for that MIME type,
00017     where the viewing command is stored with the key "view".
00018 
00019     """
00020     caps = {}
00021     for mailcap in listmailcapfiles():
00022         try:
00023             fp = open(mailcap, 'r')
00024         except IOError:
00025             continue
00026         morecaps = readmailcapfile(fp)
00027         fp.close()
00028         for key, value in morecaps.items():
00029             if not key in caps:
00030                 caps[key] = value
00031             else:
00032                 caps[key] = caps[key] + value
00033     return caps

Here is the call graph for this function:

Here is the caller graph for this function:

Return a list of all mailcap files found on the system.

Definition at line 34 of file mailcap.py.

00034 
00035 def listmailcapfiles():
00036     """Return a list of all mailcap files found on the system."""
00037     # XXX Actually, this is Unix-specific
00038     if 'MAILCAPS' in os.environ:
00039         str = os.environ['MAILCAPS']
00040         mailcaps = str.split(':')
00041     else:
00042         if 'HOME' in os.environ:
00043             home = os.environ['HOME']
00044         else:
00045             # Don't bother with getpwuid()
00046             home = '.' # Last resort
00047         mailcaps = [home + '/.mailcap', '/etc/mailcap',
00048                 '/usr/etc/mailcap', '/usr/local/etc/mailcap']
00049     return mailcaps
00050 
00051 
00052 # Part 2: the parser.

Here is the caller graph for this function:

def mailcap.lookup (   caps,
  MIMEtype,
  key = None 
)

Definition at line 158 of file mailcap.py.

00158 
00159 def lookup(caps, MIMEtype, key=None):
00160     entries = []
00161     if MIMEtype in caps:
00162         entries = entries + caps[MIMEtype]
00163     MIMEtypes = MIMEtype.split('/')
00164     MIMEtype = MIMEtypes[0] + '/*'
00165     if MIMEtype in caps:
00166         entries = entries + caps[MIMEtype]
00167     if key is not None:
00168         entries = [e for e in entries if key in e]
00169     return entries

Here is the caller graph for this function:

def mailcap.parsefield (   line,
  i,
  n 
)
Separate one key-value pair in a mailcap entry.

Definition at line 122 of file mailcap.py.

00122 
00123 def parsefield(line, i, n):
00124     """Separate one key-value pair in a mailcap entry."""
00125     start = i
00126     while i < n:
00127         c = line[i]
00128         if c == ';':
00129             break
00130         elif c == '\\':
00131             i = i+2
00132         else:
00133             i = i+1
00134     return line[start:i].strip(), i
00135 
00136 
00137 # Part 3: using the database.

Here is the caller graph for this function:

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.

00091 
00092 def parseline(line):
00093     """Parse one entry in a mailcap file and return a dictionary.
00094 
00095     The viewing command is stored as the value with the key "view",
00096     and the rest of the fields produce key-value pairs in the dict.
00097     """
00098     fields = []
00099     i, n = 0, len(line)
00100     while i < n:
00101         field, i = parsefield(line, i, n)
00102         fields.append(field)
00103         i = i+1 # Skip semicolon
00104     if len(fields) < 2:
00105         return None, None
00106     key, view, rest = fields[0], fields[1], fields[2:]
00107     fields = {'view': view}
00108     for field in rest:
00109         i = field.find('=')
00110         if i < 0:
00111             fkey = field
00112             fvalue = ""
00113         else:
00114             fkey = field[:i].strip()
00115             fvalue = field[i+1:].strip()
00116         if fkey in fields:
00117             # Ignore it
00118             pass
00119         else:
00120             fields[fkey] = fvalue
00121     return key, fields

Here is the call graph for this function:

Here is the caller graph for this function:

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.

00053 
00054 def readmailcapfile(fp):
00055     """Read a mailcap file and return a dictionary keyed by MIME type.
00056 
00057     Each MIME type is mapped to an entry consisting of a list of
00058     dictionaries; the list will contain more than one such dictionary
00059     if a given MIME type appears more than once in the mailcap file.
00060     Each dictionary contains key-value pairs for that MIME type, where
00061     the viewing command is stored with the key "view".
00062     """
00063     caps = {}
00064     while 1:
00065         line = fp.readline()
00066         if not line: break
00067         # Ignore comments and blank lines
00068         if line[0] == '#' or line.strip() == '':
00069             continue
00070         nextline = line
00071         # Join continuation lines
00072         while nextline[-2:] == '\\\n':
00073             nextline = fp.readline()
00074             if not nextline: nextline = '\n'
00075             line = line[:-2] + nextline
00076         # Parse the line
00077         key, fields = parseline(line)
00078         if not (key and fields):
00079             continue
00080         # Normalize the key
00081         types = key.split('/')
00082         for j in range(len(types)):
00083             types[j] = types[j].strip()
00084         key = '/'.join(types).lower()
00085         # Update the database
00086         if key in caps:
00087             caps[key].append(fields)
00088         else:
00089             caps[key] = [fields]
00090     return caps

Here is the call graph for this function:

Here is the caller graph for this function:

def mailcap.show (   caps)

Definition at line 235 of file mailcap.py.

00235 
00236 def show(caps):
00237     print("Mailcap files:")
00238     for fn in listmailcapfiles(): print("\t" + fn)
00239     print()
00240     if not caps: caps = getcaps()
00241     print("Mailcap entries:")
00242     print()
00243     ckeys = sorted(caps)
00244     for type in ckeys:
00245         print(type)
00246         entries = caps[type]
00247         for e in entries:
00248             keys = sorted(e)
00249             for k in keys:
00250                 print("  %-15s" % k, e[k])
00251             print()

Here is the call graph for this function:

Here is the caller graph for this function:

def mailcap.subst (   field,
  MIMEtype,
  filename,
  plist = [] 
)

Definition at line 170 of file mailcap.py.

00170 
00171 def subst(field, MIMEtype, filename, plist=[]):
00172     # XXX Actually, this is Unix-specific
00173     res = ''
00174     i, n = 0, len(field)
00175     while i < n:
00176         c = field[i]; i = i+1
00177         if c != '%':
00178             if c == '\\':
00179                 c = field[i:i+1]; i = i+1
00180             res = res + c
00181         else:
00182             c = field[i]; i = i+1
00183             if c == '%':
00184                 res = res + c
00185             elif c == 's':
00186                 res = res + filename
00187             elif c == 't':
00188                 res = res + MIMEtype
00189             elif c == '{':
00190                 start = i
00191                 while i < n and field[i] != '}':
00192                     i = i+1
00193                 name = field[start:i]
00194                 i = i+1
00195                 res = res + findparam(name, plist)
00196             # XXX To do:
00197             # %n == number of parts if type is multipart/*
00198             # %F == list of alternating type and filename for parts
00199             else:
00200                 res = res + '%' + c
00201     return res

Here is the call graph for this function:

Here is the caller graph for this function:

def mailcap.test ( )

Definition at line 213 of file mailcap.py.

00213 
00214 def test():
00215     import sys
00216     caps = getcaps()
00217     if not sys.argv[1:]:
00218         show(caps)
00219         return
00220     for i in range(1, len(sys.argv), 2):
00221         args = sys.argv[i:i+2]
00222         if len(args) < 2:
00223             print("usage: mailcap [MIMEtype file] ...")
00224             return
00225         MIMEtype = args[0]
00226         file = args[1]
00227         command, e = findmatch(caps, MIMEtype, 'view', file)
00228         if not command:
00229             print("No viewer found for", type)
00230         else:
00231             print("Executing:", command)
00232             sts = os.system(command)
00233             if sts:
00234                 print("Exit status:", sts)

Here is the call graph for this function:


Variable Documentation

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

Definition at line 5 of file mailcap.py.