I wanted to write a program in Python which scans the RAM of a computer, by displaying the services and the executables.
import psutil
import wmi
from time import sleep
from progress.bar import Bar
# Connecting
c = wmi.WMI()
# stock here Process Id
proc = []
# function to get the Size
def get_size(bytes, suffix="B"):
factor = 1028
for unit in["","K","M","G","T","P"]:
if bytes < factor:
return f"{bytes:.2f} {unit}{suffix}"
bytes /= factor
# End
print("Scanning RAM: \n")
print("system virtual memory: \n")
# Return statistics about system memory usage
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
for i in range(100):
sleep(0.02)
svmem = psutil.virtual_memory() # physical memory usage
bar.next()
# to calculate percentage of available memory
avmem = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
prcntg = '{:.1f} %'.format(avmem)
bar.finish()
# put the object in a dictionary
mem = {'Total': get_size(svmem.total), 'Percentage-available': prcntg, 'Available': get_size(svmem.available), 'Percentage-used': f'{svmem.percent} %', 'Used': get_size(svmem.used), 'Free': get_size(svmem.free)}
print(mem)
# End
print("\n")
print("system swap memory: \n")
# Return system swap memory statistics as a named tuple including the following fields
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
for i in range(100):
sleep(0.02)
swap = psutil.swap_memory() # the percentage usage calculated as (total - available) / total * 100
bar.next()
bar.finish()
mem2 = {'Total': get_size(swap.total), 'Used': get_size(swap.used), 'Free': get_size(swap.free), 'Percentage': f'{swap.percent} %'}
print(mem2)
# End
'''
# Return an iterator yielding a WindowsService class instance for all Windows services installed.
# Get a Windows service by name, returning a WindowsService instance.
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
for i in range(100):
sleep(0.02)
winserv = list(psutil.win_service_iter())
s = psutil.win_service_get('alg') # windows service by name
bar.next()
bar.finish()
print(winserv)
print("\n")
print(s.as_dict())
# End
'''
print("\n")
print("Services: \n")
# Get all Windows services using the WMI module
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
for i in range(100):
sleep(0.02)
bar.next()
print("ID: Name:\n")
for process in c.Win32_Process ():
print (f"{process.ProcessId} {process.Name}")
bar.finish()
# Get get a specific Windows service
for process in c.Win32_Process (name="notepad.exe"):
print (f"{process.ProcessId} {process.Name}")
# End
# calculate how much Processes are runnig
for process in c.Win32_Process():
proc.append(process.ProcessId)
print(f"{len(proc)} Processes are running in your Device.")
# End
-
1\$\begingroup\$ I don't think lying about the progress bars is a particularly good idea. Why is that in the program? \$\endgroup\$Reinderien– Reinderien2025年01月15日 19:44:01 +00:00Commented Jan 15 at 19:44
1 Answer 1
Comments
The code has many good comments.
However, some could be improved. For example:
# stock here Process Id
The benefit of comments is that they can be written as complete English sentences.
The following comment appears several times and should be removed to reduce clutter:
# End
The following comment merely restates the function name:
# function to get the Size
def get_size(bytes, suffix="B"):
The PEP 8 style guide recommends adding a docstring for functions. You should replace the comment with a docstring:
def get_size(bytes, suffix="B"):
""" Get the memory size """
This comment has incorrect grammar and spelling:
# calculate how much Processes are runnig
Better:
# Calculate how many processes are running
Naming
The function name get_size
is not very specific. If it is used
to get the memory size, get_memory_size
would be better.
The variable named bytes
is the same name as a Python built-in function.
This can be confusing. To eliminate the confusion, rename the variable
as something like number_bytes
. The first clue is that "bytes" has special
coloring (syntax highlighting) in the question, as it does when I copy the code
into my editor.
The variable named c
is not descriptive enough in this context.
Perhaps conn
would be better.
Clutter
To reduce clutter, remove the docstring starting with:
'''
# Return an iterator yielding a WindowsService class instance for all Windows services installed.
# Get a Windows service by name, returning a WindowsService instance.
This looks like commented-out code.
Long lines
There are some very long lines which detract from code readability. The black program can be used to automatically format the code to make it easier to understand.
Simpler
The only use of the proc
variable in the code is to calculate the number
of processes:
for process in c.Win32_Process():
proc.append(process.ProcessId)
print(f"{len(proc)} Processes are running in your Device.")
There is no need to populate an array for this purpose. You could use a simple
count variable for this or perhaps use len(c.Win32_Process())
if supported.
You never pass in the suffix
parameter when you call this
function:
def get_size(bytes, suffix="B"):
You can simplify the code by getting rid of the variable.