Python psutil 模块,NoSuchProcess() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用psutil.NoSuchProcess()

项目:Chasar    作者:camilochs    | 项目源码 | 文件源码
def pids_active(pids_computer):
    """
    This function find pids of computer and return the valid.
    """
    pid_valid = {}
    for pid in pids_computer:
        data = None
        try:
            process = psutil.Process(pid)
            data = {"pid": process.pid,
                    "status": process.status(),
                    "percent_cpu_used": process.cpu_percent(interval=0.0),
                    "percent_memory_used": process.memory_percent()}

        except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess):
            data = None

        if data is not None:
            pid_valid[process.name()] = data
    return pid_valid
项目:ransomcare    作者:Happyholic1203    | 项目源码 | 文件源码
def on_ask_user_allow_or_deny(self, evt):
        try:
            exe = evt.process.exe()
            cmdline = evt.process.cmdline()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            logger.warn('Ransomware process is caught, but the process does '
                        'not exist (PID: %d)' % evt.pid)

        logger.critical('\033[91m')
        logger.critical('*** [Crypto ransom detected] ***')
        logger.critical('[PID]: %d' % evt.process.pid)
        logger.critical('[EXE]: %r' % exe)
        logger.critical('[Command]: %r' % cmdline)
        logger.critical('[File]: %s' % evt.path)
        logger.critical('********************************\033[0m')
        flush_stdin()
        yes_no = raw_input('> Block it? (Y/n) ')

        allow = 'n' in yes_no.lower()
        if allow:
            event.EventUserAllowProcess(evt.process).fire()
        else:
            event.EventUserDenyProcess(evt.process).fire()
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def find_server_processes(cls, port=None):
        result = []
        for p in psutil.process_iter():
            try:
                if isinstance(type(p).cmdline, property):
                    pname = p.name
                    cmdline = p.cmdline
                else:
                    pname = p.name()
                    cmdline = p.cmdline()
                if pname == 'adb':
                    if 'fork-server' in cmdline and 'server' in cmdline:
                        if port != None and str(port) not in cmdline:
                            continue
                        result.append(p)
            except psutil.NoSuchProcess:
                continue
        return result
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def find_server_processes(cls, port=None):
        result = []
        for p in psutil.process_iter():
            try:
                if isinstance(type(p).cmdline, property):
                    pname = p.name
                    cmdline = p.cmdline
                else:
                    pname = p.name()
                    cmdline = p.cmdline()
                if pname == 'adb':
                    if 'fork-server' in cmdline and 'server' in cmdline:
                        if port != None and str(port) not in cmdline:
                            continue
                        result.append(p)
            except psutil.NoSuchProcess:
                continue
        return result
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def join(pid, timeout):
    if pid == 0:
        return
    start = time.time()
    while time.time() - start < timeout:
        try:
            proc = Process(pid)
        except NoSuchProcess:
            return
        except IOError, e:
            if e.errno == errno.ESRCH:
                return
            else:
                raise e
        time.sleep(0.5)
    raise Timeout('timeout')
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def join(pid, timeout):
    if pid == 0:
        return
    start = time.time()
    while time.time() - start < timeout:
        try:
            proc = Process(pid)
        except NoSuchProcess:
            return
        except IOError, e:
            if e.errno == errno.ESRCH:
                return
            else:
                raise e
        time.sleep(0.5)
    raise Timeout('timeout')
项目:monitorstack    作者:openstack    | 项目源码 | 文件源码
def get_cmdlines():
    """Retrieve the cmdline of each process running on the system."""
    processes = []

    # Get our current PID as well as the parent so we can exclude them.
    current_pid = os.getpid()
    parent_pid = os.getppid()

    for proc in psutil.process_iter():
        try:
            if proc.pid not in [current_pid, parent_pid]:
                processes.append(' '.join(proc.cmdline()))
        except psutil.NoSuchProcess:
            pass

    return processes
项目:aquests    作者:hansroh    | 项目源码 | 文件源码
def kill (chdir, procname = None, include_children = True, signaling = True):
    import psutil

    for i in range (2):
        pid = status (chdir, procname)      
        if not pid: 
            break

        if signaling:   
            os.kill (pid, signal.SIGTERM)
            time.sleep (2)

        if include_children:
            try:
                killtree.kill (pid, True)
            except psutil.NoSuchProcess:
                pass    

        while processutil.is_running (pid, procname):
            time.sleep (1)

    try:
        os.remove (os.path.join (chdir, ".pid"))
    except FileNotFoundError:   
        pass
项目:Chasar    作者:camilochs    | 项目源码 | 文件源码
def pids_active(pids_computer):
    """
    This function find pids of computer and return the valid.
    """
    pid_valid = {}
    for pid in pids_computer:
        data = None
        try:
            process = psutil.Process(pid)
            data = {"pid": process.pid,
                    "status": process.status(),
                    "percent_cpu_used": process.cpu_percent(interval=0.0),
                    "percent_memory_used": process.memory_percent()}

        except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess):
            data = None

        if data is not None:
            pid_valid[process.name()] = data
    return pid_valid
项目:universe    作者:openai    | 项目源码 | 文件源码
def cpu_times(self):
        ''' return {pid: {'user': 0.0, 'sys': 0.0}}, chrome_reset '''
        chrome_procs = self.get_chrome_procs()
        new_pids = {p.pid for p in chrome_procs}
        old_pids = {pid for pid in self.last_cpu_times}
        try:
            cpu_times = {p.pid: p.cpu_times() for p in chrome_procs}
        except psutil.NoSuchProcess:
            # Chrome restarted since fetching the new pids above. Better luck next time.
            return {}, True
        if new_pids != old_pids:
            # We don't know when the Chrome procs were restarted, so don't
            # return elapsed time until next run.
            self.last_cpu_times = cpu_times
            return {}, True
        # Same chrome pids as last run: measure the elapsed cpu times
        ordered_old_times = (self.last_cpu_times[p.pid] for p in chrome_procs)
        ordered_new_times = (cpu_times[p.pid] for p in chrome_procs)
        cpu_times_diff = {p.pid: {'user': (t[0] - l[0]) / self.interval, 'sys': (t[1] - l[1]) / self.interval}
                for (p, t, l) in zip(chrome_procs, ordered_new_times, ordered_old_times)}
        self.last_cpu_times = cpu_times
        return cpu_times_diff, False
项目:ransomcare    作者:Happyholic1203    | 项目源码 | 文件源码
def on_crypto_ransom(self, evt):
        logger.debug('Whitelist: %s' % json.dumps(self.whitelist, indent=4))
        logger.debug('Suspended: %s' % json.dumps([
            {'pid': p.pid, 'exe': p.exe()} for p in self.suspended
        ], indent=4))
        if any(suspended.pid == evt.pid for suspended in self.suspended):
            return  # ignore captured ransom events

        try:
            p = psutil.Process(evt.pid)
            cmdline = p.cmdline()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            logger.warn('Suspicious process %d exited before being caught'
                        % evt.pid)
            return

        if cmdline not in self.whitelist:
            p.suspend()
            self.suspended.append(p)
            event.EventAskUserAllowOrDeny(p, evt.path).fire()
        else:
            logger.info('Allowed white-listed process: %d' % evt.pid)
项目:ransomcare    作者:Happyholic1203    | 项目源码 | 文件源码
def get_absolute_path(event_raw):
    '''
    Keeps a cache of processes' cwds, in case that their events might come
    after they're terminated.
    '''
    pid = event_raw.get('pid')
    path = event_raw.get('path')
    if path and path[0] == '/':
        return os.path.realpath(path)

    cwd = None
    logger.debug('%r' % pid_cwd)
    try:
        process = psutil.Process(pid)
        cwd = process.cwd()
        pid_cwd[pid] = cwd  # cache every pid's cwd
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        cwd = pid_cwd.get(pid)
        if not cwd:
            return None

    return os.path.realpath(os.path.join(cwd, path))
项目:ransomcare    作者:Happyholic1203    | 项目源码 | 文件源码
def on_crypto_ransom(self, evt):
        logger.debug('Got crypto ransom event')
        cmdline, exe = None, None
        try:
            p = psutil.Process(evt.pid)
            cmdline = p.cmdline()
            exe = p.exe()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pid_profile = self.engine.pid_profiles.get(evt.pid)
            if pid_profile is not None:
                cmdline = pid_profile.get('cmdline')
                exe = cmdline[0] if cmdline else None
        crypto_ransom_event = {
            'pid': evt.pid,
            'path': evt.path,
            'cmdline': cmdline,
            'exe': exe,
            'timestamp': datetime.datetime.now().isoformat()
        }
        self.web.ctx['events'].append(crypto_ransom_event)
        self.web.socketio.emit('event', crypto_ransom_event)
项目:distiller    作者:pyoor    | 项目源码 | 文件源码
def check(proc, target_name, max_timeout):
    """
    Check CPU usage of target process
    """
    try:
        pid = proc.pid
        start_time = time()
        if psutil.Process(pid).children():
            for child in psutil.Process(pid).children():
                if child.name() == target_name:
                    while True:
                        cpu = all(0 == child.cpu_percent(interval=0.1) for x in xrange(8))
                        if cpu is not None and cpu is True:
                            kill(proc, child.pid)
                            break
                        if max_timeout is not None or max_timeout != 0:
                            end_time = time()
                            elapsed = end_time - start_time
                            if elapsed > max_timeout:
                                kill(proc, child.pid)
                                break
    except psutil.NoSuchProcess:
        pass
项目:isp-data-pollution    作者:essandess    | 项目源码 | 文件源码
def check_phantomjs_process(self):
        """
        Check if phantomjs is running.
        :return: 
        """
        # Check rss and restart if too large, then check existence
        # http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python
        try:
            if not hasattr(self,'driver'): self.open_driver()
            pid, rss_mb = self.phantomjs_pid_and_memory()
            if rss_mb > self.phantomjs_rss_limit_mb:  # memory limit
                self.quit_driver(pid=pid)
                self.open_driver()
                pid, _ = self.phantomjs_pid_and_memory()
            # check existence
            os.kill(pid, 0)
        except (OSError,psutil.NoSuchProcess,Exception) as e:
            if self.debug: print('.phantomjs_pid_and_memory() exception:\n{}'.format(e))
            if issubclass(type(e),psutil.NoSuchProcess):
                raise Exception("There's a phantomjs zombie, and the thread shouldn't have reached this statement.")
            return False
        else:
            return True
项目:isp-data-pollution    作者:essandess    | 项目源码 | 文件源码
def phantomjs_pid_and_memory(self):
        """ Return the pid and memory (MB) of the phantomjs process,
        restart if it's a zombie, and exit if a restart isn't working
        after three attempts. """
        for k in range(3):    # three strikes
            try:
                @self.phantomjs_short_timeout
                def phantomjs_process_pid(): return self.driver.service.process.pid
                pid = phantomjs_process_pid()
                rss_mb = psutil.Process(pid).memory_info().rss / float(2 ** 20)
                break
            except (psutil.NoSuchProcess,Exception) as e:
                if self.debug: print('.service.process.pid exception:\n{}'.format(e))
                self.quit_driver(pid=pid)
                self.open_driver()
        else:  # throw in the towel and exit if no viable phantomjs process after multiple attempts
            print('No viable phantomjs process after multiple attempts!')
            sys.exit(1)
        return (pid, rss_mb)
项目:incubator-airflow-old    作者:apache    | 项目源码 | 文件源码
def kill_using_shell(logger, pid, signal=signal.SIGTERM):
    try:
        process = psutil.Process(pid)
        # Use sudo only when necessary - consider SubDagOperator and SequentialExecutor case.
        if process.username() != getpass.getuser():
            args = ["sudo", "kill", "-{}".format(int(signal)), str(pid)]
        else:
            args = ["kill", "-{}".format(int(signal)), str(pid)]
        # PID may not exist and return a non-zero error code
        logger.error(subprocess.check_output(args, close_fds=True))
        logger.info("Killed process {} with signal {}".format(pid, signal))
        return True
    except psutil.NoSuchProcess as e:
        logger.warning("Process {} no longer exists".format(pid))
        return False
    except subprocess.CalledProcessError as e:
        logger.warning("Failed to kill process {} with signal {}. Output: {}"
                       .format(pid, signal, e.output))
        return False
项目:psystem    作者:gokhanm    | 项目源码 | 文件源码
def pid(self, process_name):
        """
            process_name: System Process Name
            return: Process name's pid, integer
        """
        for proc in psutil.process_iter():
            try:
                pinfo = proc.as_dict(attrs=['pid', 'name'])
                p_name = pinfo['name']
                p_pid = pinfo['pid']

                if process_name == p_name:
                    return p_pid

            except psutil.NoSuchProcess:
                pass
项目:hydra    作者:lake-lerna    | 项目源码 | 文件源码
def terminate_process_and_children(self, name):
        """
        Recursively terminate all children of
        respective process
        @args:
        name:   Name of the job
        """
        if name not in self.jobs:
            print("[%s] does not exist as a process!", name)
        ppid = self.jobs[name]['process'].pid
        try:
            parent_proc = psutil.Process(ppid)
        except psutil.NoSuchProcess:
            return
        children = parent_proc.children(recursive=True)
        for proc in children:
            l.debug(proc)
            try:
                proc.send_signal(signal.SIGKILL)
            except:
                pass
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_process_iter(self):
        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
        sproc = get_test_subprocess()
        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])

        with mock.patch('psutil.Process',
                        side_effect=psutil.NoSuchProcess(os.getpid())):
            self.assertEqual(list(psutil.process_iter()), [])
        with mock.patch('psutil.Process',
                        side_effect=psutil.AccessDenied(os.getpid())):
            with self.assertRaises(psutil.AccessDenied):
                list(psutil.process_iter())
项目:certbot    作者:nikoloskii    | 项目源码 | 文件源码
def test_race_condition(self, mock_get_utility, mock_process, mock_net):
        # This tests a race condition, or permission problem, or OS
        # incompatibility in which, for some reason, no process name can be
        # found to match the identified listening PID.
        from psutil._common import sconn
        conns = [
            sconn(fd=-1, family=2, type=1, laddr=("0.0.0.0", 30),
                  raddr=(), status="LISTEN", pid=None),
            sconn(fd=3, family=2, type=1, laddr=("192.168.5.10", 32783),
                  raddr=("20.40.60.80", 22), status="ESTABLISHED", pid=1234),
            sconn(fd=-1, family=10, type=1, laddr=("::1", 54321),
                  raddr=("::1", 111), status="CLOSE_WAIT", pid=None),
            sconn(fd=3, family=2, type=1, laddr=("0.0.0.0", 17),
                  raddr=(), status="LISTEN", pid=4416)]
        mock_net.return_value = conns
        mock_process.side_effect = psutil.NoSuchProcess("No such PID")
        # We simulate being unable to find the process name of PID 4416,
        # which results in returning False.
        self.assertFalse(self._call(17))
        self.assertEqual(mock_get_utility.generic_notification.call_count, 0)
        mock_process.assert_called_once_with(4416)
项目:TorStat    作者:rootlabs    | 项目源码 | 文件源码
def TOR_PROC_CHECK():
    isTorRunnin = False
    TOR_INFO = {}
    TOR_PROC = None
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
        except psutil.NoSuchProcess:
            pass
        else:
            if pinfo['name'] == "tor":
                isTorRunnin = True
                TOR_INFO['pid'] = pinfo['pid']
                TOR_INFO['name'] = pinfo['name']
                break

    if isTorRunnin == True:
        print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " Tor is running." + Style.RESET_ALL)
        TOR_PROC = psutil.Process(int(TOR_INFO['pid']))
        return TOR_PROC
    else:
        print ("[" + Fore.RED + Style.BRIGHT + "-" + Style.RESET_ALL + "]" + Fore.RED + Style.BRIGHT + " Tor is not running." + Style.RESET_ALL)
        exit()
项目:ruuvitag-sensor    作者:ttu    | 项目源码 | 文件源码
def stop(hcitool, hcidump):
        # import psutil here so as long as all implementations are in the same file, all will work
        import psutil

        log.info('Stop receiving broadcasts')

        def kill_child_processes(parent_pid):
            try:
                parent = psutil.Process(parent_pid)
            except psutil.NoSuchProcess:
                return

            for process in parent.children(recursive=True):
                subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(process.pid)])

        kill_child_processes(hcitool.pid)
        subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(hcitool.pid)])
        kill_child_processes(hcidump.pid)
        subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(hcidump.pid)])
项目:mWorkerService    作者:smices    | 项目源码 | 文件源码
def status():
    """
    Fetch service status
    :return:
    """
    if master_pid("c") is True:
        print colored(" SERVICE IS RUNNING... ", "white", "on_blue")
        h = PrettyTable([u"??ID", u"????"])
        h.align[u"??ID"] = "l"
        h.align[u"????"] = "l"
        h.padding_width = 1
        pid_list = processors_list("r")
        for pid in pid_list:
            try:
                if psutil.Process(pid).is_running():
                    h.add_row([pid, colored("RUNNING...",attrs=["bold"])])
                else:
                    h.add_row([colored(pid, "magenta", "on_yellow", attrs=["bold"]),
                               colored("STOPED", "magenta", "on_yellow", attrs=["bold"])])
            except psutil.NoSuchProcess:
                h.add_row([colored(pid, "yellow", attrs=["bold", "blink"]),
                           colored("LOSTED", "red", attrs=["bold", "blink"])])
        print h
    else:
        cmsg("SERVICE IS STOPED!", "e")
项目:crondeamon    作者:zhoukunpeng504    | 项目源码 | 文件源码
def start():
    old_pid=get_pid()
    try:
        process=psutil.Process(pid=old_pid)
    except psutil.NoSuchProcess as  e :
        process=None
        os.system("rm -rf %s/pid/crondeamon.pid"%datadir)
    if old_pid and process:
        cmd_line=process.cmdline()
        mask=0
        for j in cmd_line:
            if  "twistd" in j  or "crondeamon" in j  :
                mask+=1
        if mask>=2:
            print "server is running ! "
        else:
            os.system("mkdir -p %s/pid"%datadir)
            os.system("mkdir -p %s/log"%datadir)
            os.system("twistd --pidfile %s/pid/crondeamon.pid --logfile %s/log/crondeamon.log crondeamon"%(datadir,datadir))
            print "start success!"
    else:
        os.system("mkdir -p %s/pid"%datadir)
        os.system("mkdir -p %s/log"%datadir)
        os.system("twistd --pidfile %s/pid/crondeamon.pid --logfile %s/log/crondeamon.log crondeamon"%(datadir,datadir))
        print "start success!"
项目:serverthrall    作者:NullSoldier    | 项目源码 | 文件源码
def start(self):
        if self.process or self.is_running():
            self.logger.error('Server already running call close_server first')
            return

        if len(self.arguments) == 0:
            self.logger.info('Launching server and waiting for child processes')
        else:
            self.logger.info('Launching server and waiting for child processes with extra arguments, %s' % self.arguments)

        try:
            process = subprocess.Popen([self.path, '-log', self.arguments])
            process = psutil.Process(process.pid)
            self.attach(process)
        except subprocess.CalledProcessError as ex:
            self.logger.exception('Server failed to start... %s' % ex)
            return False
        except psutil.NoSuchProcess as ex:
            self.logger.exception('Server started but crashed shortly after... %s' % ex)
            return False

        self.logger.info('Server running successfully')
        return True
项目:reflector-cluster    作者:lbryio    | 项目源码 | 文件源码
def show_prism_info(queues, raw, by_queue, queue_class, worker_class):
    show_queues(queues, raw, by_queue, queue_class, worker_class)
    if not raw:
        click.echo('')
    show_workers(queues, raw, by_queue, queue_class, worker_class)
    show_cluster_info()
    click.echo('')
    click.echo("Redis clients: %i" % len(redis_conn.client_list()))
    click.echo("Local blobs: %i" % len(os.listdir(os.path.expandvars(BLOB_DIR))))

    try:
        click.echo("Open files: %i" % len(server_proc.open_files()))
    except psutil.NoSuchProcess:
        sys.exit(0)
    if not raw:
        click.echo('')
        import datetime
        click.echo('Updated: %s' % datetime.datetime.now())
项目:ops_tools    作者:juliovp01    | 项目源码 | 文件源码
def check_process_exists_and_amqp_connected(name):
    processes = filter(lambda p: check_process_name(name, p),
                       psutil.process_iter())
    if not processes:
        critical("%s is not running" % name)
    for p in processes:
        try:
            connections = p.get_connections(kind='inet')
        except psutil.NoSuchProcess:
            continue
        found_amqp = (
            len(list(itertools.takewhile(lambda c: len(c.remote_address) <= 1
                                         or c.remote_address[1]
                                         != AMQP_PORT, connections)))
            != len(connections))
        if found_amqp:
            ok("%s is working." % name)
    critical("%s is not connected to AMQP" % name)
项目:idiot    作者:snare    | 项目源码 | 文件源码
def run(self):
        with open(os.devnull, 'w') as devnull:
            try:
                # If the service is disabled in Preferences
                # the query returns a non-zero error
                # should use this query better in future
                if subprocess.check_call(['launchctl', 'print', 'system/com.openssh.sshd'], stdout=devnull, stderr=devnull):
                    return (True, "disabled")
                else:
                    return (False, "enabled in Sharing Prefs: Remote Login")
            except subprocess.CalledProcessError as e:
                # this only gets run if sshd isn't enabled by
                # launchd as checked above
                pids = []
                for p in psutil.process_iter():
                    try:
                        if p.name() == 'sshd':
                            pids.append(p.pid)
                    except psutil.NoSuchProcess:
                        pass
                if len(pids):
                    return (False, "enabled manually - see pids: {} ".format(', '.join([str(p) for p in pids])))
                else:
                    return (True, "disabled")
项目:idiot    作者:snare    | 项目源码 | 文件源码
def run(self):
        """
        Run the check.

        All check scripts must implement this method. It must return a tuple of:
        (<success>, <message>)

        In this example, if the check succeeds and FileSharing processes are nowhere
        to be found, the check will return (True, "No FileSharing processes found").

        If the check fails and an FileSharing process is found, it returns
        (False, "Found SMB or AFP FileSharing processes with pids <pids>")
        """
        pids = []
        for p in psutil.process_iter():
            try:
                if (p.name() == 'AppleFileServer' or p.name() == 'smbd'):
                    pids.append(p.pid)
            except psutil.NoSuchProcess:
                pass

        if len(pids):
            return (False, "found SMB or AFP file sharing processes with pids: {} - Disable Sharing Prefs: File Sharing".format(', '.join([str(p) for p in pids])))
        else:
            return (True, "disabled")
项目:pypers    作者:frankosan    | 项目源码 | 文件源码
def pause_pipeline(self, run_id, user):
        """
        Interrupt pipeline by sending signal to corresponding worker's children
        """
        pid = self.pids.get(run_id)
        if pid:
            pretty_print("Pausing pipeline: id=%d, user=%s" % (run_id, user))
            try:
                parent = psutil.Process(pid)
                children = parent.children(recursive=True)
                for child in children:
                    run_as(cmd=['kill', child.pid], user=user)
            except psutil.NoSuchProcess:
                pretty_print("Error pausing pipeline: no process with ID %d" % int(pid))
        else:
            pretty_print("Error pausing pipeline: ID %d not found" % run_id)
项目:buildroot    作者:flutter    | 项目源码 | 文件源码
def KillAllAdb():
  def GetAllAdb():
    for p in psutil.process_iter():
      try:
        if 'adb' in p.name:
          yield p
      except (psutil.NoSuchProcess, psutil.AccessDenied):
        pass

  for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]:
    for p in GetAllAdb():
      try:
        logging.info('kill %d %d (%s [%s])', sig, p.pid, p.name,
                     ' '.join(p.cmdline))
        p.send_signal(sig)
      except (psutil.NoSuchProcess, psutil.AccessDenied):
        pass
  for p in GetAllAdb():
    try:
      logging.error('Unable to kill %d (%s [%s])', p.pid, p.name,
                    ' '.join(p.cmdline))
    except (psutil.NoSuchProcess, psutil.AccessDenied):
      pass
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_process_iter(self):
        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
        sproc = get_test_subprocess()
        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])

        with mock.patch('psutil.Process',
                        side_effect=psutil.NoSuchProcess(os.getpid())):
            self.assertEqual(list(psutil.process_iter()), [])
        with mock.patch('psutil.Process',
                        side_effect=psutil.AccessDenied(os.getpid())):
            with self.assertRaises(psutil.AccessDenied):
                list(psutil.process_iter())
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_process_iter(self):
        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
        sproc = get_test_subprocess()
        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])

        with mock.patch('psutil.Process',
                        side_effect=psutil.NoSuchProcess(os.getpid())):
            self.assertEqual(list(psutil.process_iter()), [])
        with mock.patch('psutil.Process',
                        side_effect=psutil.AccessDenied(os.getpid())):
            with self.assertRaises(psutil.AccessDenied):
                list(psutil.process_iter())
项目:scanpy    作者:theislab    | 项目源码 | 文件源码
def get_used_files():
    """Get files used by processes with name scanpy."""
    import psutil
    loop_over_scanpy_processes = (proc for proc in psutil.process_iter()
                                  if proc.name() == 'scanpy')
    filenames = []
    for proc in loop_over_scanpy_processes:
        try:
            flist = proc.open_files()
            for nt in flist:
                filenames.append(nt.path)
        # This catches a race condition where a process ends
        # before we can examine its files
        except psutil.NoSuchProcess as err:
            pass
    return set(filenames)
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def kill_proc(procname):
    done = False
    for proc in psutil.process_iter():
        process = psutil.Process(proc.pid)
        if process.name() == procname:
            try:
                process.terminate()
                process.wait(timeout=3)
                done = True
            except psutil.AccessDenied:
                print "Error: Access Denied to terminate %s" % procname
            except psutil.NoSuchProcess:
                pass
            except psutil.TimeoutExpired:
                if proz['killcount'] == 2:
                    print "Error: Terminating of %s failed! (tried 3 times)" % procname
                else:
                    print "Error: Terminating of %s took to long.. retrying" % procname
                    proz['killcount'] += 1
                    kill_proc(procname)
            break
    if done:
        print "%s terminated!" % procname
项目:jkutils    作者:joxeankoret    | 项目源码 | 文件源码
def check_cpu(self):
    while True:
      try:
        if self.pid is None:
          time.sleep(0.2)
          continue

        proc = psutil.Process(self.pid)
        cpu = 0
        l = []
        for x in xrange(20):
          tmp = int(proc.cpu_percent(interval=0.1))
          cpu += tmp
          l.append(tmp)

        if cpu is not None and (cpu <= 100 or l.count(0) > 10):
          log("CPU at 0%, killing")
          self.cpu_killed = True
          self.do_kill()
          break
        else:
          time.sleep(0.5)
      except psutil.NoSuchProcess:
        break
项目:ppapi    作者:PPAPI    | 项目源码 | 文件源码
def all_running_processes_for_case(self, _filter):
        procs = []
        for p in psutil.process_iter():
            try:
                if psutil.pid_exists(p.pid):
                    if _filter in p.cwd(): 
                        procs.append({"run": p.cwd() + " " + p.name(),"cmd":p.cmdline()})
            except (psutil.AccessDenied):
                pass
            except (psutil.NoSuchProcess):
                pass
        return procs

    ##
    # Function to kill all running processes for one case
    #  @param _filter search filter <string>
    #  @retval list of all killed processes <list>
项目:ppapi    作者:PPAPI    | 项目源码 | 文件源码
def kill_all_running_processes_for_case(self, _filter):
        procs = []
        for p in psutil.process_iter():
            try:
                if psutil.pid_exists(p.pid):
                    if _filter in p.cwd():
                        procs.append({"run": p.cwd() + " " + p.name()})
                        self.kill_proc_tree(p.pid)
            except (psutil.AccessDenied):
                pass
            except (psutil.NoSuchProcess):
                pass
        return procs

    ##
    # Function to retrieve all processes for one case (running and completed)
    #  @param _case case <string>
    #  @retval list of all processes <list>
项目:s2e-env    作者:S2E    | 项目源码 | 文件源码
def _check_virtualbox():
    """
    Check if VirtualBox is running.

    VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must
    *not* be running together with S2E.
    """
    # Adapted from https://github.com/giampaolo/psutil/issues/132#issuecomment-44017679
    # to avoid race conditions
    for proc in psutil.process_iter():
        try:
            if proc.name == 'VBoxHeadless':
                raise CommandError('S2E uses KVM to build images. VirtualBox '
                                   'is currently running, which is not '
                                   'compatible with KVM. Please close all '
                                   'VirtualBox VMs and try again')
        except NoSuchProcess:
            pass
项目:lockex    作者:rapid7    | 项目源码 | 文件源码
def kill(pid):
    '''
    Kill a pid
    '''
    process = psutil.Process(pid)
    try:
        for proc in process.children(recursive=True) + [process]:
            try:
                log.info("Killing pid={0}".format(proc.pid))
                proc.kill()
                time.sleep(0.1)
                proc.terminate()
            except psutil.NoSuchProcess as exc:
                log.error(exc)
    except AttributeError:
        log.info("Killing pid={0}".format(process.pid))
        process.kill()
        time.sleep(0.1)
        try:
            proc.terminate()
        except UnboundLocalError:
            pass
项目:SafeEyes    作者:slgobinath    | 项目源码 | 文件源码
def __running():
    """
    Check if SafeEyes is already running.
    """
    process_count = 0
    for proc in psutil.process_iter():
        if not proc.cmdline:
            continue
        try:
            # Check if safeeyes is in process arguments
            if callable(proc.cmdline):
                # Latest psutil has cmdline function
                cmd_line = proc.cmdline()
            else:
                # In older versions cmdline was a list object
                cmd_line = proc.cmdline
            if ('python3' in cmd_line[0] or 'python' in cmd_line[0]) and ('safeeyes' in cmd_line[1] or 'safeeyes' in cmd_line):
                process_count += 1
                if process_count > 1:
                    return True

        # Ignore if process does not exist or does not have command line args
        except (IndexError, psutil.NoSuchProcess):
            pass
    return False
项目:cassandra-dtest    作者:apache    | 项目源码 | 文件源码
def kill_windows_cassandra_procs():
    # On Windows, forcefully terminate any leftover previously running cassandra processes. This is a temporary
    # workaround until we can determine the cause of intermittent hung-open tests and file-handles.
    if is_win():
        try:
            import psutil
            for proc in psutil.process_iter():
                try:
                    pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline'])
                except psutil.NoSuchProcess:
                    pass
                else:
                    if (pinfo['name'] == 'java.exe' and '-Dcassandra' in pinfo['cmdline']):
                        print 'Found running cassandra process with pid: ' + str(pinfo['pid']) + '. Killing.'
                        psutil.Process(pinfo['pid']).kill()
        except ImportError:
            debug("WARN: psutil not installed. Cannot detect and kill "
                  "running cassandra processes - you may see cascading dtest failures.")
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def poll(interval):
    # sleep some time
    time.sleep(interval)
    procs = []
    procs_status = {}
    for p in psutil.process_iter():
        try:
            p.dict = p.as_dict(['username', 'nice', 'memory_info',
                                'memory_percent', 'cpu_percent',
                                'cpu_times', 'name', 'status'])
            try:
                procs_status[p.dict['status']] += 1
            except KeyError:
                procs_status[p.dict['status']] = 1
        except psutil.NoSuchProcess:
            pass
        else:
            procs.append(p)

    # return processes sorted by CPU percent usage
    processes = sorted(procs, key=lambda p: p.dict['cpu_percent'],
                       reverse=True)
    return (processes, procs_status)
项目:pyupdater-wx-demo    作者:wettenhj    | 项目源码 | 文件源码
def PidIsRunning(pid):
    """
    Check if a process with PID pid is running.
    """
    try:
        proc = psutil.Process(int(pid))
        if proc.status == psutil.STATUS_DEAD:
            return False
        if proc.status == psutil.STATUS_ZOMBIE:
            return False
        return True  # Assume other status are valid
    except psutil.NoSuchProcess:
        return False
项目:AntiRansom    作者:YJesus    | 项目源码 | 文件源码
def ownhandle() :
    my_regex = r".*" + re.escape(sys.argv[1]) + r".*"

    regex = re.compile(my_regex, re.IGNORECASE)

    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid'])
        except psutil.NoSuchProcess:
            pass
        else:
            #print pinfo['pid']
            try:
                proci = psutil.Process(pinfo['pid'])
                for files in proci.open_files() :
                    #print files
                    #handles = re.match(my_regex, files, re.IGNORECASE)
                    match = regex.search(str(files))

                    #print match

                    if match is not None and pinfo['pid'] not in safepids :

                        return(pinfo['pid'])
            except :
                pass
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def t5(pretty, factory):
    pipe = Pipe()
    p = P2(pipe)
    p.start()
    factory.processes.append(p)

    gc_pid = pipe.get()

    try:
        proc = psutil.Process(gc_pid)
    except Exception, e:
        print('FAIL %s: could not query grandchild: %s' % (pretty, e))
        return False

    os.kill(p.pid, signal.SIGKILL)

    ok = False
    for i in range(3):
        try:
            proc = psutil.Process(gc_pid)
        except psutil.NoSuchProcess:
            ok = True
            break
        time.sleep(0.5)

    if not ok:
        print('FAIL %s: could query grandchild: %s' % (pretty, proc))
        return False

    return True

# grandchild does not die when child dies if PDEATHSIG is unset?