本文整理汇总了Python中psutil.Process方法的典型用法代码示例。如果您正苦于以下问题:Python psutil.Process方法的具体用法?Python psutil.Process怎么用?Python psutil.Process使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类psutil
的用法示例。
在下文中一共展示了psutil.Process方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def __init__(self, pid, idle_limit=None, memory_limit=None, time_limit=None):
self.limit = {"idle":idle_limit,
"memory":memory_limit,
"time":time_limit}
self.check = {"idle":0,
"memory":0,
"time":0}
self.idle_start = None
try:
if isinstance(pid, psutil.Process):
self.ps = pid
else:
self.ps = psutil.Process(pid)
self.ps.get_cpu_percent(interval=0)
except psutil.NoSuchProcess:
self.ps = None
示例2: get_proc_run_time
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def get_proc_run_time():
#Debug session time: Tue Aug 21 16:27:31.971 2012 (UTC - 4:00)
#System Uptime: 5 days 13:06:34.062
#Process Uptime: 0 days 0:00:02.718
#Kernel time: 0 days 0:00:00.000
#User time: 0 days 0:00:00.000
duration = 0
for line in pykd.dbgCommand(".time").splitlines()[-2:]:
line = line.strip().split()
duration += int(line[2]) * 86400 # days
line = line[-1].split('.')
duration += float("0.%s" % line[-1])
line = line[0].split(':')
duration += int(line[0]) * 3600 # hours
duration += int(line[1]) * 60 # minutes
duration += int(line[2]) # seconds
return duration
示例3: get_mem_usage
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def get_mem_usage(pid):
try:
proc = psutil.Process(pid)
tmp_val = proc.get_memory_info()[0]
except psutil.NoSuchProcess:
tmp_val = 0
return tmp_val
示例4: get_memory_usage
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def get_memory_usage():
"""
Get current process memory usage. This is method requires
psutils to be installed.
:Returns:
#. memory (float, None): The memory usage in Megabytes.
When psutils is not installed, None is returned.
"""
try:
import psutil
process = psutil.Process(os.getpid())
memory = float( process.memory_info()[0] ) / float(2 ** 20)
except:
LOGGER.warn("memory usage cannot be profiled. psutil is not installed. pip install psutil")
memory = None
return memory
示例5: submit_batch_to_process
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def submit_batch_to_process(batch, session):
def run_batch(tests, finished_signal):
for i, test in enumerate(tests):
next_test = tests[i + 1] if i + 1 < len(tests) else None
test.config.hook.pytest_runtest_protocol(item=test, nextitem=next_test)
if session.shouldstop:
raise session.Interrupted(session.shouldstop)
finished_signal.set()
proc = multiprocessing.Process(target=run_batch, args=(batch['tests'], synchronization['trigger_process_loop']))
with synchronization['processes_lock']:
proc.start()
pid = proc.pid
synchronization['running_pids'][pid] = True
synchronization['processes'][pid] = proc
synchronization['trigger_process_loop'].set()
示例6: kill_windows_cassandra_procs
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [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.")
示例7: setUp
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def setUp(self):
if not hasattr(self, "logger"):
self.logger = logging.getLogger(__name__)
self.channel_id = os.environ[SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID]
self.bot_token = os.environ[SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN]
if not hasattr(self, "cpu_monitor") or not TestRTMClient.cpu_monitor.is_alive():
def run_cpu_monitor(self):
self.logger.debug("Starting CPU monitor in another thread...")
TestRTMClient.cpu_usage = 0
while True:
p = psutil.Process(os.getpid())
current_cpu_usage: float = p.cpu_percent(interval=0.5)
self.logger.debug(current_cpu_usage)
if current_cpu_usage > TestRTMClient.cpu_usage:
TestRTMClient.cpu_usage = current_cpu_usage
TestRTMClient.cpu_monitor = threading.Thread(target=run_cpu_monitor, args=[self])
TestRTMClient.cpu_monitor.setDaemon(True)
TestRTMClient.cpu_monitor.start()
self.rtm_client = None
self.web_client = None
示例8: memory_usage
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def memory_usage():
"""Return memory usage of the running python process.
You can ``pip install psutil`` if you get only ``-1.``.
Returns
-------
mem : float
Currently used memory in megabytes. ``-1.`` if no way to read out.
"""
try:
import resource # linux-only
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
except ImportError:
pass
try:
import psutil
proc = psutil.Process()
return proc.memory_info().rss / 1024**2
except ImportError:
pass
warnings.warn("No tool to determine memory_usage")
return -1.
示例9: check_pidfile
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def check_pidfile(filepath, match_name, endpoint_name):
""" Helper function to identify possible dead endpoints
"""
if not os.path.exists(filepath):
return
older_pid = int(open(filepath, 'r').read().strip())
try:
proc = psutil.Process(older_pid)
if proc.name() == match_name:
logger.info("Endpoint is already active")
except psutil.NoSuchProcess:
logger.info("A prior Endpoint instance appears to have been terminated without proper cleanup")
logger.info('''Please cleanup using:
$ funcx-endpoint stop {}'''.format(endpoint_name))
示例10: adaptive_model_qa
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def adaptive_model_qa(use_gpu, num_processes):
"""
PyTest Fixture for a Question Answering Inferencer based on PyTorch.
"""
try:
model = Inferencer.load(
"deepset/bert-base-cased-squad2",
task_type="question_answering",
batch_size=16,
num_processes=num_processes,
gpu=use_gpu,
)
yield model
finally:
if num_processes != 0:
# close the pool
# we pass join=True to wait for all sub processes to close
# this is because below we want to test if all sub-processes
# have exited
model.close_multiprocessing_pool(join=True)
# check if all workers (sub processes) are closed
current_process = psutil.Process()
children = current_process.children()
assert len(children) == 0
示例11: wrap_session
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def wrap_session(session, cpu_quota=None, load_quota=None):
"""Wraps the session limiting cpu quota."""
if load_quota is None:
load_quota = session.GetParameter("load_quota")
if cpu_quota is None:
cpu_quota = session.GetParameter("cpu_quota")
if cpu_quota == None and load_quota == None:
return session
# Store the process's current CPU utilization.
proc = psutil.Process()
cpu_times = proc.cpu_times()
start_time = cpu_times.user + cpu_times.system
state = dict(last=time.time(),
start_time=start_time,
proc=proc)
def quota_callback(*_, **__):
check_quota(state, cpu_quota, load_quota)
# Register our progress dispatcher.
session.progress.Register("quota", quota_callback)
return session
示例12: kill_process_tree
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def kill_process_tree(pid, include_parent=True):
try:
import psutil
except ImportError: # pragma: no cover
return
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
return
plasma_sock_dir = None
children = proc.children(recursive=True)
if include_parent:
children.append(proc)
for p in children:
try:
if 'plasma' in p.name():
plasma_sock_dir = next((conn.laddr for conn in p.connections('unix')
if 'plasma' in conn.laddr), None)
p.kill()
except psutil.NoSuchProcess: # pragma: no cover
pass
if plasma_sock_dir:
shutil.rmtree(plasma_sock_dir, ignore_errors=True)
示例13: kill_child_processes
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def kill_child_processes(parent_pid):
""" Kill all the subprocesses recursively """
try:
parent = psutil.Process(parent_pid)
except psutil.NoSuchProcess:
return
children = parent.children(recursive=True)
print(
"================================ SHUTTING DOWN CLUSTER ================================"
)
for process in children:
try:
print("SIGTERM >>> " + " ".join(process.cmdline()[1:]))
except Exception:
pass
process.send_signal(signal.SIGTERM)
process.wait()
示例14: get_alumni
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [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
示例15: remove_stale_alumni_pidfiles
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Process [as 别名]
def remove_stale_alumni_pidfiles(
alumni: Iterable[psutil.Process],
state_dir: str,
) -> None:
alumni_pids = [proc.pid for proc in alumni]
for pidfile in os.listdir(state_dir):
try:
pid = int(pidfile)
except ValueError:
log.warn('Ignoring invalid filename: %s' % pidfile)
continue
if pid in alumni_pids:
continue
log.info('Removing stale pidfile for %d', pid)
os.remove(os.path.join(state_dir, pidfile))