问题
In Python, I am populating an object to model the configuration, environment and other aspects related to rsyslog on the local machine (RHEL 6.4 Python 2.6.4) I loop through many instances of the rsyslog daemon (this_instance_number), and many attributes (attribute) defined in a configuration file.
With those value I populate the object.
Given the following variables:
this_instance_number=5
attribute="startupscript"
The following line of code,
print ('rsyslog.instance%(instance_number)s.%(attribute)s' %\
{"instance_number": this_instance_number, "attribute": attribute})
will print this text:
rsyslog.instance5.startupscript
How can I then assign the attribute that text would refer to to a value based on that format string?
For example, if hard coded, I would assign:
rsyslog.instance5.startupscript="/etc/init.d/sample"
But, I want to assign it something like this:
('rsyslog.instance%(instance_number)s.%(attribute)s' %\
{"instance_number": this_instance_number, "attribute": attribute}) = variable
回答1:
You'd use getattr() to dynamically retrieve attributes:
instance = getattr(rsyslog, 'instance{}'.format(this_instance_number))
print getattr(instance, attribute)
and setattr() to assign:
instance = getattr(rsyslog, 'instance{}'.format(this_instance_number))
setattr(instance, attribute, variable)
or, for a more generic approach with arbitrary depth:
def get_deep_attr(obj, *path):
return reduce(getattr, path, obj)
def set_deep_attr(obj, value, *path)
setattr(get_deep_attr(obj, path[:-1]), path[-1], value)
print get_deep_attr(rsyslog, 'instance{}'.format(this_instance_number), attribute)
set_deep_attr(rsyslog, variable, 'instance{}'.format(this_instance_number), attribute)
来源:https://stackoverflow.com/questions/22349233/how-to-use-string-formatting-to-dynamically-assign-variables