paulb@1 | 1 | #!/usr/bin/env python |
paulb@1 | 2 | |
paulb@1 | 3 | "Simple desktop integration for Python." |
paulb@1 | 4 | |
paulb@1 | 5 | import os |
paulb@4 | 6 | import sys |
paulb@1 | 7 | import subprocess |
paulb@1 | 8 | |
paulb@1 | 9 | def open(url, desktop=None): |
paulb@1 | 10 | |
paulb@1 | 11 | """ |
paulb@1 | 12 | Open the 'url' in the current desktop's preferred file browser. If the |
paulb@1 | 13 | optional 'desktop' parameter is specified then attempt to use that |
paulb@1 | 14 | particular desktop environment's mechanisms to open the 'url' instead of |
paulb@1 | 15 | guessing or detecting which environment is being used. |
paulb@1 | 16 | |
paulb@4 | 17 | Suggested values for 'desktop' are "KDE", "GNOME", "Mac OS X" and "generic", |
paulb@4 | 18 | where "generic" uses an OPENER environment variable to open the specified |
paulb@4 | 19 | 'url'. |
paulb@3 | 20 | |
paulb@3 | 21 | The process identifier of the "opener" (ie. viewer, editor, browser or |
paulb@3 | 22 | program) associated with the 'url' is returned by this function. If the |
paulb@3 | 23 | process identifier cannot be determined, None is returned. |
paulb@1 | 24 | """ |
paulb@1 | 25 | |
paulb@4 | 26 | if desktop == "generic" or \ |
paulb@4 | 27 | desktop is None and os.environ.has_key("OPENER"): |
paulb@4 | 28 | |
paulb@4 | 29 | try: |
paulb@4 | 30 | # NOTE: This may not handle sophisticated commands properly. |
paulb@4 | 31 | cmd = os.environ["OPENER"].split() |
paulb@4 | 32 | cmd.append(url) |
paulb@4 | 33 | except KeyError, exc: |
paulb@4 | 34 | raise OSError, "Desktop not supported (OPENER could not be used)" |
paulb@4 | 35 | |
paulb@4 | 36 | elif desktop == "KDE" or \ |
paulb@1 | 37 | desktop is None and (os.environ.has_key("KDE_FULL_SESSION") or |
paulb@1 | 38 | os.environ.has_key("KDE_MULTIHEAD")): |
paulb@1 | 39 | |
paulb@4 | 40 | cmd = ["kfmclient", "exec", url] |
paulb@1 | 41 | |
paulb@1 | 42 | elif desktop == "GNOME" or \ |
paulb@1 | 43 | desktop is None and (os.environ.has_key("GNOME_DESKTOP_SESSION_ID") or |
paulb@1 | 44 | os.environ.has_key("GNOME_KEYRING_SOCKET")): |
paulb@1 | 45 | |
paulb@1 | 46 | cmd = ["gnome-open", url] |
paulb@1 | 47 | |
paulb@4 | 48 | elif desktop == "Mac OS X" or \ |
paulb@4 | 49 | desktop is None and sys.platform == "darwin": |
paulb@4 | 50 | |
paulb@4 | 51 | cmd = ["open", url] |
paulb@4 | 52 | |
paulb@1 | 53 | else: |
paulb@3 | 54 | try: |
paulb@3 | 55 | # NOTE: This returns None in current implementations. |
paulb@3 | 56 | return os.startfile(url) |
paulb@3 | 57 | except AttributeError, exc: |
paulb@3 | 58 | raise OSError, "Desktop not supported (os.startfile could not be used)" |
paulb@1 | 59 | |
paulb@3 | 60 | return subprocess.Popen(cmd).pid |
paulb@1 | 61 | |
paulb@1 | 62 | # vim: tabstop=4 expandtab shiftwidth=4 |