本文整理汇总了Python中psutil.Process类的典型用法代码示例。如果您正苦于以下问题:Python Process类的具体用法?Python Process怎么用?Python Process使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Process类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_infinite_loop
def test_infinite_loop(self):
# Given
user_answer = ("#!/bin/bash\nwhile [ 1 ] ;"
" do echo "" > /dev/null ; done")
kwargs = {
'metadata': {
'user_answer': user_answer,
'file_paths': self.file_paths,
'partial_grading': False,
'language': 'bash'
},
'test_case_data': self.test_case_data,
}
# When
grader = Grader(self.in_dir)
result = grader.evaluate(kwargs)
# Then
self.assertFalse(result.get("success"))
self.assert_correct_output(self.timeout_msg,
result.get("error")[0]["message"]
)
parent_proc = Process(os.getpid()).children()
if parent_proc:
children_procs = Process(parent_proc[0].pid)
self.assertFalse(any(children_procs.children(recursive=True)))
示例2: get_soledad_server_pid
def get_soledad_server_pid():
output = check_output(['pidof', 'python'])
for pid in output.split():
proc = Process(int(pid))
cmdline = proc.cmdline()
if args.issubset(set(cmdline)):
return int(pid)
示例3: main
def main(argv):
p = Popen(argv[1:])
try:
client = ExitCodeClient()
try:
proc = Process(pid=p.pid)
while p.poll() is None:
total_cpu_percent = proc.get_cpu_percent(interval=0)
for child_proc in proc.get_children(recursive=True):
total_cpu_percent += child_proc.get_cpu_percent(interval=0)
client.send_status(total_cpu_percent)
time.sleep(0.1) # recommended waiting period from psutil docs
except NoSuchProcess:
pass
except KeyboardInterrupt:
try:
p.terminate()
except OSError:
pass
client.send_status(LEDMode.Success if p.returncode == 0 else LEDMode.Error)
time.sleep(0.5) # Give server time to read value before connection closes
client.shutdown()
return p.returncode
示例4: test_infinite_loop
def test_infinite_loop(self):
# Given
user_answer = ("class Test {\n\tint square_num(int a)"
" {\n\t\twhile(0==0){\n\t\t}\n\t}\n}")
kwargs = {
'metadata': {
'user_answer': user_answer,
'file_paths': self.file_paths,
'partial_grading': False,
'language': 'java'
}, 'test_case_data': self.test_case_data,
}
# When
grader = Grader(self.in_dir)
result = grader.evaluate(kwargs)
# Then
self.assertFalse(result.get("success"))
self.assert_correct_output(self.timeout_msg,
result.get("error")[0]["message"]
)
parent_proc = Process(os.getpid()).children()
if parent_proc:
children_procs = Process(parent_proc[0].pid)
self.assertFalse(any(children_procs.children(recursive=True)))
示例5: test_infinite_loop
def test_infinite_loop(self):
# Given
user_answer = dedent("""
#include<stdio.h>
int main(void){
while(0==0){
printf("abc");}
}""")
kwargs = {
'metadata': {
'user_answer': user_answer,
'file_paths': self.file_paths,
'partial_grading': False,
'language': 'cpp'
}, 'test_case_data': self.test_case_data,
}
# When
grader = Grader(self.in_dir)
result = grader.evaluate(kwargs)
# Then
self.assertFalse(result.get("success"))
self.assert_correct_output(self.timeout_msg,
result.get("error")[0]["message"]
)
parent_proc = Process(os.getpid()).children()
if parent_proc:
children_procs = Process(parent_proc[0].pid)
self.assertFalse(any(children_procs.children(recursive=True)))
示例6: end_broker_process
def end_broker_process(self):
try:
broker_process = Process(self.broker.pid)
except NoSuchProcess:
return # was killed
# get stdout and stderr
select_config = [self.broker.stdout, self.broker.stderr], [], [], 0.1
stdout, stderr = [], []
result = select.select(*select_config)
while any(result):
if result[0]:
stdout.append(result[0][0].readline())
if result[1]:
stderr.append(result[1][0].readline())
result = select.select(*select_config)
if stdout and DEBUG_STDOUT:
_print_debug('STDOUT', ''.join(stdout))
if stderr and DEBUG_STDERR:
_print_debug('STDERR', ''.join(stderr))
# kill main process and its children
children = [process.pid for process in broker_process.get_children()]
_kill(self.broker.pid, timeout=TIMEOUT / 1000.0)
for child_pid in children:
_kill(child_pid, timeout=TIMEOUT / 1000.0)
示例7: done
def done(self):
try:
myself = Process(os.getpid())
for child in myself.get_children():
child.kill()
except Exception as e:
sys.stderr.write(str(e) + '\n')
示例8: click
def click(x, notify=False, pid=None, pids=None, webdriver=None, window_name=None, debug=False):
if debug:
print("[beryl] starting click")
print("\tpid: " + str(pid))
print("\twebdriver: " + str(webdriver))
print("\twindow_name: " + str(window_name))
print("\tstr(type(webdriver)): " + str(type(webdriver)))
type_as_string = str(type(x))
webdriver_type_as_string = str(type(webdriver))
if webdriver_type_as_string == "<class 'selenium.webdriver.firefox.webdriver.WebDriver'>":
pids = [webdriver.binary.process.pid]
elif webdriver_type_as_string == "<class 'selenium.webdriver.chrome.webdriver.WebDriver'>":
process = Process(webdriver.service.process.pid)
if hasattr(process, "children"):
pids = [p.pid for p in process.children()]
elif hasattr(process, "get_children"):
pids = [p.pid for p in process.get_children()]
if isinstance(x, str) or isinstance(x, unicode):
if x.endswith(".png") or x.endswith(".jpg"):
click_image(x, notify=notify)
else:
click_text(x, notify=notify, pids=pids, window_name=window_name, debug=debug)
elif isinstance(x, PngImageFile):
click_image(x,notify=notify)
elif isinstance(x, tuple):
click_location(x,notify=notify)
示例9: trace_memory_usage
def trace_memory_usage(self, frame, event, arg):
"""Callback for sys.settrace
Args:
frame: frame is the current stack frame
event: event is a string: 'call', 'line', 'return', 'exception', 'c_call', 'c_return', or 'c_exception'
arg: arg depends on the event type.
Returns:
function: wrap_func
"""
if event in ('call', 'line', 'return') and frame.f_code in self.code_map:
if event != 'call':
# "call" event just saves the lineno but not the memory
process = Process(getpid())
mem = process.memory_info()[0] / float(2 ** 20)
# if there is already a measurement for that line get the max
old_mem = self.code_map[frame.f_code].get(self.prevline, 0)
self.code_map[frame.f_code][self.prevline] = max(mem, old_mem)
self.prevline = frame.f_lineno
if self._original_trace_function is not None:
self._original_trace_function(frame, event, arg)
return self.trace_memory_usage
示例10: test_cleanup_children_on_terminate
def test_cleanup_children_on_terminate(self):
"""
Subprocesses spawned by tasks should be terminated on terminate
"""
class HangingSubprocessTask(luigi.Task):
def run(self):
python = sys.executable
check_call([python, '-c', 'while True: pass'])
task = HangingSubprocessTask()
queue = mock.Mock()
worker_id = 1
task_process = TaskProcess(task, worker_id, queue, lambda: None, lambda: None)
task_process.start()
parent = Process(task_process.pid)
while not parent.children():
# wait for child process to startup
sleep(0.01)
[child] = parent.children()
task_process.terminate()
child.wait(timeout=1.0) # wait for terminate to complete
self.assertFalse(parent.is_running())
self.assertFalse(child.is_running())
示例11: get_procinfo_by_address
def get_procinfo_by_address(ip_src, ip_dst, port_src=None, port_dst=None):
"""
Gets Infos about the Prozess associated with the given address information
Both port_src and port_dst must be not None or None at the same time.
return -- [pid, "/path/to/command", "user", "hash"] or []
"""
result = []
if port_src is not None:
pids = [c.pid for c in net_connections()
if len(c.raddr) != 0 and c.pid is not None and
(c.laddr[0], c.raddr[0], c.laddr[1], c.raddr[1]) == (ip_src, ip_dst, port_src, port_dst)]
else:
pids = [c.pid for c in net_connections()
if len(c.raddr) != 0 and c.pid is not None and (c.laddr[0], c.raddr[0]) == (ip_src, ip_dst)]
try:
if len(pids) > 1:
logger.warning("more than 1 matching process: %r", pids)
proc = Process(pids[0])
cmd = [pids[0], proc.cmdline(), proc.username()]
hash_input = "%d%s%s" % (cmd[0], cmd[1], cmd[2])
procinfo_hash = hashlib.sha256(hash_input.encode("UTF-8"))
cmd.append(procinfo_hash)
logger.debug("process info: %r", cmd)
return cmd
except IndexError:
pass
return []
示例12: ppid_cascade
def ppid_cascade(process=None):
if process is None:
process = Process()
process = process.parent()
while process:
yield process.pid
process = process.parent()
示例13: _get_shell_pid
def _get_shell_pid():
"""Returns parent process pid."""
proc = Process(os.getpid())
try:
return proc.parent().pid
except TypeError:
return proc.parent.pid
示例14: worker
def worker(self, obj):
if self.active_workers:
for node, active_workers in self.active_workers.iteritems():
for worker in active_workers:
if worker['id'] == obj.task_id:
p = Process(worker['worker_pid'])
return 'CPU:%.1f%% RAM:%.2f%%' % (p.cpu_percent(0.05), p.memory_percent())
return 'N/a'
示例15: run
def run(self):
self._isRunning = True
process = Process(os.getpid())
while self._isRunning:
self.cpuUsage = process.get_cpu_percent(self._pollInterval)
self.memUsage = process.get_memory_info()[0]
if self.delegate is not None:
self.delegate.processCpuUsage(self.cpuUsage)
self.delegate.processMemUsage(self.memUsage)