/usr/lib/python2.7/dist-packages/igraph/configuration.py is in python-igraph 0.7.1.post6-5.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""
Configuration framework for igraph.
igraph has some parameters which usually affect the behaviour of many functions.
This module provides the framework for altering and querying igraph parameters
as well as saving them to and retrieving them from disk.
"""
__license__ = """\
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
from ConfigParser import SafeConfigParser
import platform
import os.path
def get_platform_image_viewer():
"""Returns the path of an image viewer on the given platform"""
plat = platform.system()
if plat == "Darwin":
# Most likely Mac OS X
return "open"
elif plat == "Linux":
# Linux has a whole lot of choices, try to find one
choices = ["eog", "gthumb", "gqview", "kuickshow", "xnview", "display",
"gpicview", "gwenview", "qiv", "gimv", "ristretto"]
paths = ["/usr/bin", "/bin"]
for path in paths:
for choice in choices:
full_path = os.path.join(path, choice)
if os.path.isfile(full_path):
return full_path
return ""
elif plat == "Windows" or plat == "Microsoft": # Thanks to Dale Hunscher
# Use the built-in Windows image viewer, if available
return "start"
else:
# Unknown system
return ""
class Configuration(object):
"""Class representing igraph configuration details.
General ideas
=============
The configuration of igraph is stored in the form of name-value pairs.
This object provides an interface to the configuration data using the
syntax known from dict:
>>> c=Configuration()
>>> c["general.verbose"] = True
>>> print c["general.verbose"]
True
Configuration keys are organized into sections, and the name to be used
for a given key is always in the form C{section.keyname}, like
C{general.verbose} in the example above. In that case, C{general} is the
name of the configuration section, and C{verbose} is the name of the key.
If the name of the section is omitted, it defaults to C{general}, so
C{general.verbose} can be referred to as C{verbose}:
>>> c=Configuration()
>>> c["verbose"] = True
>>> print c["general.verbose"]
True
User-level configuration is stored in C{~/.igraphrc} per default on Linux
and Mac OS X systems, or in C{C:\\Documents and Settings\\username\\.igraphrc}
on Windows systems. However, this configuration is read only when C{igraph}
is launched through its shell interface defined in L{igraph.app.shell}.
This behaviour might change before version 1.0.
Known configuration keys
========================
The known configuration keys are presented below, sorted by section. When
referring to them in program code, don't forget to add the section name,
expect in the case of section C{general}.
General settings
----------------
These settings are all stored in section C{general}.
- B{shells}: the list of preferred Python shells to be used with the
command-line C{igraph} script. The shells in the list are tried one
by one until any of them is found on the system. C{igraph} functions
are then imported into the main namespace of the shell and the shell
is launched. Known shells and their respective class names to be
used can be found in L{igraph.app.shell}. Example:
C{IPythonShell, ClassicPythonShell}. This is the default, by the way.
- B{verbose}: whether L{igraph} should talk more than really necessary.
For instance, if set to C{True}, some functions display progress bars.
Application settings
--------------------
These settings specify the external applications that are possibly
used by C{igraph}. They are all stored in section C{apps}.
- B{image_viewer}: image viewer application. If set to an empty string,
it will be determined automatically from the platform C{igraph} runs
on. On Mac OS X, it defaults to the Preview application. On Linux,
it chooses a viewer from several well-known Linux viewers like
C{gthumb}, C{kuickview} and so on (see the source code for the full
list). On Windows, it defaults to the system's built-in image viewer.
Plotting settings
-----------------
These settings specify the default values used by plotting functions.
They are all stored in section C{plotting}.
- B{layout}: default graph layout algorithm to be used.
- B{mark_groups}: whether to mark the clusters by polygons when
plotting a clustering object.
- B{palette}: default palette to be used for converting integer
numbers to colors. See L{colors.Palette} for more information.
Valid palette names are stored in C{colors.palettes}.
- B{wrap_labels}: whether to try to wrap the labels of the
vertices automatically if they don't fit within the vertex.
Default: C{False}.
Remote repository settings
--------------------------
These settings specify how igraph should access remote graph repositories.
Currently only the Nexus repository is supported. All these settings are
stored in section C{remote}.
- B{nexus.url}: the root URL of the Nexus repository. Default:
C{http://nexus.igraph.org}.
Shell settings
--------------
These settings specify options for external environments in which igraph is
embedded (e.g., IPython and its Qt console). These settings are stored in
section C{shell}.
- B{ipython.inlining.Plot}: whether to show instances of the L{Plot} class
inline in IPython's console if the console supports it. Default: C{True}
@undocumented: _item_to_section_key, _types, _sections, _definitions, _instance
"""
# pylint: disable-msg=R0903
# R0903: too few public methods
class Types(object):
"""Static class for the implementation of custom getter/setter functions
for configuration keys"""
def __init__(self):
pass
@staticmethod
def setboolean(obj, section, key, value):
"""Sets a boolean value in the given configuration object.
@param obj: a configuration object
@param section: the section of the value to be set
@param key: the key of the value to be set
@param value: the value itself. C{0}, C{false}, C{no} and C{off}
means false, C{1}, C{true}, C{yes} and C{on} means true,
everything else results in a C{ValueError} being thrown.
Values are case insensitive
"""
value = str(value).lower()
if value in ("0", "false", "no", "off"):
value = "false"
elif value in ("1", "true", "yes", "on"):
value = "true"
else:
raise ValueError("value cannot be coerced to boolean type")
obj.set(section, key, value)
@staticmethod
def setint(obj, section, key, value):
"""Sets an integer value in the given configuration object.
@param obj: a configuration object
@param section: the section of the value to be set
@param key: the key of the value to be set
@param value: the value itself.
"""
obj.set(section, key, str(int(value)))
@staticmethod
def setfloat(obj, section, key, value):
"""Sets a float value in the given configuration object.
Note that float values are converted to strings in the configuration
object, which may lead to some precision loss.
@param obj: a configuration object
@param section: the section of the value to be set
@param key: the key of the value to be set
@param value: the value itself.
"""
obj.set(section, key, str(float(value)))
_types = {
"boolean": {
"getter": SafeConfigParser.getboolean,
"setter": Types.setboolean
},
"int": {
"getter": SafeConfigParser.getint,
"setter": Types.setint
},
"float": {
"getter": SafeConfigParser.getfloat,
"setter": Types.setfloat
}
}
_sections = ("general", "apps", "plotting", "remote", "shell")
_definitions = {
"general.shells": {
"default": "IPythonShell,ClassicPythonShell"
},
"general.verbose": {
"default": True,
"type": "boolean"
},
"apps.image_viewer": {
"default": get_platform_image_viewer()
},
"plotting.layout": {
"default": "auto"
},
"plotting.mark_groups": {
"default": False,
"type": "boolean"
},
"plotting.palette": {
"default": "gray"
},
"plotting.wrap_labels": {
"default": False,
"type": "boolean"
},
"remote.nexus.url": {
"default": "http://nexus.igraph.org"
},
"shell.ipython.inlining.Plot": {
"default": True,
"type": "boolean"
}
}
# The singleton instance we are using throughout other modules
_instance = None
def __init__(self, filename=None):
"""Creates a new configuration instance.
@param filename: file or file pointer to be read. Can be omitted.
"""
self._config = SafeConfigParser()
self._filename = None
# Create default sections
for sec in self._sections:
self._config.add_section(sec)
# Create default values
for name, definition in self._definitions.iteritems():
if "default" in definition:
self[name] = definition["default"]
if filename is not None:
self.load(filename)
@property
def filename(self):
"""Returns the filename associated to the object.
It is usually the name of the configuration file that was used when
creating the object. L{Configuration.load} always overwrites it with
the filename given to it. If C{None}, the configuration was either
created from scratch or it was updated from a stream without name
information."""
return self._filename
def _get(self, section, key):
"""Internal function that returns the value of a given key in a
given section."""
definition = self._definitions.get("%s.%s" % (section, key), {})
getter = None
if "type" in definition:
getter = self._types[definition["type"]].get("getter")
if getter is None:
getter = self._config.__class__.get
return getter(self._config, section, key)
@staticmethod
def _item_to_section_key(item):
"""Converts an item description to a section-key pair.
@param item: the item to be converted
@return: if C{item} contains a period (C{.}), it is splitted into two parts
at the first period, then the two parts are returned, so the part before
the period is the section. If C{item} does not contain a period, the
section is assumed to be C{general}, and the second part of the returned
pair contains C{item} unchanged"""
if "." in item:
section, key = item.split(".", 1)
else:
section, key = "general", item
return section, key
def __contains__(self, item):
"""Checks whether the given configuration item is set.
@param item: the configuration key to check.
@return: C{True} if the key has an associated value, C{False} otherwise.
"""
section, key = self._item_to_section_key(item)
return self._config.has_option(section, key)
def __getitem__(self, item):
"""Returns the given configuration item.
@param item: the configuration key to retrieve.
@return: the configuration value"""
section, key = self._item_to_section_key(item)
if key == "*":
# Special case: retrieving all the keys within a section and
# returning it in a dict
keys = self._config.items(section)
return dict((key, self._get(section, key)) for key, _ in keys)
else:
return self._get(section, key)
def __setitem__(self, item, value):
"""Sets the given configuration item.
@param item: the configuration key to set
@param value: the new value of the configuration key
"""
section, key = self._item_to_section_key(item)
definition = self._definitions.get("%s.%s" % (section, key), {})
setter = None
if "type" in definition:
setter = self._types[definition["type"]].get("setter", None)
if setter is None:
setter = self._config.__class__.set
return setter(self._config, section, key, value)
def __delitem__(self, item):
"""Deletes the given item from the configuration.
If the item has a default value, the default value is written back instead
of the current value. Without a default value, the item is really deleted.
"""
section, key = self._item_to_section_key(item)
definition = self._definitions.get("%s.%s" % (section, key), {})
if "default" in definition:
self[item] = definition["default"]
else:
self._config.remove_option(section, key)
def has_key(self, item):
"""Checks if the configuration has a given key.
@param item: the key being sought"""
if "." in item:
section, key = item.split(".", 1)
else:
section, key = "general", item
return self._config.has_option(section, key)
def load(self, stream=None):
"""Loads the configuration from the given file.
@param stream: name of a file or a file object. The configuration will be loaded
from here. Can be omitted, in this case, the user-level configuration is
loaded.
"""
stream = stream or get_user_config_file()
if isinstance(stream, basestring):
stream = open(stream, "r")
file_was_open = True
self._config.readfp(stream)
self._filename = getattr(stream, "name", None)
if file_was_open:
stream.close()
def save(self, stream=None):
"""Saves the configuration.
@param stream: name of a file or a file object. The configuration will be saved
there. Can be omitted, in this case, the user-level configuration file will
be overwritten.
"""
stream = stream or get_user_config_file()
if not hasattr(stream, "write") or not hasattr(stream, "close"):
stream = open(stream, "w")
file_was_open = True
self._config.write(stream)
if file_was_open:
stream.close()
@classmethod
def instance(cls):
"""Returns the single instance of the configuration object."""
if cls._instance is None:
cfile = get_user_config_file()
try:
config = cls(cfile)
except IOError:
# No config file yet, whatever
config = cls()
cls._instance = config
return cls._instance
def get_user_config_file():
"""Returns the path where the user-level configuration file is stored"""
return os.path.expanduser("~/.igraphrc")
def init():
"""Default mechanism to initiate igraph configuration
This method loads the user-specific configuration file from the
user's home directory, or if it does not exist, creates a default
configuration.
The method is safe to be called multiple times, it will not parse
the configuration file twice.
@return: the L{Configuration} object loaded or created."""
return Configuration.instance()
|