Get CPU and GPU Temp using Python Windows - python

I was wondering if there was a way to get the CPU and the GPU temperature in python. I have already found a way for Linux (using psutil.sensors_temperature()), and I wanted to find a way for Windows.
A way to find the temperatures for Mac OS would also be appreciated, but I mainly want a way for windows.
I prefer to only use python modules, but DLL and C/C++ extensions are also completely acceptable!
When I try doing the below, I get None:
import wmi
w = wmi.WMI()
prin(w.Win32_TemperatureProbe()[0].CurrentReading)
When I try doing the below, I get an error:
import wmi
w = wmi.WMI(namespace="root\wmi")
temperature_info = w.MSAcpi_ThermalZoneTemperature()[0]
print(temperature_info.CurrentTemperature)
Error:
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217396, 'OLE error 0x8004100c', None, None)>
I have heard of OpenHardwareMoniter, but this requires me to install something that is not a python module. I would also prefer to not have to run the script as admin to get the results.
I am also fine with running windows cmd commands with python, but I have not found one that returns the CPU temp.
Update: I found this: https://stackoverflow.com/a/58924992/13710015.
I can't figure out how to use it though.
When I tried doing: print(OUTPUT_temp._fields_), I got
[('Board Temp', <class 'ctypes.c_ulong'>), ('CPU Temp', <class 'ctypes.c_ulong'>), ('Board Temp2', <class 'ctypes.c_ulong'>), ('temp4', <class 'ctypes.c_ulong'>), ('temp5', <class 'ctypes.c_ulong'>)]
Note: I really do not want to run this as admin. If I absolutely have to, I can, but I prefer not to.

I think there doesn't have a directly way to achieve that. Some CPU producers wouldn't provide wmi to let your know the temperature directly.
You could use OpenHardwareMoniter.dll. Use the dynamic library.
Firstly, Download the OpenHardwareMoniter. It contains a file called OpenHardwareMonitorLib.dll (version 0.9.6, December 2020).
Install the module pythonnet:
pip install pythonnet
Below code works fine on my PC (Get the CPU temperature):
import clr # the pythonnet module.
clr.AddReference(r'YourdllPath')
# e.g. clr.AddReference(r'OpenHardwareMonitor/OpenHardwareMonitorLib'), without .dll
from OpenHardwareMonitor.Hardware import Computer
c = Computer()
c.CPUEnabled = True # get the Info about CPU
c.GPUEnabled = True # get the Info about GPU
c.Open()
while True:
for a in range(0, len(c.Hardware[0].Sensors)):
# print(c.Hardware[0].Sensors[a].Identifier)
if "/temperature" in str(c.Hardware[0].Sensors[a].Identifier):
print(c.Hardware[0].Sensors[a].get_Value())
c.Hardware[0].Update()
To Get the GPU temperature, change the c.Hardware[0] to c.Hardware[1].
Compare the result with :
Attention: If you want to get the CPU temperature, you need to run it as Administrator. If not, you will only get the value of Load. For GPU temperature, it can work without Admin permissions (as on Windows 10 21H1).
I did some changes from a Chinese Blog

I found a pretty good module for getting the temperature of NVIDIA GPUs.
pip install gputil
Code to print out temperature
import GPUtil
gpu = GPUtil.getGPUs()[0]
print(gpu.temperature)
I found it here

so you can use gpiozero to get the temp
first pip install gpiozero and from gpiozero import CPUTemperature to import it and cpu = CPUTemperature() print(cpu.temperature)
code:
from gpiozero import CPUTemperature
cpu = CPUTemperature()
print(cpu.temperature)
hope you enjoy. :)

Related

FTDI specific - libftd2xx.so is not loaded when using python wrapper to libMPSSE.so

I have installed the FTDI libftd2xx.so following the FTDI installation guide. I also has the libMPSSE.so downloaded. I am writing a python wrapper to use the I2C functions in the libMPSSE.so
However, I got the following error when trying to run my code:
../../TopLayer/I2C/src/ftdi_i2c.c:239:I2C_InitChannel(): NULL expression encountered
According to https://stackoverflow.com/a/22994703/8406938, looks like it cannot find the libftd2xx.so
Here is my python wrapper:
filepath = 'my path to the libMPSSE.so'
mpsse = CDLL(os.path.join(filepath, 'libMPSSE.so')
ChannelConf = ChannelConfig()
ChannelConf.clock_rate = 100000
ChannelConf.LatencyTimer = 3
ChannelConf.Options = 0
status = mpsse.I2C_InitChannel(c_void_p()), byref(ChannelConf))
The exact same code work in my Windows machine with libMPSSE.dll with the windows driver. Any suggestion how to solve this?

How can I get the volume of sound of a video in Python using moviepy?

I want to get the volume of sound of a video so I use the following:
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate
clip = VideoFileClip("soccer_game.mp4")
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000)
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
But I get these errors:
Exception AttributeError: "VideoFileClip instance has no attribute 'reader'" in <bound method VideoFileClip.__del__ of <moviepy.video.io.VideoFileClip.VideoFileClip instance at 0x084C3198>> ignored
WindowsError: [Error 5] Access is denied
I am using IPython notebook and Python 2.7.
I assume something doesn't have the appropriate permissions. I have changed run this program as an administrator for ffmpeg.exe, ffplay.exe, ffprobe.exe.
I fixed a bug today that may have caused your problem, would you mind upgrading and trying again ? If it still doesn't work, I'll need to know your windows version.
Rather than doing own calculations, I would recommend to use an existing library or tool that considers the human-perceived loudness.
For example, ffmpeg can measure the loudness based on the EBU R 128 recommendation (in LUFS).
This discussion recommends pyloudnorm.

Python - How to get the start/base address of a process?

How do I get the start/base address of a process? Per example Solitaire.exe (solitaire.exe+BAFA8)
#-*- coding: utf-8 -*-
import ctypes, win32ui, win32process
PROCESS_ALL_ACCESS = 0x1F0FFF
HWND = win32ui.FindWindow(None,u"Solitär").GetSafeHwnd()
PID = win32process.GetWindowThreadProcessId(HWND)[1]
PROCESS = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS,False,PID)
print PID, HWND,PROCESS
I would like to calculate a memory address and for this way I need the base address of solitaire.exe.
Here's a picture of what I mean:
I think the handle returned by GetModuleHandle is actually the base address of the given module. You get the handle of the exe by passing NULL.
Install pydbg
Source: https://github.com/OpenRCE/pydbg
Unofficial binaries here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg
from pydbg import *
from pydbg.defines import *
import struct
dbg = pydbg()
path_exe = "C:\\windows\\system32\\calc.exe"
dbg.load(path_exe, "-u amir")
dbg.debug_event_loop()
parameter_addr = dbg.context.Esp #(+ 0x8)
print 'ESP (address) ',parameter_addr
#attach not working under Win7 for me
#pid = raw_input("Enter PID:")
#print 'PID entered %i'%int(pid)
#dbg.attach(int(pid)) #attaching to running process not working
You might want to have a look at PaiMei, although it's not very active right now https://github.com/OpenRCE/paimei
I couldn't get attach() to work and used load instead. Pydbg has loads of functionality, such as read_proccess_memory, write_process_memory etc.
Note that you can't randomly change memory, because an operating system protects memory of other processes from your process (protected mode). Before the x86 processors there were some which allowed all processors to run in real mode, i.e. the full access of memory for every programm. Non-malicious software usually (always?) doesn't read/write other processes' memory.
The HMDOULE value of GetModuleHandle is the base address of the loaded module and is probably the address you need to compute the offset.
If not, that address is the start of the header of the module (DLL/EXE), which can be displayed with the dumpbin utility that comes with Visual Studio or you can interpret it yourself using the Microsoft PE and COFF Specification to determine the AddressOfEntryPoint and BaseOfCode as offsets from the base address. If the base address of the module isn't what you need, one of these two is another option.
Example:
>>> BaseAddress = win32api.GetModuleHandle(None) + 0xBAFA8
>>> print '{:08X}'.format(BaseAddress)
1D0BAFA8
If The AddressOfEntryPoint or BaseOfCode is needed, you'll have to use ctypes to call ReadProcessMemory following the PE specification to locate the offsets, or just use dumpbin /headers solitaire.exe to learn the offsets.
You can use frida to easy do that.
It is very useful to make hack and do some memory operation just like make address offset, read memory, write something to special memory etc...
https://github.com/frida/frida
2021.08.01 update:
Thanks for #Simas Joneliunas reminding
There some step using frida(windows):
Install frida by pip
pip install frida-tools # CLI tools
pip install frida # Python bindings
Using frida api
session = frida.attach(processName)
script = session.create_script("""yourScript""")
script.load()
sys.stdin.read() #make program always alive
session.detach()
Edit your scrip(using JavaScrip)
var baseAddr = Module.findBaseAddress('solitaire.exe');
var firstPointer = baseAddr.add(0xBAFA8).readPointer();
var secondPointer = firstPointer.add(0x50).readPointer();
var thirdPointer = secondPointer.add(0x14).readPointer();
#if your target pointer points to a Ansi String, you can use #thirdPointer.readAnsiString() to read
The official site https://frida.re/

OpenCV crashing on cv.Resize

When running OpenCV on Windows 7, using the standard python shell, I get the following behavior.
import cv
im = cv.LoadImageM("data/somefile.jpg")
thumb = cv.CreateMat(im.rows/6, im.cols/6, im.type)
print "Before"
cv.Resize(im, thumb)
print "After"
Gives:
>>> Before
========================= RESTART ==========================
No error is thrown, what should I look for? What causes such crashing in OpenCV/Python?
Most memory allocation in OpenCV is unchecked and can result in crashes. OpenCV also attempts to throw exceptions through C code, which may cause anything to happen (usually a crash) depending on how it was compiled.
Check whether the values of im.rows/6, etc. are what you expect and that the image sizes should be within python memory limits.
I had to rebuild OpenCV using Visual Studio (Express) 2010, in stead of MinGW, that did the trick, so I guess it was just a faulty build in the end.
i don't think your program is crashing,it is doing just what you are telling it to do.
See the codes below,am using openCv 2.2 with python 2.7.2.Try using WaitKey() to prevent crashes!
import cv
cv.NamedWindow("win",cv.CV_WINDOW_AUTOSIZE)
im= cv.LoadImageM("image.jpg")
thumb= cv.CreateMat(im.rows/3, im.cols/3, im.type)
cv.Resize(im, thumb)
cv.ShowImage("win",thumb)
cv.WaitKey(10000)

'module' object has no attribute 'pcapObject'

I have the following sample code which doesn't seem to want to run.
import pcap
pc = pcap.pcapObject()
dev = sys.argv[1]
pc.open_live(dev, 1600, 0, 100)
pc.setfilter("udp port 53", 0, 0)
while 1:
pc.dispatch(1, p.pcap_dispatch)
I'm really not sure why. I'm using pypcap. I'm running this on both 2.5.1 and 2.6 versions of python (separate machines) using mac osx (leopard).
At least according to documentation from the project this line:
pc = pcap.pcapObject()
Should really be:
pc = pcap.pcap()
There are two pcap libraries for Python:
pypcap
pylibpcap
Both of them are imported as:
import pcap
But the following code implies that pylibpcap is actually expected, instead of pypcap.
pcap.pcapObject()
I dont have python on this Computer, but when i look at the example, it should be
pc = pcap.pcap ()

Categories