Python: VMware Object data - python

How does one get all the property values from an object. For example a method returned me an object, but when I print it out there's only type and value displayed. For example I've got an ManagedObjectReference of Task named obj. If I write print obj.info an error occurs:
AttributeError: returnval instance has no attribute 'info'

If you are using PropertyCollector's RetrieveProperties, CheckForUupdates etc then in PropertyFilterSpec set PropertySpec.all=True. This will fetch all properties of the MOR. But this will be a huge performance hit. Instead I would suggest list out the properties you need in the PropertySpec.pathSet.

Related

Python AWS boto3 returning NoneType Error

I'm trying to enumerate some EC2 instance details in an AWS account using the boto3 Python module, but I keep getting an unexpected error. Specifically, I'm trying to get the tags associated with each instance.
Here is a rough copy of my code:
#!/usr/bin/python3
import boto3
import botocore
boto3_session = create_boto3_session(profile_name='some_profile')
ec2_resource = boto3_session.resource("ec2", region_name='some_region')
ec2_instances = ec2_resource.instances.all()
for ec2_instance in ec2_instances:
tags = getattr(ec2_instance, 'tags', [])
for tag in tags:
print(tag)
When the code runs, it prints the tags of the instances as expected - until it finds an instance without tags, and then I get the error:
for tag in tags:
TypeError: 'NoneType' object is not iterable
What I don't understand is why the getattr() function returns a 'NoneType', instead of an empty list like I've asked it to. Am I missing something?
I think I've found the answer. It's not specific to boto3.
When you call getattr() on an object, it only seems to return a supplied, default value if the class doesn't have a __getattr__() method implemented. If it does have that method, then it will return the value specified in __getattr__(), regardless.
This also seems to be the case for calling hasattr() on an object. It will return the value specified in __getattr__() if the method is implemented. This is somewhat counter-intuitive, because if the __getattr__() method is set to return False, then
calling hasattr() for a non-existent attribute will return True.
Would something like this work? All my instances have tags, but I think if no tags exist, you get an empty list, so you may have to check on length if an error pops up.
for ec2_instance in ec2_instances:
if ec2_instance.tags:
for tag in ec2_instance.tags:
print(tag)

Calling class methods dinamically using Python [duplicate]

I would like to call an object method dynamically.
The variable "MethodWanted" contains the method I want to execute, the variable "ObjectToApply" contains the object.
My code so far is:
MethodWanted=".children()"
print eval(str(ObjectToApply)+MethodWanted)
But I get the following error:
exception executing script
File "<string>", line 1
<pos 164243664 childIndex: 6 lvl: 5>.children()
^
SyntaxError: invalid syntax
I also tried without str() wrapping the object, but then I get a "cant use + with str and object types" error.
When not dynamically, I can just execute this code to get the desired result:
ObjectToApply.children()
How to do that dynamically?
Methods are just attributes, so use getattr() to retrieve one dynamically:
MethodWanted = 'children'
getattr(ObjectToApply, MethodWanted)()
Note that the method name is children, not .children(). Don't confuse syntax with the name here. getattr() returns just the method object, you still need to call it (jusing ()).

Changing object type from string or list [Python]

I have a small problem.
I'm trying to make a function for creating an ordered dictionary by retriving attributes of model object by the names. Models are based on data from databases and sometimes they should be converted. If list element is a string - there is no problem, ODictionary is created, and it's working. But If I want to convert for example int to string - there is a problem.
I made it with tuples. The first element is the name of new OrderedDictionary item, second should be the right type.
For example :
elementValue = getattr(element[1], element[0])
With ("id", int) i'm getting "AttributeError: type object 'int' has no attribute 'id'"
So its wrong option...
It's my first time with getattr. There is no problem with basic usage (for me) when I have to retrieve object att by the name but how to cast to different type from a given str type?
elementValue = getattr(element[1], element[0])
With ("id", int) i'm getting "AttributeError: type object 'int' has no attribute 'id'" So its wrong option...
The signature for getattr() is object, attrname[, default] - object being the object you want to get the attribute from, attrname the attribute name (as string), and default an optional default value if object has no attribute attrname (if you don't pass default and object has no attribute attrname you get an AttributeError). Obviously getattr() is not going to do any kind of type conversion, this is something you'll have to do by yourself.
You didn't post enough of your code to give you more than a few hints but assuming you have a list of ("attrname", typeconverter) (where typeconverter is any callable taking the original attribute value and returning the converted value), what you want would look something like:
def to_odict(obj, attrlist):
od = OrderedDict()
for attrname, converter in attrlist:
# TODO : error handling ???
raw_val = getattr(obj, attrname)
val = converter(raw_val)
od["attrname"] = val
return od

how to access the data of a GStreamer buffer in Python?

In the old (pre-GObject-introspection) GStreamer bindings, it was possible to access gst.Buffer data via the .data attribute or by casting to str. This is no longer possible:
>>> p buf.data
*** AttributeError: 'Buffer' object has no attribute 'data'
>>> str(buf)
'<GstBuffer at 0x7fca2c7c2950>'
To access the contents of a Gst.Buffer in recent versions, you must first map() the buffer to get a Gst.MapInfo, which has a data attribute of type bytes (str in Python 2).
(result, mapinfo) = buf.map(Gst.MapFlags.READ)
assert result
try:
# use mapinfo.data here
pass
finally:
buf.unmap(mapinfo)
You can also access the buffer's constituent Gst.Memory elements with get_memory(), and map them individually. (AFAICT, calling Buffer.map() is equivalent to calling .get_all_memory() and mapping the resulting Memory.)
Unfortunately, writing to these buffers is not possible since Python represents them with immutable types even when the Gst.MapFlags.WRITE flag is set. Instead, you'd have to do something like create a new Gst.Memory with the modified data, and use Gst.Buffer.replace_all_memory().

how to assign variable to module name in python function

I have a set of modules, and I want to be able to call one of them within a function based on an argument given to that function. I tried this, but it doesn't work:
from my.set import modules
def get_modules(sub_mod):
variable = sub_mod
mod_object = modules.variable
function(mod_object)
I get:
AttributeError: 'module' object has no attribute 'variable'
It's not taking the argument I give it, which would be the name of a module that exists under my.set.modules. so if I called the function get_modules(name_of_mod_under_modules), I would like the line modules.variable to be "modules.name_of_mod_under_modules" which I could then have as an object passed to mod_object.
In your current code, you're looking for modules.variable which doesn't exist, hence the error! That's not how you get an attribute of an object.
To achieve what you wanted, use the getattr function.
mod_object = getattr(modules, variable)

Categories