Getting CPU information from Python WMI - python

I am trying to get some system information from Pythons WMI module however allot of the methods mention online don't seem to be working. I know it is easier to do it in other languages but I want to try and do this in Python for reasons.
I have tried using the Win32_TemperatureProbe() method but I get a return value of None. I have also tried the MSAcpi_ThermalZoneTemperature() and the error for that is below. I have been doing my research and can't seem to find any alternative methods or fixes to these errors. There seem to be allot of threads open but none solved.
Here is my current code:
import wmi, platform
#Initiating WMI
c = wmi.WMI(namespace="root\\wmi")
#Setting variables
drive_letter, free_space = [], []
stats = {}
#Getting basic infromation
print(platform.processor())
print(c.MSAcpi_ThermalZoneTemperature()[0].CurrentTemperature/10.0)-273.15
for disk in c.Win32_LogicalDisk(["Caption","FreeSpace"], DriveType=3):
free_space_GB = round(int((disk.FreeSpace))/1073741824, 2)
drive_letter.append(str(disk.Caption))
free_space.append(str(free_space_GB))
stats = {"Free Space":free_space, "Drive Letter":drive_letter}
print(stats)
and here is the output I get when running this code:
Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\wmi.py", line 817, in query
return self._namespace.query (wql, self, fields)
File "C:\Python34\lib\site-packages\wmi.py", line 1009, in query
return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
File "C:\Python34\lib\site-packages\wmi.py", line 1009, in <listcomp>
return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 247, in __getitem__
return self._get_good_object_(self._enum_.__getitem__(index))
File "C:\Python34\lib\site-packages\win32com\client\util.py", line 37, in __getitem__
return self.__GetIndex(index)
File "C:\Python34\lib\site-packages\win32com\client\util.py", line 53, in __GetIndex
result = self._oleobj_.Next(1)
pywintypes.com_error: (-2147217396, 'OLE error 0x8004100c', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Brandyn\Desktop\Performance_monitor.py", line 12, in <module>
print(c.MSAcpi_ThermalZoneTemperature()[0].CurrentTemperature/10.0)-273.15
File "C:\Python34\lib\site-packages\wmi.py", line 819, in query
handle_com_error ()
File "C:\Python34\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217396, 'OLE error 0x8004100c', None, None)>
When I change the namespace to null, the error changes to this:
Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\wmi.py", line 1145, in __getattr__
return self._cached_classes (attribute)
File "C:\Python34\lib\site-packages\wmi.py", line 1156, in _cached_classes
self._classes_map[class_name] = _wmi_class (self, self._namespace.Get (class_name))
File "<COMObject winmgmts:>", line 3, in Get
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemServicesEx', 'Not found ', None, 0, -2147217406), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Brandyn\Desktop\Performance_monitor.py", line 12, in <module>
print(c.MSAcpi_ThermalZoneTemperature()[0].CurrentTemperature/10.0)-273.15
File "C:\Python34\lib\site-packages\wmi.py", line 1147, in __getattr__
return getattr (self._namespace, attribute)
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: winmgmts:.MSAcpi_ThermalZoneTemperature
Is there a fix to this method or is there another viable alternative or should I just simply stop this and focus on a different language?

I had the same issue.
For Win32_LogicalDisk, you need to replace namespace root\\wmi with root\\cimv2.
Then it worked for me on Win7.
For MSAcpi_ThermalZoneTemperature, I have not found a solution. The object looks as follows
>>> print c.MSAcpi_ThermalZoneTemperature
[dynamic: ToInstance, provider("WMIProv"), WMI, guid("{A1BC18C0-A7C8-11d1-BF3C-00A0C9062910}")]
class MSAcpi_ThermalZoneTemperature : MSAcpi
{
[key, read] string InstanceName;
[read] boolean Active;
[WmiDataId(1), read] uint32 ThermalStamp;
[WmiDataId(2), read] uint32 ThermalConstant1;
[WmiDataId(3), read] uint32 ThermalConstant2;
[WmiDataId(4), read] uint32 Reserved;
[WmiDataId(5), read] uint32 SamplingPeriod;
[WmiDataId(6), read] uint32 CurrentTemperature;
[WmiDataId(7), read] uint32 PassiveTripPoint;
[WmiDataId(8), read] uint32 CriticalTripPoint;
[WmiDataId(9), read] uint32 ActiveTripPointCount;
[WmiDataId(10), MissingValue(0), read, MAX(10)] uint32 ActiveTripPoint[];
};
BUT c.MSAcpi_ThermalZoneTemperature.CurrentTemperature returns None.
Interesting is if we run folliwing code
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\WMI")
colItems = objSWbemServices.ExecQuery("SELECT * FROM MSAcpi_ThermalZoneTemperature")
print repr(colItems)
print len(colItems)
then calling print repr(colItems) returns <COMObject <unknown>>
and calling print len(colItems) generates an exception:
Traceback (most recent call last):
File "get_wmi_test1.py", line 45, in <module>
print len(colItems)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 228, in
__len__
return self._oleobj_.Invoke(dispid, LCID, invkind, 1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectSet'
, u'Not supported ', None, 0, -2147217396), None)
I looked a bit around and seems to be more complex issue. Look here:
MSAcpi_ThermalZoneTemperature not showing temperature
How to enable WMI on windows 7

Related

Can't write on XML file due to (TypeError: argument of type 'int' is not iterable) using ElementTree in Python

I keep getting
Traceback (most recent call last):
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 1076, in _escape_attrib
if "&" in text:
TypeError: argument of type 'int' is not iterable
when I'm trying to write an XML file with some attributes I need to edit.
Here's my code:
import xml.etree.ElementTree as ET
tree = ET.parse('TM_GeneralSettings.xml')
root = tree.getroot()
for item in root.iter('Control'):
numX = int(((720/1080)*float(item.attrib.get('LocationX'))))
numY = int(((720 / 1080) * float(item.attrib.get('LocationY'))))
numW = int(((720 / 1080) * float(item.attrib.get('SizeW'))))
numH = int(((720 / 1080) * float(item.attrib.get('SizeH'))))
print(numX, ':', numY, ':', numW, ':', numH)
item.set('LocationX', numX)
item.set('LocationY', numY)
item.set('LocationW', numW)
item.set('LocationH', numH)
tree.write('TM_GeneralSettings2.xml')
I also get this errors when I run my code:
Traceback (most recent call last):
File "/Users/alessandrochiodo/PycharmProjects/pythonProject/main.py", line 17, in <module>
tree.write('TM_GeneralSettings2.xml')
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 772, in write
serialize(write, self._root, qnames, namespaces,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 937, in _serialize_xml
_serialize_xml(write, e, qnames, None,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 930, in _serialize_xml
v = _escape_attrib(v)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 1099, in _escape_attrib
_raise_serialization_error(text)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 1053, in _raise_serialization_error
raise TypeError(
TypeError: cannot serialize 0 (type int)
Can someone help me? I can't find a solution.

How do I reformat this json for database import?

I have these "json" files that I like to insert into my mongodb database.
An example of one is:
http://s.live.ksmobile.net/cheetahlive/de/ff/15201023827214369775/15201023827214369775.json
The problem is, that it is formated like this:
{ "channelType":"TEMPGROUP", ... } # line 1
{ "channelType":"TEMPGROUP", ... } # line 2
So instead of inserting it as 1 document in the DB, it insert every single line as 1 entry. That ends up with what should be 3 documents from 3 "json" files in the database become 1189 documents in the database instead.
How can I insert the whole content of the ".json" into one document?
My code is:
replay_url = "http://live.ksmobile.net/live/getreplayvideos?"
userid = 969730808384462848
url2 = replay_url + urllib.parse.urlencode({'userid': userid}) + '&page_size=1000'
raw_replay_data = requests.get(url2).json()
for i in raw_replay_data['data']['video_info']:
url3 = i['msgfile']
raw_message_data = urllib.request.urlopen(url3)
for line in raw_message_data:
json_data = json.loads(line)
messages.insert_one(json_data)
print(json_data)
Update to give more information to answer
messages.insert(json_data) gives this error:
Traceback (most recent call last):
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/collection.py", line 633, in _insert
blk.execute(concern, session=session)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/bulk.py", line 432, in execute
return self.execute_command(generator, write_concern, session)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/bulk.py", line 329, in execute_command
raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/import_messages_dev.py", line 43, in <module>
messages.insert(json_data)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/collection.py", line 2941, in insert
check_keys, manipulate, write_concern)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/collection.py", line 635, in _insert
_raise_last_error(bwe.details)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/helpers.py", line 220, in _raise_last_error
_raise_last_write_error(write_errors)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/helpers.py", line 188, in _raise_last_write_error
raise DuplicateKeyError(error.get("errmsg"), 11000, error)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: liveme.messages.$_id_ dup key: { : ObjectId('5aa2fc6f5d60126499060949') }
messages.insert_one(json_data) gives me this error:
Traceback (most recent call last):
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/import_messages_dev.py", line 43, in <module>
messages.insert_one(json_data)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/collection.py", line 676, in insert_one
common.validate_is_document_type("document", document)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/common.py", line 434, in validate_is_document_type
"collections.MutableMapping" % (option,))
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
messages.insert_many(json_data) gives me this error:
Traceback (most recent call last):
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/import_messages_dev.py", line 43, in <module>
messages.insert_many(json_data)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/collection.py", line 742, in insert_many
blk.execute(self.write_concern.document, session=session)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/bulk.py", line 432, in execute
return self.execute_command(generator, write_concern, session)
File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/bulk.py", line 329, in execute_command
raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred
messages.insert and messages.insert_many both insert 1 line and throw the error.
These files obviously do not contain properly formatted json - rather they contain a separate object on each line.
To turn them into valid json, you probably want a list of objects, i.e.:
[{ "channelType":"TEMPGROUP", ... },
{ "channelType":"TEMPGROUP", ... }]
You can achieve this by doing:
for i in raw_replay_data['data']['video_info']:
url3 = i['msgfile']
raw_message_data = urllib.request.urlopen(url3)
json_data = []
for line in raw_message_data:
json_data.append(json.loads(line))
messages.insert_one(json_data)
print(json_data)

error when serializing calendar event

I am trying to modify calendars using the python caldav library (version 0.5.0) on python 2.7. I am using the following code snippet to add an exdate to recurring events
for event in results:
vevent = event.instance.vevent
if vevent.status.value != "CANCELLED":
if (vevent.summary.value, vevent.dtstart.value) in cancelled:
ev = calendar.event_by_uid(vevent.uid.value)
ev.instance.vevent.add("exdate").value = vevent.dtstart.value
print ev.instance.vevent.serialize()
Although the vobject library claims support for datetime objects the last line fails with:
Traceback (most recent call last):
File "./caldavTest.py", line 31, in <module>
print ev.instance.vevent.serialize()
File "/usr/lib/python2.7/site-packages/vobject/base.py", line 254, in serialize
return behavior.serialize(self, buf, lineLength, validate)
File "/usr/lib/python2.7/site-packages/vobject/behavior.py", line 166, in serialize
out = base.defaultSerialize(transformed, buf, lineLength)
File "/usr/lib/python2.7/site-packages/vobject/base.py", line 1007, in defaultSerialize
child.serialize(outbuf, lineLength, validate=False)
File "/usr/lib/python2.7/site-packages/vobject/base.py", line 254, in serialize
return behavior.serialize(self, buf, lineLength, validate)
File "/usr/lib/python2.7/site-packages/vobject/behavior.py", line 160, in serialize
transformed = obj.transformFromNative()
File "/usr/lib/python2.7/site-packages/vobject/base.py", line 226, in transformFromNative
raise NativeError(msg, lineNumber)
vobject.base.NativeError: "In transformFromNative, unhandled exception on line None <type 'exceptions.TypeError'>: 'datetime.datetime' object has no attribute '__getitem__'"
Any ideas?

TypeError: <function context_today at 0xaaa7064> is not JSON serializable

I need to return date to the date field when i change my division
Here is my Python code
tea_worker_ids = self.pool.get('bpl.worker').search(cr, uid, [('bpl_division_id', '=', division_id), ('default_work', '=', 'tea')])
for record in self.pool.get('bpl.worker').browse(cr, uid, tea_worker_ids):
tea_list_data.append({'worker_id': record.id, 'worker_emp_no': record.emp_no, 'is_selected':True,'date': (fields.date.context_today)})#
tea_v['selected_tea_workers'] = tea_list_data
this is the error
2013-05-13 06:22:28,810 15393 ERROR ABC werkzeug: Error on request:
Traceback (most recent call last):
File "/usr/share/pyshared/werkzeug/serving.py", line 159, in run_wsgi
execute(app)
File "/usr/share/pyshared/werkzeug/serving.py", line 146, in execute
application_iter = app(environ, start_response)
File "/usr/share/pyshared/simplejson/__init__.py", line 286, in dumps
return _default_encoder.encode(obj)
File "/usr/share/pyshared/simplejson/encoder.py", line 226, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/share/pyshared/simplejson/encoder.py", line 296, in iterencode
return _iterencode(o, 0)
File "/usr/share/pyshared/simplejson/encoder.py", line 202, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <function context_today at 0xaaa7064> is not JSON serializable
please help me to sort this issue,
EDITED
when it changed to fields.date.context_today()
then error comes as below
File "/home/bellvantage/Documents/openerp-7.0/openerp-7/openerp/addons/bpl/bpl.py", line 1059, in on_change_division
workers_list.append({'worker_id': record.id,'start_date': fields.date.context_today()})
TypeError: context_today() takes at least 3 arguments (0 given)
Looks like context_today is a method, not a value. You need to call it:
tea_list_data.append({'worker_id': record.id, 'worker_emp_no': record.emp_no,
'is_selected':True,'date': (fields.date.context_today())})
its worked with
workers_list.append({'worker_id': record.id, 'start_date': time.strftime('%Y-%m-%d'), 'selected':True})
Here fields.date.context_today is a method, so you need to pass argument, so it will be look like,
tea_list_data.append({'worker_id': record.id, 'worker_emp_no': record.emp_no,
'is_selected':True,
'date': (fields.date.context_today(self,cr,uid,context=context))})

Why is this python WMI call giving me an error?

Ok, I am pretty clueless here. I use the python WMI module to do the following command:
sj = wmi.Win32_ScheduledJob
sj.Create("cmd", 0x40000000, 32, 1, 0, "******153000.000000-420")
And that gives me the following error:
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
sj.Create("cmd", 0x40000000, 32, 1, 0, "******153000.000000-420")
File "C:\Python25\lib\site-packages\wmi.py", line 431, in __call__
handle_com_error ()
File "C:\Python25\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
x_wmi: <x_wmi: Unexpected COM Error (-2147352567, 'Exception occurred.', (0, u'SWbemProperty', u'Type mismatch ', None, 0, -2147217403), None)>
Ok, so could you tell me what arguments I am providing wrong? Please give me sample code. Thanks!
Does it make any difference if you format the StartTime argument with 8 initial * characters instead of 6?
I just notice that the Win32_ScheduledJob documentation seems to indicate 8 *s, in place of the omitted YYYYMMDD characters...

Categories

Resources