Get CPU load with python3 in Raspberry Pi OS Bullseye - python-3.x

My goal is to get the current CPU usage ##% returned to display on a ePaper HAT display. I'm currently using python3.
I've tried 2 solutions found on stackoverflow and they produced unexpected results.
import os
def getCPUuse():
return str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline())
print(getCPUuse())
I'm getting "TERM environment variable not set." outputted in the shell when running this proposed code.
I'm not sure how to make this message go away, as the other proposed solutions to "TERM environment variable not set." is to set the variable XTERM but the variable seems to be set already. When entering set | grep TERM into terminal, "TERM=xterm-256color" is returned.
import psutil
def get_CPU():
return psutil.cpu_percent()
print(get_CPU())
Here is another proposed code but running this always returns "0.0". I'm suspicious that the CPU load is constantly 0.0 so I used
htop
in the terminal, and it looks like average CPU load was ~2.8%, not 0.
Perhaps I should use from gpiozero import LoadAverage instead? I'm new to programming hardware. If someone with more experience can offer pointers on whether https://gpiozero.readthedocs.io/en/stable/api_internal.html#loadaverage is promising, that'd be helpful too.
I'm trying to keep solutions based on Python3.

Related

Python too many subprocesses?

I'm trying to start a lot of python procees on a single machine.
Here is a code snippet:
fout = open(path, 'w')
p = subprocess.Popen((python_path,module_name),stdout=fout,bufsize=-1)
After about 100 processes I'm getting the error below:
Running on win 10 64 bit, Python 3.5. Any Idea what that might be? Already tried to split the start (so start from two scripts) as well as sleep command. After a certain number of processes, the error shows up. Any Idea what that might be? Thanks a lot for any hint!
PS:
Some background. Each process opens database connections as well as does some requests using the requests package. Then some calculations are done using numpy, scipy etc.
PPS: Just discover this error message:
dll load failed the paging file is too small for this operation to complete python (when calling scipy)
Issues solved through reinstalling numpy and scipy + installing mkl.
Strange about this error was that it only appeared after a certain number of processes. Would love to hear if anybody knows why this happened!

how do I clear a printed line and replace it with updated variable IDLE [duplicate]

This question already has answers here:
Print to the same line and not a new line? [duplicate]
(19 answers)
Closed 4 years ago.
I need to clear a printed line, but so far I have found no good answers for using python 3.7, IDLE on windows 10. I am trying to make a simple code that prints a changing variable. But I don't want tons of new lines being printed. I want to try and get it all on one line.
Is it possible to print a variable that has been updated later on in the code?
Do remember I am doing this in IDLE, not kali or something like that.
Thanks for all your help in advance.
The Python language definition defines when bytes will be sent to a file, such as sys.stdout, the default file for print. It does not define what the connected device does with the bytes.
When running code from IDLE, sys.stdout is initially connected to IDLE's Shell window. Shell is not a terminal and does not interpret terminal control codes other than '\n'. The reasons are a) IDLE is aimed at program development, by programmers, rather than program running by users, and developers sometimes need to see all the output from a program; and b) IDLE is cross-platform, while terminal behaviors are various, depending on the system, settings, and current modes (such as insert versus overwrite).
However, I am planning to add an option to run code in an IDLE editor with sys.stdout directed to the local system terminal/console.

How to colour Python output (version 3.6.3 IDLE)

I have already searched the web far and wide but I can not find a valid answer for my problem (for Python 3.6.3 IDLE).
I'm creating a program with IDLE Python and i need to change the output colour to green (0,255,0).
Can you help me? :D
IDLE is written in Tkinter so it uses the same techniques that
you would use to change the colour of text in a Text widget.
But IDLE does not expose the Text widget to you as a user.
In fact it doesn't make much sense for IDLE to do that since IDLE is
only a development tool. It is not where you are expected to run
your programs. THus IDLE tries to mimic the environment where
your programs should run not to provide facilities that would
only work within IDLE.
Is there any reason why you want to change the ouput only in IDLE?
Or do you really want to be able to control the output of your
program wherever it runs? If the latter then you will need to
create your own Text window and display the output there.
By this Method some how you can change color.but add Extra Character by itself, it mean it is not efficient
>>> color.write("Hi, are you called Miharu461? \n","KEYWORD")
Hi, are you called Miharu461?
31

Net::SNMP caching results for extend OIDs

The scope of this work is to query two machines' high resolution timer at the "same time" and get the time clock inaccuracy between both systems. This is done by having the 3rd machine sending an SNMP-get for a custom OID where the SNMP agent is configured to invoke a perl script to return the high-resolution timer. All works fine as in the snmp-get manages to return the expected result. However it appears that regardless of the frequency of the snmpget queries, the snmpagent only performs a fresh query to the script at ~5 second intervals. I am running NET SNMP version 5.4.3. After some research I've seen that this is typical of NET SNMP to cache the results and this is done on MIB tree basis. There is MIB (nsCacheTable) with the respective intervals by querying snmpwalk to 1.3.6.1.4.1.8072.1.5.3. Apparently the values can be changed to 0 to remove caching. Some of these are read-only though. Although I've set a few of them to 0 using SNMPset (as most of them return a Bad object type error).
I know very basic SNMP so I followed a guide online and mapped the below custom OID to the perl script with this line in the snmpd.conf.
extend .1.3.6.1.4.1.27654.3 return_date /usr/bin/perl [directory]/[perl script name].pl
Then the actual OID containing the output (time in epoch) is:
iso.3.6.1.4.1.27654.3.3.1.1.11.114.101.116.117.114.110.95.100.97.116.101
Anyone has any ideas how I can disable the caching for this OID?
Thanks in advance.
---EDIT---
According to this blog post, in order to avoid disabling the caching - one can instead use pass-persist scripts which look more complex to implement at first glance. The perl script I used to call is the below:
#!/usr/bin/perl
# THIS SCRIPT RETURNS THE EPOCH TIME OF DAY IN MICROSECONDS
use Time::HiRes qw(gettimeofday);
($s, $usec) = gettimeofday();
$newtime = $s.$usec;
print ($newtime);
Anyone can provide help in converting this script for pass-persist and how the snmpd.conf should look like?

Cygwin top command - See processes for all users

Does anybody know how to see the processes for all users using top command in Cygwin (part of procps library under System).
I know this can be done in *nix but I am struggling in Cygwin. I have tried using pslist but it does not behave in a putty SSH console.
I need to have a solution where I can see a top like dialog using SSH. I do not have any NTLM SSO access to the Win2k3 guest at all so ssh is the only way in.
top only displays Cygwin processes. ps -W will list Windows processes as well.
Manytimes the command "tasklist" gets the job done more effectively. It built into windows, just make sure your System32 folder is part of your bash profile PATH. There is also procps itself. You should also try using mintty for your terminal. You could always try attaching any of these task apps to screen, and or using watch to poll the information.
It seems you can do something like:
wmic process get ProcessId,Name,UserModeTime,KernelModeTime /EVERY:1
The User and Kernel mode times there seem to be expressed in 1/10,000,000th of second.
You should be able to post-process that output to get the CPU-usage per second.
Here using cygwin's perl:
wmic process get ProcessId,Name,UserModeTime,KernelModeTime /EVERY:1 |
perl -lne '
if (/\S/) {
my ($k,$c,$p,$u) = split /\s{2,}/;
$n{"$p\t$c"}=$k+$u;
} else {
my %c;
for my $k (keys %n) {
$c{$k} = $n{$k} - $o{$k} if defined $o{$k}
}
print "$_\t" . $c{$_}/1e5 for (sort {$c{$b}<=>$c{$a}} keys %c)[0..20];
%o = %n; %n = undef; print ""
}'
Outputs something like:
0 System Idle Process 588.12377
2196 sh.exe 107.00075
248 svchost.exe 85.80055
7140 explorer.exe 26.52017
[...]
every second.
Note that if the System Idle Process shows just under 800% on an idle system, that's because your system has 8 CPU cores (well at least 8 threads) as that counts the CPU time of all CPUs.
Also note that the EVERY:1 above is a lie. wmic doesn't seem to give that output every second. More likely, it sleeps roughly 1 second between each report and doesn't compensate for the time it takes to compute the report. So in practice, it will run every 1 second and a bit which means those percentages are not very accurate and slightly overestimated.

Resources