Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_name(self):
name = psutil.Process().name()
with mock.patch("psutil._psplatform.cext.proc_exe",
side_effect=psutil.AccessDenied(os.getpid())) as fun:
psutil.Process().name() == name
assert fun.called
for i, thread in enumerate(pinfo['threads']):
if not verbose and i >= NON_VERBOSE_ITERATIONS:
print_("", "[...]")
break
print_('', template % thread)
print_('', "total=%s" % len(pinfo['threads']))
else:
print_('threads', '')
if hasattr(proc, "rlimit"):
res_names = [x for x in dir(psutil) if x.startswith("RLIMIT")]
resources = []
for res_name in res_names:
try:
soft, hard = proc.rlimit(getattr(psutil, res_name))
except psutil.AccessDenied:
pass
else:
resources.append((res_name, soft, hard))
if resources:
template = "%-12s %15s %15s"
print_("res-limits", template % ("RLIMIT", "SOFT", "HARD"))
for res_name, soft, hard in resources:
if soft == psutil.RLIM_INFINITY:
soft = "infinity"
if hard == psutil.RLIM_INFINITY:
hard = "infinity"
print_('', template % (
RLIMITS_MAP.get(res_name, res_name), soft, hard))
if hasattr(proc, "environ") and pinfo['environ']:
template = "%-25s %s"
def closeDispyScheduler():
''' Close the Dispy Scheduler '''
global popen
if popen != None:
popen.terminate()
popen.wait()
popen=None
else:
for proc in psutil.process_iter():
try:
cmdline = proc.cmdline()
except (PermissionError, psutil.AccessDenied):
continue
for arg in cmdline:
if re.search('dispyscheduler.py',arg):
proc.send_signal(psutil.signal.SIGTERM)
# https://psutil.readthedocs.io/en/latest/#psutil.Process.open_files
if wait_files.intersection({true_path(x.path) for x in proc.info["open_files"]}):
try:
procs.append(psutil.Process(proc.info["pid"]))
except (psutil.AccessDenied, psutil.NoSuchProcess): # pragma: no cover
pass
# only check previously blocking processes
while procs:
try:
if wait_files.intersection({true_path(x.path) for x in procs[-1].open_files()}):
if deadline <= time.time():
log.debug("wait_on_files(timeout=%d) timed out", timeout)
return False
time.sleep(poll_rate)
continue
except (psutil.AccessDenied, psutil.NoSuchProcess): # pragma: no cover
pass
procs.pop()
return True
def update(self):
"""
Update the list of BrewPi processes by receiving them from the system with psutil.
Returns: list of BrewPiProcess objects
"""
bpList = []
matching = []
# some OS's (OS X) do not allow processes to read info from other processes.
try:
matching = [p for p in psutil.process_iter() if any('python' in p.name() and 'brewpi.py'in s for s in p.cmdline())]
except psutil.AccessDenied:
pass
for p in matching:
bp = self.parseProcess(p)
if bp:
bpList.append(bp)
self.list = bpList
return self.list
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
def get_value(self, process):
result = dict()
for k in process_handlers:
handler = process_handlers[k]
if hasattr(handler, "method") and handler.method is not None: # property is defined for current OS
try:
if isinstance(handler, ProcessMethodCommandHandler):
v = handler.handle('', process)
self.add_to_dict(result, k, v, self.join)
elif self.subproperties:
if isinstance(handler, ProcessMethodIndexCommandHandler) or isinstance(handler, ProcessMethodTupleCommandHandler):
v = handler.handle('*', process)
self.add_to_dict(result, k, v, self.join)
except psutil.AccessDenied: # just skip with property
pass
return string_from_dict_optionally(result, self.join)
# since the ones returned by psutil would not be aware of symlinks in the
# path we should also get realpath for path
path = realpath(path)
for proc in psutil.process_iter():
try:
open_paths = [p.path for p in proc.open_files()] + [proc.cwd()]
for p in open_paths:
# note: could be done more efficiently so we do not
# renormalize path over and over again etc
if path_startswith(p, path):
files[p] = proc
# Catch a race condition where a process ends
# before we can examine its files
except psutil.NoSuchProcess:
pass
except psutil.AccessDenied:
pass
if files and log_open:
lgr.log(log_open, "Open files under %s: %s", path, files)
return files
def process(param):
pack = MapPack()
protoList = pack.newList("Proto")
localList = pack.newList("LocalAddr")
remoteList = pack.newList("RemoteAddr")
statusList = pack.newList("Status")
pidList = pack.newList("Pid")
nameList = pack.newList("ProgramName")
for p in psutil.process_iter():
name = '?'
try:
name = p.name()
cons = p.connections(kind='inet')
except psutil.AccessDenied:
protoList.addStr(AD)
localList.addStr(AD)
remoteList.addStr(AD)
statusList.addStr(AD)
pidList.addStr(str(p.pid))
nameList.addStr(name)
except psutil.NoSuchProcess:
continue
else:
for c in cons:
raddr = ""
laddr = "%s:%s" % (c.laddr)
if c.raddr:
raddr = "%s:%s" % (c.raddr)
protoList.addStr(proto_map[(c.family, c.type)])
localList.addStr(laddr)
def __get_process_stats__(self, proc):
"""
Get process (proc) statistics
"""
procstat = {}
try:
procstat['name'] = proc.name
except psutil.AccessDenied:
# Can not get the process name ?
# then no need to retreive others stats
# so exit...
return {}
procstat['pid'] = proc.pid
try:
procstat['cmdline'] = " ".join(proc.cmdline)
except psutil.AccessDenied:
procstat['cmdline'] = "?"
try:
procstat['memory_info'] = proc.get_memory_info()
except psutil.AccessDenied:
procstat['memory_info'] = {}