def check_resources(process: psutil.Process): with process.oneshot(): user_time_used = process.cpu_times().user system_time_used = process.cpu_times().system cpu_time_used = (user_time_used + system_time_used) * 1000 memory_used = process.memory_info().rss // 1024 return memory_used, cpu_time_used
class Proc(object): def __init__(self, pid): self.pid = pid self.proc = Process(pid) with self.proc.oneshot(): self.name = self.proc.name() self.owner = self.proc.username() self.created = self.proc.create_time() def poll(self, delay=1): if not self.proc.is_running(): return ( self.pid, '**DEAD**' + self.name, self.owner, 0, 0 ) with self.proc.oneshot(): self.poll1 = self.proc.cpu_times() self.virtual1 = self.proc.memory_info().vms self.system1 = cpu_times() time.sleep(delay) with self.proc.oneshot(): self.poll2 = self.proc.cpu_times() self.virtual2 = self.proc.memory_info().vms self.system2 = cpu_times() self.proc_time = sum(self.poll2) - sum(self.poll1) self.cpu_time = sum(self.system2) - sum(self.system1) self.virtual = MB(( self.virtual1 + self.virtual2 ) / 2) self.cpu_percent = 100 * ( self.proc_time / self.cpu_time ) return ( self.pid, self.name, self.owner, self.cpu_percent, self.virtual ) def is_running(self): return self.proc.is_running() def __repr__(self): return "**process** %s (%d)" % ( self.proc.name(), self.pid ) def __str__(self): return template.format(self.pid, self.name, self.owner, self.cpu_percent, self.virtual)
async def advinfo(self, ctx): proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) bot = await self.client.application_info() e = discord.Embed(title=f"{bot.name}", description=f"{bot.description}", colour=COLOURS['purple']) e.add_field(name="Bot Version", value=f'{BOT_VERSION}', inline=False) e.add_field(name="Uptime", value=f'{str(uptime).split(".")[0]}', inline=True) e.add_field(name="", value="") e.add_field(name="CPU time", value=f'{str(cpu_time).split(".")[0]}', inline=True) # name and value of below field are Zero Width Space not empty # Check this : https://emojipedia.org/zero-width-joiner/ e.add_field(name="Ping", value=f'{round(self.client.latency*1000)}ms', inline=True) e.add_field(name="", value="") e.add_field(name="Response Time", value=f'-', inline=False) e.add_field(name="Memory Usage", value=f'{mem_usage:,.0f}/{mem_total:,.0f} MB', inline=True) e.add_field(name="Memory Usage %", value=f'{mem_of_total:,.2f}%', inline=True) e.set_thumbnail(url=str(bot.icon_url)) e.set_footer( text=f'Python Version - {version_info.major}.{version_info.minor}.{version_info.micro} | Discord.py Version - {discord.version_info.major}.{discord.version_info.minor}.{discord.version_info.micro}') start = time() msg = await ctx.send(embed=e) end = time() e.set_field_at(index=6, name="Response Time", value=f'{round((end-start)*1000)}ms', inline=True) await msg.edit(embed=e)
def __enter__(self): cput = P.cpu_times() memi = P.memory_info_ex() self.start_sys = cput.system self.start_user = cput.user self.start_rss = memi.rss self.start_disk = get_wdb() + get_ldb()
def _monitor_pid(pid: int, usage: Usage): proc = Process(pid) while proc.is_running() and not Executor.is_shutting_down(): usage.cpu_time = sum(proc.cpu_times()) usage.mem_peak = max(usage.mem_peak, proc.memory_info().vms) time.sleep(0.5)
async def botstats(self, ctx): embed = discord.Embed(title="Statistics", colour=discord.Colour.red(), thumbnail=self.bot.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) embed.add_field(name="Python version", value=python_version(), inline=True), embed.add_field(name="discord.py version", value=discord_version, inline=True), embed.add_field(name="Uptime", value=uptime, inline=True), embed.add_field(name="CPU time", value=cpu_time, inline=True), embed.add_field( name="Memory usage", value= f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", inline=True), #embed.add_field(name = "Users", value = f"{ctx.guild.member_count:,}", inline =True) await ctx.send(embed=embed)
async def show_bot_stats(self, ctx): '''Displays Statistical Information''' embed = Embed(title="Bot stats", colour=ctx.author.colour, thumbnail=self.bot.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) #cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) mo = self.bot.guilds sum1 = 0 for s in mo: sum1 += len(s.members) fields = [ ("Python version", python_version(), True), ("discord.py version", discord_version, True), ("Uptime", uptime, True), ("CPU time", f"{cpu_time}%", True), ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True), ("Users", f"{sum1:,}", True), ("Servers", f"{len(self.bot.guilds)}", True), ("Region", f"`Europe`", True), ("Latency", "`{0}`".format(round(self.bot.latency, 4) * 1000), True) ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await ctx.send(embed=embed)
async def show_bot_stats(self, ctx): embed = Embed(title="Bot stats", colour=ctx.author.colour, thumbnail=self.bot.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) fields = [ ("Bot version", self.bot.VERSION, True), ("Python version", python_version(), True), ("discord.py version", discord_version, True), ("Uptime", uptime, True), ("CPU time", cpu_time, True), ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True), ("Users", f"{self.bot.guild.member_count:,}", True) ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await ctx.send(embed=embed)
def __exit__(self, *args): cput = P.cpu_times() memi = P.memory_info_ex() self.stop_sys = cput.system self.stop_user = cput.user self.stop_rss = memi.rss self.stop_disk = get_wdb() + get_ldb() t_elapsed_sys = self.stop_sys - self.start_sys t_elapsed_user = self.stop_user - self.start_user t_elapsed = t_elapsed_sys + t_elapsed_user print >>sys.stderr, blessings.Terminal().yellow('timer: {} took {} (user: {}, sys: {}) seconds.'.format(self.name, t_elapsed, t_elapsed_user, t_elapsed_sys)) print >>sys.stderr, blessings.Terminal().yellow('timer: rss = {} MiB. (change: {} MiB).'.format(self.stop_rss/1048576.0, (self.stop_rss-self.start_rss)/1048576.0)) print >>sys.stderr, blessings.Terminal().yellow('timer: disk = {} MiB. (change: {} MiB).'.format(self.stop_disk/1048576.0, (self.stop_disk-self.start_disk)/1048576.0)) print >>sys.stderr stats[self.name+'.Memory'] = self.stop_rss + self.stop_disk stats[self.name+'.Runtime'] = t_elapsed
def get_cpu_times(process: psutil.Process) -> dict: """ Returns the CPU usage by a process. Args: process (psutil.Process): The process that you want to get the data """ ret = dict() cpu_data = process.cpu_times() ret['cpu_user'] = cpu_data.user ret['cpu_system'] = cpu_data.system ret['cpu_children_user'] = cpu_data.children_user ret['cpu_children_system'] = cpu_data.children_system ret['cpu_iowait'] = cpu_data.iowait return ret
async def cmd_stats(self, ctx): async with ctx.typing(): start = time() msg = await ctx.send("-") end = time() dwsp_latency = round(self.bot.latency*1000) response_latency = round((end-start)*1000) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time()-proc.create_time()) cpu_time = timedelta(seconds=(cpu:=proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = round(mem_total * (mem_of_total / 100),2) mem_of_total = round(mem_of_total, 2) mem_total = round(mem_total/1024) embed=Embed( title=self.bot.user.name, color=ctx.guild.me.color if ctx.guild else ctx.author.color, timestamp=datetime.utcnow() ) embed.set_author(name=self.bot.user, icon_url=self.bot.user.avatar_url) embed.set_thumbnail(url=self.bot.user.avatar_url) fields=[ ("Default Prefix", self.bot.prefix, True), ("DWSP Latency", f"{dwsp_latency}ms", True), ("Response Latency", f"{response_latency}ms", True), ("Bot Version", self.bot.VERSION, True), ("Python Version", python_version(), True), ("Discord.py Version", discord_version, True), ("Uptime", uptime, True), ("CPU Time", cpu_time, True), ("Loaded Cogs", len(self.bot.extensions), True), ("Memory Usage", f"{mem_usage}MB/{mem_total}GB {mem_of_total}%", False), ("Servers", len(self.bot.guilds), True), ("Users", len(self.bot.users), True), ("Banned Users", len(self.bot.banlist), True)] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await msg.delete() await ctx.send(embed=embed)
async def show_bot_info(self, ctx): t = datetime.utcnow() proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) e = Embed(title=f"Information about `ICE X`", colour=ctx.author.colour) fields = [ ("Bot version", self.bot.VERSION, True), ("Bot Owner", f"<@!537634097137188875>", True), ("Python version", python_version(), True), ("discord.py version", discord_version, True), ("Uptime", uptime, True), ("CPU time", cpu_time, True), ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True), ("Invite Bot", '**[Invite](https://discord.com/api/oauth2/authorize?client_id=723380957343907911&permissions=8&scope=bot "Invite the bot to your server")**', False) ] for name, value, inline in fields: e.add_field(name=name, value=value, inline=inline) e.set_thumbnail(url=self.bot.user.avatar_url) e.set_author( name=f"{ctx.author.display_name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar_url) e.set_footer( text= f"Requested by {ctx.author.display_name} | {t.strftime('%b %d, %Y | %I:%M %p UTC')}" ) await ctx.send(embed=e)
async def gbotinfo(self, ctx): embed = discord.Embed(title='About gBot', colour=discord.Colour.blurple()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) fields = [ ("Developed by:", "Galax028#9474", True), ("Hosted using:", "https://mydiscordbothosting.com", True), ("Version:", f"`{version}`", True), ("Total Commands:", f"{len(self.bot.commands)}", True), ("Invite the bot:", "[Click Here](https://rb.gy/wzzuvm)", True), ("Support Server:", "[Click Here](https://discord.gg/2hVmdnb)", True), ("⠀", "----------------------------------------------------------------------", False), ("Python Version:", f"`{python_version()}`", True), ("discord.py Version:", f"`{discord_version}`", True), ("⠀", "⠀", True), ("Uptime:", f"`{uptime}`", True), ("CPU Time:", f"`{cpu_time}`", True), ("RAM Usage:", f"`{mem_usage:,.3f}/250 MiB`", True), ("⠀", "----------------------------------------------------------------------", False), ("Special Thanks:", "PixelEdition#2116, Marxist Gamer#3000, Sir.Nick#4646", False), ("⠀", "⠀", False) ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) embed.set_footer(text="Thank you for using gBot!") await ctx.send(embed=embed)
def analyse(self) -> dict: """ This is the main method of this class, if the resources used by assigment/submission need to be retrieved you must use this method. :return: Returns a Dict containing : list of cpuTimes, the file size and the maximum resident size. """ # Retrieve the indexes of the inputs / outputs the program succeeded. indexes = [i for i, x in enumerate(self.__successIOs) if x == 1] runs = 0 executable = self.getAssignment().getCompiledName() psProcess = Process(getpid()) cpuTimeValues = [] memVirtual = 0 while (runs <= 20): for i in indexes: process = Popen([self.__assignment.getLaunchCommand(), executable], stdout=PIPE, stdin=PIPE, stderr=PIPE) rusageChild = resource.getrusage(resource.RUSAGE_CHILDREN) try: _, __ = process.communicate( bytes(self.__assignment.getIOs()[i][0].encode('UTF-8')), timeout=30) if rusageChild.ru_maxrss > self.__maxRSS: self.__maxRSS = rusageChild.ru_maxrss except TimeoutExpired: assert ('[except - CodeAnalysis.anaylse() - This point should never be reached as IOs has already' 'been checked up.s') self.__cpuTimes.append( getattr(psProcess.cpu_times(), 'children_user') - sum(self.__cpuTimes)) runs += 1 if path.exists('./stat'): with open('./stat', 'r') as f: values = f.read().split(' ') if memVirtual == 0: memVirtual = values[22] return { 'cpuTime': sum(self.__cpuTimes) / len(self.__cpuTimes), 'fileSize': path.getsize(self.__assignment.getOriginalFilename()), 'virtualMem': memVirtual }
async def show_bot_info(self, ctx, patreon_status): embed = Embed( title="Doob Info <:doob:754762131085459498>", colour=ctx.author.colour, timestamp=datetime.utcnow(), ) bot_version = self.bot.VERSION proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta( seconds=(cpu := proc.cpu_times()).system + cpu.user ) # pylint: disable=used-before-assignment mem_total = virtual_memory().total / (1025 ** 2) mem_of_total = proc.memory_percent() mem_usg = mem_total * (mem_of_total / 100) fields = [ ("Name", "Doob <:doob:754762131085459498>", False), ( "Description", "The multipurpose Discord Bot with global leveling and powerful logging tools for your server.", False, ), ("Developers", "<@308000668181069824>", False), ("Doob's Server Count", f"{str(len(self.bot.guilds))}", True), ("Doob's Member Count", f"{str(len(self.bot.users))}", True), ( "The ping for Doob is...", f" :ping_pong: {round(self.bot.latency * 1000)} ms", False, ), ("Python Version", python_version(), True), ("Uptime", uptime, True), ("CPU Time", cpu_time, True), ( "Memory Usage", f"{mem_usg:,.3f} MiB / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True, ), ("Library", f"discord.py {discord_version}", True), ( "Bot Version", f"{self.bot.VERSION} - [Changelog](https://github.com/doobdev/doob/blob/master/CHANGELOG.md#v{bot_version.replace('.', '')})", True, ), ("Top.gg Link", "https://top.gg/bot/680606346952966177", False), ( "Invite Link", "[Invite Link Here](https://doob.link/invite)", True, ), ( "GitHub Repository", "[Click Here](https://github.com/doobdev/doob)", True, ), ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) embed.set_thumbnail(url=ctx.guild.me.avatar_url) embed.set_footer( text=f"{ctx.author.name} requested Doob's information", icon_url=ctx.author.avatar_url, ) if patreon_status == True: embed.add_field( name="Patreon", value=f"Thanks for [Donating](https://patreon.com/doobdev) {ctx.author.display_name}! :white_check_mark:", inline=False, ) await ctx.reply(embed=embed) if patreon_status == False: embed.add_field( name="Patreon", value="[Click Here for Patreon](https://patreon.com/doobdev)", inline=False, ) await ctx.reply(embed=embed)
async def show_bot_info(self, ctx, patreon_status): embed = Embed(title="Krinio Info", colour=ctx.author.colour, timestamp=datetime.utcnow()) bot_version = self.bot.VERSION proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1025**2) mem_of_total = proc.memory_percent() mem_usg = mem_total * (mem_of_total / 100) fields = [ ("Name", "Krinio", False), ("Developers", "<@308000668181069824>", False), ("Krinio's Server Count", f"{str(len(self.bot.guilds))}", True), ("Krinio's Member Count", f"{str(len(self.bot.users))}", True), ( "The ping for Krinio is...", f" :ping_pong: {round(self.bot.latency * 1000)} ms", False, ), ("Python Version", python_version(), True), ("Uptime", uptime, True), ("CPU Time", cpu_time, True), ( "Memory Usage", f"{mem_usg:,.3f} MiB / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True, ), ("Library", f"discord.py {discord_version}", True), ( "Bot Version", f"{self.bot.VERSION} - [Changelog](https://github.com/doobdev/Krinio/blob/master/CHANGELOG.md#v{bot_version.replace('.', '')})", True, ), ("Top.gg Link", "https://top.gg/bot/744377689095536750", False), ( "Invite Link", "[Invite Link Here](https://discord.com/oauth2/authorize?client_id=744377689095536750&scope=bot&permissions=271674430)", True, ), ( "GitHub Repository", "[Click Here](https://github.com/doobdev/Krinio)", True, ), ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) embed.set_thumbnail(url=ctx.guild.me.avatar_url) embed.set_footer( text=f"{ctx.author.name} requested Krinio's information", icon_url=ctx.author.avatar_url, ) if patreon_status == True: embed.add_field( name="Patreon", value= f"Thanks for [Donating](https://patreon.com/doobdev) {ctx.author.display_name}! :white_check_mark:", inline=False, ) await ctx.send(embed=embed) if patreon_status == False: embed.add_field( name="Patreon", value="[Click Here for Patreon](https://patreon.com/doobdev)", inline=False, ) await ctx.send(embed=embed)
def _get_data(p: psutil.Process): with p.oneshot(): t = p.cpu_times().user + p.cpu_times().system m = p.memory_info().rss return t, m
def track_process(self, p: psutil.Process): with p.oneshot(): key = None if p.pid in self.pids: key = self.pids[p.pid] if self.processes[key].name != p.name(): key = None if key is None: key = len(self.processes) self.processes.append(ProcessInfo(key, p.pid, p.name())) self.pids[p.pid] = key self.data.update({ f'process.{key}.name': p.name(), f'process.{key}.pid': p.pid, f'process.{key}.ppid': p.ppid(), f'process.{key}.create_time': p.create_time(), }) try: self.data.update({ f'process.{key}.exe': p.exe(), }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: self.data.update({ f'process.{key}.cmdline': '\n'.join(p.cmdline()), }) except (psutil.AccessDenied, psutil.ZombieProcess): pass self.processes[key].active = True try: res = p.memory_info() self.data.update({ f'process.{key}.rss': res.rss, f'process.{key}.vms': res.vms, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: res = p.cpu_times() self.data.update({ f'process.{key}.user': res.user, f'process.{key}.system': res.system, }) if hasattr(res, 'iowait'): self.data.update({ f'process.{key}.iowait': res.iowait, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: res = p.cpu_percent() self.data.update({ f'process.{key}.cpu': res, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: res = p.num_threads() self.data.update({ f'process.{key}.threads': res, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass
async def command_bot_info(self, ctx: commands.Context) -> None: proc = Process() with proc.oneshot(): uptime = chron.short_delta( timedelta(seconds=time() - proc.create_time())) cpu_time = chron.short_delta( timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user), milliseconds=True) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) await ctx.send(embed=discord.Embed.from_dict({ "title": "Carberretta Information", "color": DEFAULT_EMBED_COLOUR, "thumbnail": { "url": f"{self.bot.user.avatar_url}" }, "author": { "name": "Carberretta" }, "footer": { "text": f"Requested by {ctx.author.display_name}", "icon_url": f"{ctx.author.avatar_url}", }, "fields": [ { "name": "Bot Version", "value": self.bot.version, "inline": True }, { "name": "Python Version", "value": python_version(), "inline": True }, { "name": "discord.py Version", "value": discord.__version__, "inline": True }, { "name": "Uptime", "value": uptime, "inline": True }, { "name": "CPU Time", "value": cpu_time, "inline": True }, { "name": "Memory Usage", "value": f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:,.0f}%)", "inline": True, }, { "name": "Code Lines", "value": f"{int(self.bot.loc.code):,}", "inline": True }, { "name": "Docs Lines", "value": f"{int(self.bot.loc.docs):,}", "inline": True }, { "name": "Blank Lines", "value": f"{int(self.bot.loc.empty):,}", "inline": True }, { "name": "Database Calls", "value": f"{self.bot.db._calls:,}", "inline": True }, ], }))
class _ProcessMonitor: WARNING_THRESHOLD = 100 * 1024 * 1024 busy = False def __init__(self): self.process = Process() self.peak_mem_res = 0 self.low_mem_warning = False def monitor_task(self): if sys.stdout.isatty(): while self.busy: try: # only print the data out every 10 seconds if datetime.now().second / 10 == 0: info = self._get_info() output.debug(info) else: # call get_mem so that we record peak more accurately self._get_mem() time.sleep(1) except Exception: output.debug_exception() self.busy = False pass else: # if this isn't a TTY, no point in doing any of this self.busy = False def _get_info(self) -> str: from yawast.external.memory_size import Size # prime the call to cpu_percent, as the first call doesn't return useful data self.process.cpu_percent(interval=1) # use oneshot() to cache the data, so we minimize hits with self.process.oneshot(): pct = self.process.cpu_percent() times = self.process.cpu_times() mem = self._get_mem() mem_res = "{0:cM}".format(Size(mem.rss)) mem_virt = "{0:cM}".format(Size(mem.vms)) thr = self.process.num_threads() vm = psutil.virtual_memory() mem_total = "{0:cM}".format(Size(vm.total)) mem_avail_bytes = vm.available mem_avail = "{0:cM}".format(Size(vm.available)) if mem_avail_bytes < self.WARNING_THRESHOLD and not self.low_mem_warning: self.low_mem_warning = True output.error(f"Low RAM Available: {mem_avail}") cons = -1 try: cons = len(self.process.connections(kind="inet")) except Exception: # we don't care if this fails output.debug_exception() cpu_freq = psutil.cpu_freq() info = (f"Process Stats: CPU: {pct}% - Sys: {times.system} - " f"User: {times.user} - Res: {mem_res} - Virt: {mem_virt} - " f"Available: {mem_avail}/{mem_total} - Threads: {thr} - " f"Connections: {cons} - CPU Freq: " f"{int(cpu_freq.current)}MHz/{int(cpu_freq.max)}MHz") return info def _get_mem(self): mem = self.process.memory_info() if mem.rss > self.peak_mem_res: self.peak_mem_res = mem.rss output.debug(f"New high-memory threshold: {self.peak_mem_res}") return mem def __enter__(self): self.busy = True threading.Thread(target=self.monitor_task).start() return self def __exit__(self, exception, value, tb): self.busy = False if exception is not None: return False