本文整理匯總了Python中psutil.process_iter方法的典型用法代碼示例。如果您正苦於以下問題:Python psutil.process_iter方法的具體用法?Python psutil.process_iter怎麽用?Python psutil.process_iter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類psutil
的用法示例。
在下文中一共展示了psutil.process_iter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: check
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def check(self):
"""
Check that the service is running and consistent with pid file(s).
Returns True or False.
"""
# Set of pids (strings) where the command string matches what we are
# looking for.
detected_pids = set()
# Set of pids (strings) that are both running processes and found in
# pid files.
consistent_pids = set()
# Search for running processes that match our command string.
for proc in psutil.process_iter():
try:
if self.cmdstring in proc.name():
detected_pids.add(str(proc.pid))
# We could also get psutil.ZombieProcess or
# psutil.AccessDenied. We want those to be logged.
except psutil.NoSuchProcess:
pass
# Search for pid file(s) and check consistency.
for pidfile in self.pidfiles:
for path in glob.iglob(pidfile):
with open(path, 'r') as source:
pid = source.read().strip()
if pid in detected_pids:
consistent_pids.add(pid)
else:
# Delete the stale pid file.
os.remove(path)
return len(consistent_pids) > 0
示例2: _maybe_get_running_openvpn
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def _maybe_get_running_openvpn():
"""
Looks for previously running openvpn instances.
:rtype: psutil Process
"""
openvpn = None
for p in psutil.process_iter():
try:
# This needs more work, see #3268, but for the moment
# we need to be able to filter out arguments in the form
# --openvpn-foo, since otherwise we are shooting ourselves
# in the feet.
cmdline = p.cmdline()
if any(map(lambda s: s.find(
"LEAPOPENVPN") != -1, cmdline)):
openvpn = p
break
except psutil.AccessDenied:
pass
return openvpn
示例3: kill_windows_cassandra_procs
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
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:
logger.debug("WARN: psutil not installed. Cannot detect and kill "
"running cassandra processes - you may see cascading dtest failures.")
示例4: is_up
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def is_up(self):
"""
Checks if a polkit daemon is running.
:return: True if it's running, False if it's not.
:rtype: boolean
"""
# Note that gnome-shell does not uses a separate process for the
# polkit-agent, it uses a polkit-agent within its own process so we
# can't ps-grep a polkit process, we can ps-grep gnome-shell itself.
if os.getuid() == 0:
# if you're running as root, it's your problem, not mine.
return True
running = False
for proc in psutil.process_iter():
if any((pk in proc.name() for pk in polkit.POLKIT_PROC_NAMES)):
running = True
break
return running
示例5: start_app
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def start_app():
from leap.bitmask.util import STANDALONE
mypid = os.getpid()
# Kill a previously-running process
for proc in psutil.process_iter():
if proc.name() == PROCNAME and proc.pid != mypid:
proc.kill()
# Allow the frozen binary in the bundle double as the cli entrypoint
# Why have only a user interface when you can have two?
if STANDALONE and len(sys.argv) > 1:
if sys.argv[1] == 'bitmask_helpers':
from leap.bitmask.vpn.helpers import main
return main()
from leap.bitmask.cli import bitmask_cli
return bitmask_cli.main()
reset_authtoken()
launch_gui()
示例6: check_stale_pidfile
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def check_stale_pidfile():
def is_pid_running(pidno):
return 1 == len(
filter(lambda p: p.pid == int(pidno), psutil.process_iter()))
pidno = None
pidfile = os.path.join(get_path_prefix(), 'leap', 'bitmaskd.pid')
try:
if os.path.isfile(pidfile):
with open(pidfile, 'r') as pid_fd:
pidno = pid_fd.readline().strip()
if pidno and pidno.isdigit():
if not is_pid_running(pidno):
os.unlink(pidfile)
except Exception as exc:
print('[bitmask] Error while removing stale file: %r' % exc)
示例7: get_alumni
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def get_alumni(
username: str,
) -> Iterator[psutil.Process]:
main_pid = get_main_pid()
for proc in psutil.process_iter():
if proc.name() != 'haproxy-synapse':
continue
if proc.username() != username:
continue
if proc.pid == main_pid:
continue
yield proc
示例8: crawl_connections
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def crawl_connections():
created_since = -1
proc_list = psutil.process_iter()
for p in proc_list:
pid = (p.pid() if hasattr(p.pid, '__call__') else p.pid)
status = (p.status() if hasattr(p.status, '__call__'
) else p.status)
if status == psutil.STATUS_ZOMBIE:
continue
create_time = (
p.create_time() if hasattr(
p.create_time,
'__call__') else p.create_time)
name = (p.name() if hasattr(p.name, '__call__') else p.name)
if create_time <= created_since:
continue
for conn in p.get_connections():
yield crawl_single_connection(conn, pid, name)
示例9: __init__
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def __init__(self, name, kernel, distro, arch, host_namespace='',
pid=None):
VirtualMachine.__init__(self, name, kernel, distro, arch,
host_namespace=host_namespace)
if pid is None:
# Find the pid of the QEMU process running virtual machine `name`
self.pid = None
for proc in psutil.process_iter():
if 'qemu' in proc.name():
line = proc.cmdline()
if name == line[line.index('-name') + 1]:
self.pid = proc.pid
if self.pid is None:
raise ValueError('no VM with vm_name: %s' % name)
else:
self.pid = pid
示例10: test_ppid
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def test_ppid(self):
if hasattr(os, 'getppid'):
self.assertEqual(psutil.Process().ppid(), os.getppid())
this_parent = os.getpid()
sproc = get_test_subprocess()
p = psutil.Process(sproc.pid)
self.assertEqual(p.ppid(), this_parent)
# no other process is supposed to have us as parent
reap_children(recursive=True)
if APPVEYOR:
# Occasional failures, see:
# https://ci.appveyor.com/project/giampaolo/psutil/build/
# job/0hs623nenj7w4m33
return
for p in psutil.process_iter():
if p.pid == sproc.pid:
continue
# XXX: sometimes this fails on Windows; not sure why.
self.assertNotEqual(p.ppid(), this_parent, msg=p)
示例11: test_children_duplicates
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def test_children_duplicates(self):
# find the process which has the highest number of children
table = collections.defaultdict(int)
for p in psutil.process_iter():
try:
table[p.ppid()] += 1
except psutil.Error:
pass
# this is the one, now let's make sure there are no duplicates
pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
p = psutil.Process(pid)
try:
c = p.children(recursive=True)
except psutil.AccessDenied: # windows
pass
else:
self.assertEqual(len(c), len(set(c)))
示例12: test_process_iter
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
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())
示例13: test_prcess_iter_w_params
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def test_prcess_iter_w_params(self):
for p in psutil.process_iter(attrs=['pid']):
self.assertEqual(list(p.info.keys()), ['pid'])
with self.assertRaises(ValueError):
list(psutil.process_iter(attrs=['foo']))
with mock.patch("psutil._psplatform.Process.cpu_times",
side_effect=psutil.AccessDenied(0, "")) as m:
for p in psutil.process_iter(attrs=["pid", "cpu_times"]):
self.assertIsNone(p.info['cpu_times'])
self.assertGreaterEqual(p.info['pid'], 0)
assert m.called
with mock.patch("psutil._psplatform.Process.cpu_times",
side_effect=psutil.AccessDenied(0, "")) as m:
flag = object()
for p in psutil.process_iter(
attrs=["pid", "cpu_times"], ad_value=flag):
self.assertIs(p.info['cpu_times'], flag)
self.assertGreaterEqual(p.info['pid'], 0)
assert m.called
示例14: get_runtime_snapshot
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def get_runtime_snapshot():
"""Return a list of current processes and their command lines as string."""
process_strings = []
for process in psutil.process_iter():
try:
process_info = process.as_dict(attrs=['name', 'cmdline', 'pid', 'ppid'])
process_string = '{name} ({pid}, {ppid})'.format(
name=process_info['name'],
pid=process_info['pid'],
ppid=process_info['ppid'])
process_cmd_line = process_info['cmdline']
if process_cmd_line:
process_string += ': {cmd_line}'.format(
cmd_line=(' '.join(process_cmd_line)))
process_strings.append(process_string)
except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
# Ignore the error, use whatever info is available for access.
pass
return '\n'.join(sorted(process_strings))
示例15: verify_instances
# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import process_iter [as 別名]
def verify_instances(self):
'''
returns ([instances that should be but aren't running, ...], [instances that shouldn't be but are running, ...])
'''
extra_instances = []
app_pattern = re.compile(r'0\.0\.0\.0:([0-9]*)')
expected_instances = self.list_instances()
with self.lock:
for proc in psutil.process_iter():
if proc.name() == 'redis-server' and proc.ppid() == 1:
match = app_pattern.search(proc.cmdline()[0])
if match and match.group(1) != '6379':
instance = match.group(1)
if not instance in expected_instances:
extra_instances.append(instance)
elif instance in expected_instances:
expected_instances.remove(instance)
return (expected_instances, extra_instances)