Explicitly ask the ipython kernel for its pid
161293
def set_pid():
    
    global pid
    lines = '\n'.join(['import os', '_pid = os.getpid()'])

    try:
        msg_id = send(lines, silent=True, user_variables=['_pid'])
    except TypeError: # change in IPython 3.0+
        msg_id = send(lines, silent=True, user_expressions={'_pid':'_pid'})

    # wait to get message back from kernel
    try:
        child = get_child_msg(msg_id)
    except Empty:
        echo("no reply from IPython kernel")
        return
    try:
        pid = int(child['content']['user_variables']['_pid'])
    except TypeError: # change in IPython 1.0.dev moved this out
        pid = int(child['content']['user_variables']['_pid']['data']['text/plain'])
    except KeyError:    # change in IPython 3.0+
        pid = int(
            child['content']['user_expressions']['_pid']['data']['text/plain'])
    except KeyError: # change in IPython 1.0.dev moved this out
        echo("Could not get PID information, kernel not running Python?")
    return pid
1176749
def resolve_pid(fetched_pid):
    
    return PersistentIdentifier.get(
        pid_type=fetched_pid.pid_type,
        pid_value=fetched_pid.pid_value,
        pid_provider=fetched_pid.provider.pid_provider
    )
681713
def os_is_running(pid):
    '''
    
    '''
    if isinstance(pid, six.string_types):
        pid = int(pid)
    if HAS_PSUTIL:
        return psutil.pid_exists(pid)
    else:
        try:
            os.kill(pid, 0)  # SIG 0 is the "are you alive?" signal
            return True
        except OSError:
            return False
166681
def attach_kernel_driver(self, interface):
        
        """
        self._ctx.managed_open()
        self._ctx.backend.attach_kernel_driver(
            self._ctx.handle,
            interface)
669837
def load_ipython_extension(ip, **kwargs):
    """"""
    global _loaded
    if not _loaded:
        ip.register_magics(MatlabMagics(ip, **kwargs))
        _loaded = True
912917
def _pid_is_alive(cls, pid, timeout):
        """"""
        try:
            proc = psutil.Process(pid)
        except psutil.NoSuchProcess:
            return False

        try:
            proc.wait(timeout=timeout)
        except psutil.TimeoutExpired:
            return True

        return False
101309
def process_info(pid=None):
    '''
    '''
    if psutil is None:  # pragma    nocover
        return {}
    pid = pid or os.getpid()
    try:
        p = psutil.Process(pid)
    # this fails on platforms which don't allow multiprocessing
    except psutil.NoSuchProcess:  # pragma    nocover
        return {}
    else:
        mem = p.memory_info()
        return {'memory': convert_bytes(mem.rss),
                'memory_virtual': convert_bytes(mem.vms),
                'cpu_percent': p.cpu_percent(),
                'nice': p.nice(),
                'num_threads': p.num_threads()}
957550
def connect_client_to_kernel(self, client, is_cython=False,
                                 is_pylab=False, is_sympy=False):
        """"""
        connection_file = client.connection_file
        stderr_handle = None if self.test_no_stderr else client.stderr_handle
        km, kc = self.create_kernel_manager_and_kernel_client(
                     connection_file,
                     stderr_handle,
                     is_cython=is_cython,
                     is_pylab=is_pylab,
                     is_sympy=is_sympy)

        # An error occurred if this is True
        if is_string(km) and kc is None:
            client.shellwidget.kernel_manager = None
            client.show_kernel_error(km)
            return

        # This avoids a recurrent, spurious NameError when running our
        # tests in our CIs
        if not self.testing:
            kc.started_channels.connect(
                lambda c=client: self.process_started(c))
            kc.stopped_channels.connect(
                lambda c=client: self.process_finished(c))
        kc.start_channels(shell=True, iopub=True)

        shellwidget = client.shellwidget
        shellwidget.kernel_manager = km
        shellwidget.kernel_client = kc
981674
def _check_pid(self, allow_reset=False):
        """"""
        if not self.pid == current_process().pid:
            if allow_reset:
                self.reset()
            else:
                raise RuntimeError("Forbidden operation in multiple processes")
575891
def get_pid(self):
        
        if self.dwProcessId is None:
            if self.__process is not None:
                # Infinite loop if self.__process is None
                self.dwProcessId = self.get_process().get_pid()
            else:
                try:
                    # I wish this had been implemented before Vista...
                    # XXX TODO find the real ntdll call under this api
                    hThread = self.get_handle(
                                        win32.THREAD_QUERY_LIMITED_INFORMATION)
                    self.dwProcessId = win32.GetProcessIdOfThread(hThread)
                except AttributeError:
                    # This method really sucks :P
                    self.dwProcessId = self.__get_pid_by_scanning()
        return self.dwProcessId
124642
def create_kernel_spec(self, is_cython=False,
                           is_pylab=False, is_sympy=False):
        """"""
        # Before creating our kernel spec, we always need to
        # set this value in spyder.ini
        CONF.set('main', 'spyder_pythonpath',
                 self.main.get_spyder_pythonpath())
        return SpyderKernelSpec(is_cython=is_cython,
                                is_pylab=is_pylab,
                                is_sympy=is_sympy)
549991
def connect_to_ipykernel(self, service_name, timeout=10):
        """"""
        kernel_json_file = self.wait_for_ipykernel(service_name, timeout=10)
        self.start_interactive_mode()
        subprocess.check_call([
            sys.executable, "-m", "IPython", "console", "--existing", kernel_json_file
        ])
        self.stop_interactive_mode()
1149110
def pid(self):
        
        # We can't possibly be running if our base_pathname isn't defined.
        if not self.base_pathname:
            return None
        try:
            pidfile = os.path.join(self.base_pathname, 'postmaster.pid')
            return int(open(pidfile).readline())
        except (IOError, OSError):
            return None
994415
def getPID(self):
        
        if self._pid is not None:
            if not PlatformManager.isPIDValid(self._pid):
                self._pid = -1
            return self._pid
        return -1
859458
def detect_process(cls, headers):
    """"""

    try:
      if 'Libprocess-From' in headers:
        return PID.from_string(headers['Libprocess-From']), False
      elif 'User-Agent' in headers and headers['User-Agent'].startswith('libprocess/'):
        return PID.from_string(headers['User-Agent'][len('libprocess/'):]), True
    except ValueError as e:
      log.error('Failed to detect process: %r' % e)
      pass

    return None, None
441776
def write_pid(self, pid=None):
    """"""
    pid = pid or os.getpid()
    self.write_metadata_by_name(self._name, 'pid', str(pid))
164450
def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags):
        
        if use_subprocess is False:
            return foo(*args, **kwrags)

        child_pid = os.fork()
        if child_pid == 0:
            foo(*args, **kwrags)
            sys.exit(0)
        return os.waitpid(child_pid, 0)[1] == 0