python类NoSuchProcess()的实例源码

file_sharing.py 文件源码 项目:idiot 作者: snare 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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")
pipelines_manager.py 文件源码 项目:pypers 作者: frankosan 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
bb_device_status_check.py 文件源码 项目:buildroot 作者: flutter 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
test_linux.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
test_system.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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())
test_linux.py 文件源码 项目:FancyWord 作者: EastonLee 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
test_system.py 文件源码 项目:FancyWord 作者: EastonLee 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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())
readwrite.py 文件源码 项目:scanpy 作者: theislab 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
interrupt_switch_prog.py 文件源码 项目:Sample-Code 作者: meigrafd 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
process.py 文件源码 项目:jkutils 作者: joxeankoret 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
processes.py 文件源码 项目:ppapi 作者: PPAPI 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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>
processes.py 文件源码 项目:ppapi 作者: PPAPI 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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>
image_build.py 文件源码 项目:s2e-env 作者: S2E 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
execute.py 文件源码 项目:lockex 作者: rapid7 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
__main__.py 文件源码 项目:SafeEyes 作者: slgobinath 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
dtest.py 文件源码 项目:cassandra-dtest 作者: apache 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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.")
top.py 文件源码 项目:LinuxBashShellScriptForOps 作者: DingGuodong 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
test_freeze_update_available.py 文件源码 项目:pyupdater-wx-demo 作者: wettenhj 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
monit.py 文件源码 项目:AntiRansom 作者: YJesus 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
process.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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?


问题


面经


文章

微信
公众号

扫码关注公众号