Launching an independent Python program in a cross-platform way (including mac)

André andre.roberge at gmail.com
Tue May 1 07:47:47 EDT 2007


My apologies about the last post; I posted my "test" code by mistake,
with hard-coded path information.  Here's for future reference
something that is general and should work cross-platform.
André

def exec_external(code=None,  path=None):
    """execute code in an external process
    currently works under:
        * Windows NT (tested)
        * GNOME
        * OS X
    This also needs to be tested for KDE
    and implemented some form of linux fallback (xterm?)
    """
    if path is None:
        path = os.path.join(os.path.expanduser("~"), "temp.py")
    if os.name == 'nt' or sys.platform == 'darwin':
        current_dir = os.getcwd()
        target_dir, fname = os.path.split(path)

    if code is not None:
        filename = open(path, 'w')
        filename.write(code)
        filename.close()

    if os.name == 'nt':
        os.chdir(target_dir) # change dir so as to deal with paths
that
                             # include spaces
        Popen(["cmd.exe", ('/c start python %s'%fname)])
        os.chdir(current_dir)
    elif sys.platform == 'darwin':  # a much more general method can
be found
                                 # in SPE, Stani's Python Editor -
Child.py
        activate = 'tell application "Terminal" to activate'
        script = r"cd '\''%s'\'';python '\''%s'\'';exit"%(target_dir,
fname)
        do_script = r'tell application "Terminal" to do script
"%s"'%script
        command =  "osascript -e '%s';osascript -e '%s'"%(activate,
do_script)
        os.popen(command)
    elif os.name == 'posix':
        try:
            os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome-
terminal',
                                '-x', 'python', '%s'%path)
        except:
            try: # untested
                os.spawnlp(os.P_NOWAIT, 'konsole', 'konsole',
                                '-x', 'python', '%s'%path)
            except:
                raise NotImplementedError
    else:
        raise NotImplementedError





More information about the Python-list mailing list