Ticket #693: trac_693-spawn-nb.2.patch

File trac_693-spawn-nb.2.patch, 2.0 KB (added by timdumol, 12 years ago)

Uses signals only to check if the process exists (as Twisted does)

  • sagenb/notebook/run_notebook.py

    #693 Script to spawn a browser/start notebook
    
    diff -r d58a0f9a1f1e sagenb/notebook/run_notebook.py
    a b  
    2020    protocol = 'ssl'
    2121
    2222# System libraries
    23 import getpass, os, shutil, socket
     23import getpass, os, shutil, socket, subprocess, errno
    2424
    2525from sagenb.misc.misc import (DOT_SAGENB, print_open_msg, find_next_available_port)
     26from sagenb.misc.misc import browser
    2627
    2728import notebook
    2829
     
    7576    else:
    7677        if isinstance(directory, basestring) and len(directory) > 0 and directory[-1] == "/":
    7778            directory = directory[:-1]
     79
     80    twistd_pid_path = os.path.join(directory + '.sagenb', 'twistd.pid')
     81   
     82    def remove_pidfile(path):
     83        """Ad-hoc function to remove the stale pidfile"""
     84        print 'Removing stale pidfile %s' % path
     85        os.remove(path)
     86
     87    def launch_browser_to_nb():
     88        """Ad-hoc function to launch browser to the notebook page"""
     89        subprocess.Popen(browser().split(' ') + ['http%s://%s:%d' % ('s' if secure else '', address,port)])
     90
     91
     92       
     93    if os.path.exists(twistd_pid_path):
     94        try:
     95            twistd_pid = int(open(twistd_pid_path).read())
     96        except:
     97            print 'Pidfile %s contains non-numeric value' % twistd_pid_path
     98            return
     99       
     100        # Check if process exists
     101        try:
     102            os.kill(twistd_pid, 0)
     103            # Process exists, proceed launch
     104            launch_browser_to_nb()
     105            return
     106        except OSError, why:
     107            if why[0] == errno.ESRCH:
     108                # Process with pid does not exist
     109                remove_pidfile(twistd_pid_path)
     110            else:
     111                print("Could not check status of PID %s from pidfile %s: %s" %
     112                      (twistd_pid, twistd_pid_path, why[1]))
    78113           
    79114    # First change to the directory that contains the notebook directory
    80115    wd = os.path.split(directory)