Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'psutil' in functional components in Python. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
name = '/var/log/WLAN_Thermo/TEMPLOG.csv'
else:
create_logfile(name, log_kanal)
new_config = ConfigParser.SafeConfigParser()
Temperatur = [None for i in xrange(channel_count)]
alarm_state = [None for i in xrange(channel_count)]
test_alarm = False
config_mtime = 0
alarm_time = 0
try:
while True:
time_start = time.time()
CPU_usage = psutil.cpu_percent(interval=1, percpu=True)
ram = psutil.virtual_memory()
ram_free = ram.free // 2**20
logger.debug(u'CPU: {} RAM free: {}'.format(CPU_usage, ram_free))
alarm_irgendwo = False
alarm_neu = False
alarm_repeat = False
alarme = []
statusse = []
pit = {}
pit2 = {}
if enable_maverick:
logger.info(u'Reading from Maverick receiver...')
maverick = read_maverick()
else:
logger.info(u'Maverick is disabled')
def _KillWebServers():
for s in [signal.SIGTERM, signal.SIGINT, signal.SIGQUIT, signal.SIGKILL]:
signalled = []
for server in ['lighttpd', 'webpagereplay']:
for p in psutil.process_iter():
try:
if not server in ' '.join(p.cmdline):
continue
logging.info('Killing %s %s %s', s, server, p.pid)
p.send_signal(s)
signalled.append(p)
except Exception: # pylint: disable=broad-except
logging.exception('Failed killing %s %s', server, p.pid)
for p in signalled:
try:
p.wait(1)
except Exception: # pylint: disable=broad-except
logging.exception('Failed waiting for %s to die.', p.pid)
def test_swap_memory(self):
out = sh('env PATH=/usr/sbin:/sbin:%s swap -l -k' % os.environ['PATH'])
lines = out.strip().split('\n')[1:]
if not lines:
raise ValueError('no swap device(s) configured')
total = free = 0
for line in lines:
line = line.split()
t, f = line[-2:]
t = t.replace('K', '')
f = f.replace('K', '')
total += int(int(t) * 1024)
free += int(int(f) * 1024)
used = total - free
psutil_swap = psutil.swap_memory()
self.assertEqual(psutil_swap.total, total)
self.assertEqual(psutil_swap.used, used)
self.assertEqual(psutil_swap.free, free)
import psutil
import sys
MEGABYTE = 1 << 20
p = psutil.Popen(["test.exe", '0.1', sys.argv[1]])
#print(p.get_memory_info())
while (p.is_running()):
print(str(p.get_memory_info()[0] / MEGABYTE)+' '+str(p.get_memory_info()[1] / MEGABYTE))
try:
p.wait(0.01)
except:
pass
def test_halfway_terminated_process(self):
# Test that NoSuchProcess exception gets raised in case the
# process dies after we create the Process object.
# Example:
# >>> proc = Process(1234)
# >>> time.sleep(2) # time-consuming task, process dies in meantime
# >>> proc.name()
# Refers to Issue #15
sproc = get_test_subprocess()
p = psutil.Process(sproc.pid)
p.terminate()
p.wait()
if WINDOWS:
call_until(psutil.pids, "%s not in ret" % p.pid)
self.assertFalse(p.is_running())
# self.assertFalse(p.pid in psutil.pids(), msg="retcode = %s" %
# retcode)
excluded_names = ['pid', 'is_running', 'wait', 'create_time']
if LINUX and not RLIMIT_SUPPORT:
excluded_names.append('rlimit')
for name in dir(p):
if (name.startswith('_') or
name in excluded_names):
continue
try:
meth = getattr(p, name)
# get/set methods
if name == 'nice':
if POSIX:
def test_get_open_files2(self):
# test fd and path fields
fileobj = open(TESTFN, 'r')
p = psutil.Process(os.getpid())
for path, fd in p.get_open_files():
if path == fileobj.name or fd == fileobj.fileno():
break
else:
self.fail("no file found; files=%s" % repr(p.get_open_files()))
self.assertEqual(path, fileobj.name)
if WINDOWS:
self.assertEqual(fd, -1)
else:
self.assertEqual(fd, fileobj.fileno())
# test positions
ntuple = p.get_open_files()[0]
self.assertEqual(ntuple[0], ntuple.path)
self.assertEqual(ntuple[1], ntuple.fd)
# test file is gone
fileobj.close()
def test_memory():
if 'TRAVIS' not in os.environ:
return
p = psutil.Process()
mv = MemoryVisitor(p)
start = datetime.now()
RepositoryMining('test-repos/rails', mv,
from_commit='977b4be208c2c54eeaaf7b46953174ef402f49d4',
to_commit='ede505592cfab0212e53ca8ad1c38026a7b5d042').mine()
end = datetime.now()
diff = end - start
print('Max memory {} Mb'.format(mv.maxMemory / (2 ** 20)))
print('Min memory {} Mb'.format(mv.minMemory / (2 ** 20)))
print('Min memory {} Mb'.format(', '.join(map(str, mv.all))))
print('Time {}:{}:{}'.format(diff.seconds//3600, (diff.seconds//60)%60, diff.seconds))
def kill_all(process):
parent = psutil.Process(process.pid)
for child in parent.children(recursive=True):
child.kill()
parent.kill()
@staticmethod
def is_running(proc_name):
"""Check if process is running"""
result = False
for proc in psutil.process_iter():
if proc_name in str(proc):
result = True
break
return result
#!/usr/bin/python
import psutil
while True:
cpu_percents = str(psutil.cpu_percent(interval=0.5, percpu=True))
line = str(cpu_percents)[1:-1]
print line
datafile = open("cpuData.txt", "a")
datafile.write(line + "\n")
datafile.close()