本文整理汇总了Python中psutil.Error方法的典型用法代码示例。如果您正苦于以下问题:Python psutil.Error方法的具体用法?Python psutil.Error怎么用?Python psutil.Error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类psutil
的用法示例。
在下文中一共展示了psutil.Error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_children_duplicates
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [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)))
示例2: test_children_duplicates
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [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]
if LINUX and pid == 0:
raise self.skipTest("PID 0")
p = psutil.Process(pid)
try:
c = p.children(recursive=True)
except psutil.AccessDenied: # windows
pass
else:
self.assertEqual(len(c), len(set(c)))
示例3: kill_all_child_processes
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def kill_all_child_processes(pid=None):
# get current process if pid not provided
include_parent = True
if not pid:
pid = os.getpid()
include_parent = False
print("\nLeaving process id {}".format(pid))
try:
parent = psutil.Process(pid)
except psutil.Error:
# could not find parent process id
return
for child in parent.children(recursive=True):
child.kill()
if include_parent:
parent.kill()
示例4: up
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def up(cluster_config_file, min_workers, max_workers, no_restart, restart_only,
yes, cluster_name):
"""Create or update a Ray cluster."""
if restart_only or no_restart:
assert restart_only != no_restart, "Cannot set both 'restart_only' " \
"and 'no_restart' at the same time!"
if urllib.parse.urlparse(cluster_config_file).scheme in ("http", "https"):
try:
response = urllib.request.urlopen(cluster_config_file, timeout=5)
content = response.read()
file_name = cluster_config_file.split("/")[-1]
with open(file_name, "wb") as f:
f.write(content)
cluster_config_file = file_name
except urllib.error.HTTPError as e:
logger.info("Error downloading file: ", e)
create_or_update_cluster(cluster_config_file, min_workers, max_workers,
no_restart, restart_only, yes, cluster_name)
示例5: _kill_all_child_processes
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def _kill_all_child_processes(send_kill=False):
# get current process if pid not provided
pid = os.getpid()
try:
parent = psutil.Process(pid)
except psutil.Error:
# could not find parent process id
return
for child in parent.children(recursive=True):
if send_kill:
child.kill()
else:
child.terminate()
# kill ourselves
if send_kill:
parent.kill()
else:
parent.terminate()
示例6: terminate
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def terminate(self):
# return codes:
# 0 no work to do
# 1 terminated
# -1 failed to terminate
if not self.pid or not self.isrunning():
return 0
timeout = 20
try:
proc = psutil.Process(self.pid)
proc.terminate()
try:
proc.wait(timeout=timeout/2)
except psutil.TimeoutExpired:
proc.kill()
proc.wait(timeout=timeout/2)
except psutil.Error:
return -1
return 1
示例7: _kill_process
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def _kill_process(self):
with self._lock:
if self._process is not None and self._process.is_running() and not self._process_children:
try:
self._process.suspend() # Suspend the process before getting list of childrens
except psutil.Error as e:
logger.info('Failed to suspend the process: %s', e.msg)
try:
self._process_children = self._process.children(recursive=True)
except psutil.Error:
pass
try:
self._process.kill()
logger.warning('Killed %s because it was still running', self._process_cmd)
except psutil.NoSuchProcess:
pass
except psutil.AccessDenied as e:
logger.warning('Failed to kill the process: %s', e.msg)
示例8: test_callback_executor
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def test_callback_executor(self, mock_popen):
mock_popen.return_value.children.return_value = []
mock_popen.return_value.is_running.return_value = True
ce = CallbackExecutor()
ce._kill_children = Mock(side_effect=Exception)
self.assertIsNone(ce.call([]))
ce.join()
self.assertIsNone(ce.call([]))
mock_popen.return_value.kill.side_effect = psutil.AccessDenied()
self.assertIsNone(ce.call([]))
ce._process_children = []
mock_popen.return_value.children.side_effect = psutil.Error()
mock_popen.return_value.kill.side_effect = psutil.NoSuchProcess(123)
self.assertIsNone(ce.call([]))
mock_popen.side_effect = Exception
ce = CallbackExecutor()
ce._condition.wait = Mock(side_effect=[None, Exception])
self.assertIsNone(ce.call([]))
ce.join()
示例9: test_signal_kill
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def test_signal_kill(self, mock_kill, mock_children, mock_suspend):
proc = PostmasterProcess(123)
# all processes successfully stopped
mock_children.return_value = [Mock()]
mock_children.return_value[0].kill.side_effect = psutil.Error
self.assertTrue(proc.signal_kill())
# postmaster has gone before suspend
mock_suspend.side_effect = psutil.NoSuchProcess(123)
self.assertTrue(proc.signal_kill())
# postmaster has gone before we got a list of children
mock_suspend.side_effect = psutil.Error()
mock_children.side_effect = psutil.NoSuchProcess(123)
self.assertTrue(proc.signal_kill())
# postmaster has gone after we got a list of children
mock_children.side_effect = psutil.Error()
mock_kill.side_effect = psutil.NoSuchProcess(123)
self.assertTrue(proc.signal_kill())
# failed to kill postmaster
mock_kill.side_effect = psutil.AccessDenied(123)
self.assertFalse(proc.signal_kill())
示例10: _get_field
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def _get_field(self, field_name):
try:
result = getattr(self._proc, field_name)
if callable(result):
result = result()
return result
except psutil.Error:
# Some processes do not have environ defined.
if field_name == "environ":
return {}
return None
except AttributeError:
return None
示例11: discord_process
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def discord_process():
executables = {}
for proc in psutil.process_iter():
try:
(path, exe) = os.path.split(proc.exe())
except (psutil.Error, OSError):
pass
else:
if exe.startswith('Discord') and not exe.endswith('Helper'):
entry = executables.get(exe)
if entry is None:
entry = executables[exe] = DiscordProcess(path=path, exe=exe)
entry.processes.append(proc)
if len(executables) == 0:
raise RuntimeError('Could not find Discord executable.')
if len(executables) == 1:
r = executables.popitem()
print('Found {0.exe} under {0.path}'.format(r[1]))
return r[1]
lookup = list(executables)
for index, exe in enumerate(lookup):
print('%s: Found %s' % (index, exe))
while True:
index = input("Discord executable to use (number): ")
try:
index = int(index)
except ValueError as e:
print('Invalid index passed')
else:
if index >= len(lookup) or index < 0:
print('Index too big (or small)')
else:
key = lookup[index]
return executables[key]
示例12: test_exe
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def test_exe(self):
for p in psutil.process_iter():
try:
self.assertEqual(os.path.basename(p.exe()), p.name())
except psutil.Error:
pass
示例13: run
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def run(self):
'''
Runs until no longer valid (app moved, not master, etc), or repeated errors over self.threshold
'''
while self._run:
start_time = time.time()
if self.failcount >= self.threshold:
self.logger.error('Node stat reporter thread for Monaco DB is sleeping to prevent thrashing')
time.sleep(15)
# Collect/Publish stats
try:
info = self.r.info()
for stat in ['connected_slaves', 'used_memory', 'connected_clients', 'instantaneous_ops_per_sec']:
PUBLISHER.publish_monaco_stat(self.node_id, stat, info[stat])
proc = self.redmgr.instance_proc('6379')
if proc:
PUBLISHER.publish_monaco_stat(self.node_id, 'cpu_percent', proc.cpu_percent(interval=self.interval))
except redis.ConnectionError:
self.logger.info('Redis error accessing Monaco DB info')
del self.r
self.r = redis.StrictRedis(port=config.config['mgmt_port'])
except psutil.Error, err:
self.logger.info('psutil error - %s', repr(err))
self.failcount += 1
except Exception, exc:
self.logger.exception(exc)
self.failcount += 1
示例14: proc_info
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def proc_info(pid):
tcase = PsutilTestCase()
def check_exception(exc, proc, name, ppid):
tcase.assertEqual(exc.pid, pid)
tcase.assertEqual(exc.name, name)
if isinstance(exc, psutil.ZombieProcess):
if exc.ppid is not None:
tcase.assertGreaterEqual(exc.ppid, 0)
tcase.assertEqual(exc.ppid, ppid)
elif isinstance(exc, psutil.NoSuchProcess):
tcase.assertProcessGone(proc)
str(exc)
assert exc.msg
def do_wait():
if pid != 0:
try:
proc.wait(0)
except psutil.Error as exc:
check_exception(exc, proc, name, ppid)
try:
proc = psutil.Process(pid)
d = proc.as_dict(['ppid', 'name'])
except psutil.NoSuchProcess:
return {}
name, ppid = d['name'], d['ppid']
info = {'pid': proc.pid}
ns = process_namespace(proc)
with proc.oneshot():
for fun, fun_name in ns.iter(ns.getters, clear_cache=False):
try:
info[fun_name] = fun()
except psutil.Error as exc:
check_exception(exc, proc, name, ppid)
continue
do_wait()
return info
示例15: print_tree
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Error [as 别名]
def print_tree(parent, tree, indent=''):
try:
name = psutil.Process(parent).name()
except psutil.Error:
name = "?"
print(parent, name)
if parent not in tree:
return
children = tree[parent][:-1]
for child in children:
sys.stdout.write(indent + "|- ")
print_tree(child, tree, indent + "| ")
child = tree[parent][-1]
sys.stdout.write(indent + "`_ ")
print_tree(child, tree, indent + " ")