[cura-tools] master: added 2 exceptions to clarify attribute access errors (96c70bc)
by miminar@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 96c70bcb609b143014ea1a630fdaf82bf79f0c01
Author: Michal Minar <miminar(a)redhat.com>
Date: Thu Aug 29 08:20:34 2013 +0200
added 2 exceptions to clarify attribute access errors
When accessing not registered class from namespace or not existing
part of namespace, an AttributeError was raised. Which is confusing.
Now LMIClassNotFound or LMINamespaceNotFound raised instead with
more descriptive information.
>---------------------------------------------------------------
cli/lmi/shell/LMIExceptions.py | 18 ++++++++++++++++++
cli/lmi/shell/LMINamespace.py | 6 +++++-
2 files changed, 23 insertions(+), 1 deletions(-)
diff --git a/cli/lmi/shell/LMIExceptions.py b/cli/lmi/shell/LMIExceptions.py
index e281207..d499918 100644
--- a/cli/lmi/shell/LMIExceptions.py
+++ b/cli/lmi/shell/LMIExceptions.py
@@ -68,3 +68,21 @@ class LMIFilterError(Exception):
"""
Raised, when there is a filter error present
"""
+
+class LMIClassNotFound(AttributeError):
+ """
+ Raised, when trying to access missing class in cim namespace.
+ """
+ def __init__(self, namespace, class_name):
+ AttributeError.__init__(self, 'no such class "%s" in "%s" namespace' %
+ (class_name, namespace))
+
+class LMINamespaceNotFound(AttributeError):
+ """
+ Raised, when trying to access not existing namespace from connnection
+ or namespace object.
+ """
+ def __init__(self, namespace, *args):
+ AttributeError.__init__(self, 'no such namespace "%s"' %
+ "/".join([namespace] + list(args)))
+
diff --git a/cli/lmi/shell/LMINamespace.py b/cli/lmi/shell/LMINamespace.py
index e63cc29..67c496e 100644
--- a/cli/lmi/shell/LMINamespace.py
+++ b/cli/lmi/shell/LMINamespace.py
@@ -15,6 +15,8 @@
import sys
+import LMIExceptions
+
from LMIBaseObject import LMIWrapperBaseObject
from LMIBaseClient import LMIBaseClient
@@ -49,7 +51,9 @@ class LMINamespace(LMIWrapperBaseObject):
(class_list, _, _) = self._conn._client._get_class_names(self._name, DeepInheritance=True)
if name in class_list:
return lmi_wrap_cim_class(self._conn, name, self.name)
- raise AttributeError(name)
+ if '_' in name:
+ raise LMIExceptions.LMIClassNotFound(self.name, name)
+ raise LMIExceptions.LMINamespaceNotFound(self.name, name)
def __repr__(self):
"""
10 years, 7 months
[cura-tools] master: changed dependency name (171abb1)
by miminar@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 171abb18cc3ee406cd91d76b0c09dad330513bb7
Author: Michal Minar <miminar(a)redhat.com>
Date: Fri Aug 23 06:42:46 2013 +0200
changed dependency name
Upstream lmi egg changed its name to openlmi, dependency needs to be
updated.
>---------------------------------------------------------------
cli/setup.py | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
diff --git a/cli/setup.py b/cli/setup.py
index 9753557..d7e4758 100644
--- a/cli/setup.py
+++ b/cli/setup.py
@@ -26,6 +26,6 @@ setup(
author_email="phatina(a)redhat.com",
namespace_packages=['lmi'],
packages=["lmi", "lmi.shell"],
- install_requires=["lmi"],
+ install_requires=["openlmi"],
scripts=["lmishell"]
)
10 years, 7 months
[cura-tools] master: properly handle redirected std(out|err) when prompting (49da34d)
by miminar@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 49da34dde6e67f365d8498468d828338d7bb2a1d
Author: Michal Minar <miminar(a)redhat.com>
Date: Wed Aug 21 09:20:33 2013 +0200
properly handle redirected std(out|err) when prompting
Detect, which of stdout and stderr is attached to terminal and use it
for prompt when asking for credentials. Stdout is preferred.
When stdout is redirected, readline won't have any history records. It
needs to be checked before trying to modify it.
>---------------------------------------------------------------
cli/lmi/shell/LMIConnection.py | 24 ++++++++++++++++++++----
1 files changed, 20 insertions(+), 4 deletions(-)
diff --git a/cli/lmi/shell/LMIConnection.py b/cli/lmi/shell/LMIConnection.py
index 10211dd..5dfa5fe 100644
--- a/cli/lmi/shell/LMIConnection.py
+++ b/cli/lmi/shell/LMIConnection.py
@@ -44,14 +44,28 @@ def __lmi_raw_input(prompt, use_echo=True):
prompt -- string with a prompt before the input begins
use_echo -- bool flag, which indicates, if to echo the input on the command line
"""
+ if not sys.stdout.isatty() and sys.stderr.isatty():
+ # read the input with prompt printed to stderr
+ def get_input(prompt):
+ sys.stderr.write(prompt)
+ return raw_input()
+ stream = sys.stderr
+ else:
+ # read the input with prompt printed to stdout
+ # NOTE: raw_input uses stdout only if the readline module is imported
+ get_input = raw_input
+ stream = sys.stdout
+ if not sys.stderr.isatty() and not sys.stdout.isatty():
+ LOG.warn('both stdout and stderr are detached from terminal,'
+ ' using stdout for prompt')
if not use_echo:
os.system("stty -echo")
try:
- result = raw_input(prompt)
+ result = get_input(prompt)
except EOFError, e:
if not use_echo:
os.system("stty echo")
- sys.stdout.write("\n")
+ stream.write("\n")
return None
except KeyboardInterrupt, e:
if not use_echo:
@@ -59,10 +73,12 @@ def __lmi_raw_input(prompt, use_echo=True):
raise e
if not use_echo:
os.system("stty echo")
- sys.stdout.write("\n")
+ stream.write("\n")
if result:
cur_hist_len = readline.get_current_history_length()
- readline.remove_history_item(cur_hist_len - 1)
+ if cur_hist_len > 1:
+ readline.remove_history_item(cur_hist_len - 1)
+
return result
def connect(hostname, username="", password="", interactive=False, use_cache=True,
10 years, 8 months
[cura-tools] master: ditched host parameter in CIMInstanceName creation (94b04c4)
by miminar@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 94b04c47eabacdbb8383934faf8b913553a1f5fa
Author: Michal Minar <miminar(a)redhat.com>
Date: Tue Aug 20 12:52:39 2013 +0200
ditched host parameter in CIMInstanceName creation
hostname property of LMIBaseClient may contain schema, port and possibly
other components of URL, that can not be part of hostname string. This
rendered new_instance_name() method unusable for non-trivial connections.
>---------------------------------------------------------------
cli/lmi/shell/LMIClass.py | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
diff --git a/cli/lmi/shell/LMIClass.py b/cli/lmi/shell/LMIClass.py
index 9267fc9..f03ce85 100644
--- a/cli/lmi/shell/LMIClass.py
+++ b/cli/lmi/shell/LMIClass.py
@@ -163,7 +163,7 @@ class LMIClass(LMIWrapperBaseObject):
corresponding values
"""
cim_inst_name = pywbem.CIMInstanceName(self.classname, keybindings,
- self._conn._client.hostname, self.namespace)
+ namespace=self.namespace)
return lmi_wrap_cim_instance_name(self._conn, cim_inst_name)
# NOTE: usage with Key=something, Value=something is deprecated
10 years, 8 months
[cura-tools] master: allow to customize the prompt, when asking for credentials (6b8444c)
by miminar@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 6b8444c9122c74e543151e9cb883efe45ed24aa3
Author: Michal Minar <miminar(a)redhat.com>
Date: Mon Aug 19 13:22:24 2013 +0200
allow to customize the prompt, when asking for credentials
The user can be now presented with additional information regarding a
host he tries to connect to. This can be used be lmi metacommand to
prefix the promt with hostname when connecting to multiple hosts:
$ lmi -h host1 -h host2 service start svnserve.service
$ [host1] username: ****
$ [host1] password: ****
$ [host2] username: *****
$ [host2] password: *****
>---------------------------------------------------------------
cli/lmi/shell/LMIConnection.py | 8 +++++---
1 files changed, 5 insertions(+), 3 deletions(-)
diff --git a/cli/lmi/shell/LMIConnection.py b/cli/lmi/shell/LMIConnection.py
index ef3d37f..10211dd 100644
--- a/cli/lmi/shell/LMIConnection.py
+++ b/cli/lmi/shell/LMIConnection.py
@@ -66,7 +66,7 @@ def __lmi_raw_input(prompt, use_echo=True):
return result
def connect(hostname, username="", password="", interactive=False, use_cache=True,
- verify_certificate=True):
+ verify_certificate=True, prompt_prefix=''):
"""
Returns a LMIConnection object with provided hostname and credentials.
@@ -82,6 +82,8 @@ def connect(hostname, username="", password="", interactive=False, use_cache=Tru
issued.
verify_certificate -- flag indicating, whether a server side certificate
needs to be verified, if SSL used
+ prompt_prefix -- string prefixing username and password prompts in case
+ the user is asked for credentials
"""
connection = None
netloc = urlparse.urlparse(hostname).netloc
@@ -97,9 +99,9 @@ def connect(hostname, username="", password="", interactive=False, use_cache=Tru
if interactive:
try:
if not username:
- username = __lmi_raw_input("username: ", True)
+ username = __lmi_raw_input(prompt_prefix+"username: ", True)
if not password:
- password = __lmi_raw_input("password: ", False)
+ password = __lmi_raw_input(prompt_prefix+"password: ", False)
except KeyboardInterrupt, e:
sys.stdout.write("\n")
return None
10 years, 8 months
[cura-tools] master: bump release version to v0.7 (056e4b5)
by phatina@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 056e4b5c43f6f160555741d1e76485c12fa57074
Author: Peter Hatina <phatina(a)redhat.com>
Date: Fri Aug 9 12:10:46 2013 +0200
bump release version to v0.7
>---------------------------------------------------------------
cli/lmi/shell/__init__.py | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
diff --git a/cli/lmi/shell/__init__.py b/cli/lmi/shell/__init__.py
index 271da23..775d5c9 100644
--- a/cli/lmi/shell/__init__.py
+++ b/cli/lmi/shell/__init__.py
@@ -17,7 +17,7 @@
LMIShell
"""
-__version__ = "0.6"
+__version__ = "0.7"
from LMIExceptions import *
from LMIUtil import LMIPassByRef
10 years, 8 months
[cura-tools] master: update man page (6ea7860)
by phatina@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 6ea78607c261f689bb579a6c65741c050730a839
Author: Peter Hatina <phatina(a)redhat.com>
Date: Fri Aug 9 12:10:00 2013 +0200
update man page
>---------------------------------------------------------------
man/lmishell.1 | 144 ++++++++++++++++++++++++++++++++++++++++----------------
1 files changed, 103 insertions(+), 41 deletions(-)
diff --git a/man/lmishell.1 b/man/lmishell.1
index 4eb5502..33ca818 100644
--- a/man/lmishell.1
+++ b/man/lmishell.1
@@ -1,4 +1,4 @@
-.TH lmishell "1" "July 2013" "openlmi-tools version 0.5" "User Commands"
+.TH lmishell "1" "August 2013" "openlmi-tools v0.7" "User Commands"
.SH NAME
lmishell \- (non)interactive WBEM client and interpreter.
.SH SYNOPSIS
@@ -9,11 +9,10 @@ lmishell provides a (non)interactive or interactive way how to access CIM
objects provided by OpenPegasus or sblim-sfcb CIMOM.
OpenLMI Shell is based on a python interpreter and added logic, therefore what
-you can do in pure python, it is possible in LMIShell. There are classes added
-to manipulate with CIM classes, instance names, instances, etc. Additional
-classes are added to fulfill wrapper pattern and expose only those methods,
-which are necessary for the purpose of a shell. Following scheme depicts a
-structure of the OpenLMI Shell.
+is possible to do in pure python, it is possible in LMIShell. There are classes
+added to manipulate with CIM classes, instance names, instances, etc.
+Additional classes are added to fulfill wrapper pattern and expose only those
+methods, which are necessary for the purpose of a shell.
.SH OPTIONS
The options may be given in any order before the first positional argument,
which stands for the script name.
@@ -33,6 +32,10 @@ Print all log messages to stderr.
.TP
\fB\-q\fR \fB\-\-quiet\fR
Do not print any log messages to stderr.
+.TP
+\fB\-n\fR \fB\-\-noverify\fR
+Do not verify server's certificate, if SSL used. By default, the certificate
+validity check will be performed.
.P
By default, LMIShell prints out log messages with Error severity. Options
\fB\-v\fR, \fB\-m\fR and \fB\-q\fR are mutually exclusive and
@@ -172,13 +175,22 @@ following code:
...
>
-\fBNOTE:\fR The suffix "`Values`" privides a way, hot to access ValueMap properties.
+\fBNOTE:\fR The suffix "`Values`" privides a way, how to access ValueMap properties.
To retrieve a constant value, see the next example:
> constant_value_names_lst = cls.PropertyValues.values()
> cls.PropertyValues.ConstantValueName
ConstantValue
+ > cls.PropertyValues.value("ConstantValueName")
+ ConstantValue
+ >
+.SS GET VALUEMAP PROPERTY VALUE NAME
+LMIShell can also return string representing constant value. See the following
+code:
+
+ > cls.PropertyValue.value_name(ConstantValue)
+ ConstantValueName
>
.SS GET INSTANCES
Using a class object, you can access its instances. You can easily get a list
@@ -268,14 +280,9 @@ To execute a method within an object, run this:
> instance.Method(
... Param1=value1,
... Param2=value2, ...)
- https://host: ok (0)
+ LMIReturnValue(rval=ReturnValue, rparams=ReturnParametersDictionary, errorstr="Possible error string")
>
-See the result string after a method was executed. This kind of "display
-sugar" is used only in the interactive mode. It displays a hostname, on which
-the object method was executed and its return value "ok" or "fail" (it also
-includes a return value in the parenthesis).
-
To get the result from a method call, see following:
> (rval, rparams, errorstr) = instance.Method(
@@ -283,12 +290,12 @@ To get the result from a method call, see following:
... Param2=value2, ...)
>
-The tuple in the previous example will contain retun value of the method call
+The tuple in the previous example will contain return value of the method call
(`rval`), returned parameters (`rparams`) and possible error string
(`errorstr`).
-
-The LMIShell can perform synchronous method call, which means, that the
-LMIShell is able to synchronously wait for a Job object to change its state to
+.SS SYNCHRONOUS METHODS
+LMIShell can perform synchronous method call, which means, that the LMIShell
+is able to synchronously wait for a Job object to change its state to
"finished" state and then return the job's return parameters. LMIShell can
perform the synchrous method call, if the given method returns a object of
following classes:
@@ -297,8 +304,8 @@ following classes:
* `LMI_SoftwareInstallationJob`
* `LMI_NetworkJob`
-LMIShell first tries to use indications as the waiting method, but if it
-fails, then it uses polling method instead.
+LMIShell first tries to use indications as the waiting method. If it fails,
+then it uses polling method instead.
Following example illustrates, how to perform a synchronous method call:
@@ -313,6 +320,61 @@ When a synchronous method call is done:
* `rval` will contain the job's return value
* `rparams` will contain the job's return parameters
+ * `errorstr` will contain job's possible error string
+
+It is possible to force LMIShell to use only polling method, see the next
+example:
+
+ > (rval, rparams, errorstr) = instance.SyncMethod(
+ ... PreferPolling=True,
+ ... Param1=value1,
+ ... Param2=value2, ...)
+ >
+.TP 4
+.B VALUEMAP PARAMETERS
+A CIM Method may contain ValueMap parameters (aliases for constant values) in
+its MOF definition. To access these parameters, which contain constant values,
+see following code:
+
+ > instance.Method.print_valuemap_parameters()
+ ...
+ > valuemap_parameters = instance.Method.valuemap_parameters()
+ >
+.TP 4
+.B GET VALUEMAP PARAMETER VALUE
+By using a ValueMap parameters, you can retrieve a constant value defined in
+the MOF file for a specific method. To get a list of all available constants,
+their values, use the following code:
+
+ > instance.Method.ParameterValues.print_values()
+ ...
+ >
+
+\fBNOTE:\fR The suffix "Values" privides a way, how to access ValueMap parameters.
+
+To retrieve a constant value, see the next example:
+
+ > constant_value_names_lst = instance.Method.ParameterValues.values()
+ > instance.Method.ParameterValues.ConstantValueName
+ ConstantValue
+ > instance.Method.ParameterValues.value("ConstantValueName")
+ ConstantValue
+ >
+.TP 4
+.B GET VALUEMAP PARAMETER
+Method can also contain a mapping between constant property name and
+corresponding value. Following code demonstrates, how to access such
+parameters:
+
+ > instance.Method.ConstantValueName
+.TP 4
+.B GET VALUEMAP PARAMETER VALUE NAME
+LMIShell can also return string representing constant value. See the following
+code:
+
+ > instance.Method.ParameterValue.value_name(ConstantValue)
+ ConstantValueName
+ >
.SS PROPERTIES
You can also access an instance object properties. To get a property, see the
following example.
@@ -325,7 +387,7 @@ To modify a property, execute following:
> instance.Property = NewPropertyValue
> instance.push()
- https://host: ok (0)
+ LMIReturnValue(rval=0, rparams={}, errorstr='')
>
\fBNOTE:\fR If you change an instance object property, you have to execute a `.push()` method to propagate the change to the CIMOM.
@@ -510,7 +572,8 @@ subscription, by which we can receive such event responses.
.SS SUBSCRIBING TO AN INDICATION
The shell is capable of creating an indication subscription with the filter
and handler objects in one single step. This example is based upon sblim-cmpi-
-base provider. How to subscribe to an indication, please, follow next example:
+base provider. How to subscribe to an indication, please, follow the next
+example:
> # When connecting to CIMOM, ensure, that the user account can create objects in the namespace root/PG_InterOp
> c = connect("host", "privileged_user", "password")
@@ -526,7 +589,7 @@ base provider. How to subscribe to an indication, please, follow next example:
... HandlerSystemCreationClassName="CIM_ComputerSystem",
... Destination="http://192.168.122.1:5988" # this is the destination computer, where all the indications will be delivered
... )
- https://hostname: ok (True)
+ LMIReturnValue(rval=True, rparams={}, errorstr='')
>
In this state, we have a indication subscription created.
@@ -549,7 +612,7 @@ shell quits. If you want to delete the subscriptions sooner, you can use
following methods:
> c.unsubscribe_indication(indication_name)
- https://hostname: ok (True)
+ LMIReturnValue(rval=True, rparams={}, errorstr='')
> c.unsubscribe_all_indications()
>
.SS INDICATION HANDLER
@@ -618,14 +681,6 @@ The LMIShell can also search in the history of commands by hitting ` <ctrl+r>
` and typing the command prefix (as your default shell does).
(reverse-i-search)`connect': c = connect("host", "username")
-.SS DISPLAY SUGAR
-Interactive interface by default uses "display sugar" when calling a method in
-the format `"http(s)://hostname: ok/fail (numberic_value)"` as a display
-replacement for object of a `ReturnValue` class. This feature can be disabled
-by executing:
-
- > use_display_sugar(False)
- >
.SS EXCEPTION HANDLING
Exception handling by the shell can be turned off -- since then, all the
exceptions need to be handled by your code. To allow all the exceptions to
@@ -639,7 +694,7 @@ To turn exception handling by the shell back on, run this:
> use_exceptions(False)
>
.SS CACHE
-The shell's connection objects use a temporary cache for storing CIM class
+The LMIShell's connection objects use a temporary cache for storing CIM class
names and CIM classes to save network communication.
The cache can be cleared, see following example:
@@ -649,30 +704,37 @@ The cache can be cleared, see following example:
The cache can be also turned off, see next example:
- > c.use_cache(False) # disables the cache usage
+ > c.use_cache(False)
>
.TP 4
.B TAB-COMPLETION
Interactive interface also supports tab-completion for basic programming
structures and also for CIM objects (such as namespace, classes, methods and
-properties completion, ). Following code shows a few examples:
+properties completion, ). Following code shows few examples:
- > c = conn<tab> # expands to: see next line
+ > c = conn<tab>
> c = connect(
- > lmi_service_class = c.root.c<tab> # see next line
+ > lmi_service_class = c.root.c<tab>
> lmi_service_class = c.root.cimv2
- > lmi_service_class = c.root.cimv2.lmi_ser<tab> # see next line
- > lmi_service_class = c.root.cimv2.LMI_Service # it also fixes upper/lower case in the class name
+ > lmi_service_class = c.root.cimv2.lmi_ser<tab>
+ > lmi_service_class = c.root.cimv2.LMI_Service
- > sshd_service = lmi_s<tab> # see next line
+ > sshd_service = lmi_s<tab>
> sshd_service = lmi_service_class
- > sshd_service.Stat<tab> # see next line
+ > sshd_service.Stat<tab>
> sshd_service.Status
- > sshd_service.Res<tab> # see next line
+ > sshd_service.Res<tab>
> sshd_service.RestartService(
+
+ > lmi_service_class.Req<tab>
+ > lmi_service_class.RequestedStateChangeValues
+ > lmi_service_class.RequestesStateChangeValues.Sh<tab>
+ > lmi_service_class.RequestedStateChangeValues.Shutdown
+ > # similar for method calls, as well
+ >
.SS CONFIGURATION FILE
The LMIShell has a tiny configuration file with location `~/.lmishellrc`. In
configuration file, you can set these properties:
10 years, 8 months
[cura-tools] master: introduce custom help() function (d4f169e)
by phatina@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit d4f169e7fca81c2b2b85eb4e9dfc19b7b2d36022
Author: Peter Hatina <phatina(a)redhat.com>
Date: Fri Aug 9 12:06:19 2013 +0200
introduce custom help() function
>---------------------------------------------------------------
cli/lmi/shell/LMIConsole.py | 5 +++-
cli/lmi/shell/LMIHelper.py | 54 +++++++++++++++++++++++++++++++++++++++++++
cli/lmi/shell/LMIUtil.py | 7 +++++
3 files changed, 65 insertions(+), 1 deletions(-)
diff --git a/cli/lmi/shell/LMIConsole.py b/cli/lmi/shell/LMIConsole.py
index 31cecd6..1a0bd3e 100644
--- a/cli/lmi/shell/LMIConsole.py
+++ b/cli/lmi/shell/LMIConsole.py
@@ -39,6 +39,8 @@ from LMIUtil import lmi_set_use_exceptions
from LMIUtil import lmi_get_use_exceptions
from LMIUtil import lmi_isinstance
+from LMIHelper import LMIHelper
+
class LMIConsole(code.InteractiveConsole):
"""
Class representing an interactive console.
@@ -64,7 +66,8 @@ class LMIConsole(code.InteractiveConsole):
"LMIInstanceName" : LMIObjectFactory().LMIInstanceName,
"LMIMethod" : LMIObjectFactory().LMIMethod,
"use_exceptions" : lmi_set_use_exceptions,
- "lmi_isinstance" : lmi_isinstance
+ "lmi_isinstance" : lmi_isinstance,
+ "help" : LMIHelper()
}
def __init__(self):
diff --git a/cli/lmi/shell/LMIHelper.py b/cli/lmi/shell/LMIHelper.py
new file mode 100644
index 0000000..5984db9
--- /dev/null
+++ b/cli/lmi/shell/LMIHelper.py
@@ -0,0 +1,54 @@
+# Copyright (C) 2012-2013 Peter Hatina <phatina(a)redhat.com>
+#
+# 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, see <http://www.gnu.org/licenses/>.
+
+import os
+import sys
+import subprocess
+from site import _Helper
+
+from LMIUtil import lmi_script_name
+
+class LMIHelper(_Helper):
+ """
+ LMI Helper class, which overrides python help.
+ """
+ def __repr__(self):
+ """
+ Returns a pretty string for the object.
+ """
+ return "Type help() to see man page for %s, " \
+ "or help(object) for help about object." % lmi_script_name()
+
+ def __call__(self, *args, **kwargs):
+ """
+ Executes either man page for LMIShell or prints pydoc help for an object.
+ """
+ if not args and not kwargs:
+ try:
+ # Python 3+
+ from subprocess import DEVNULL as devnull
+ devnull_close = lambda: None
+ except ImportError:
+ devnull = open(os.devnull, "wb")
+ devnull_close = lambda: devnull.close()
+ rcode = subprocess.call(["man", lmi_script_name()], stderr=devnull)
+ devnull_close()
+ if rcode > 0:
+ sys.stderr.write("Man page for %s can not be found, " % lmi_script_name())
+ sys.stderr.write("refer to Wiki page instead.\n\n")
+ sys.stderr.write("Available at: https://fedorahosted.org/openlmi/wiki/shell\n" )
+ else:
+ import pydoc
+ return pydoc.help(*args, **kwargs)
diff --git a/cli/lmi/shell/LMIUtil.py b/cli/lmi/shell/LMIUtil.py
index 990ac8d..9f34d21 100644
--- a/cli/lmi/shell/LMIUtil.py
+++ b/cli/lmi/shell/LMIUtil.py
@@ -13,6 +13,7 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
+import os
import sys
import pywbem
@@ -314,3 +315,9 @@ def lmi_isinstance(lmi_obj, lmi_class):
return True
classname = client._get_superclass(classname, namespace)
return False
+
+def lmi_script_name():
+ """
+ Returns a string of executed script.
+ """
+ return os.path.basename(sys.argv[0])
10 years, 8 months
[cura-tools] master: code cleanup, LMIFormatter, which, get_pager (c6b3f05)
by phatina@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit c6b3f05a2adc1b41e2f938be27ec880143412593
Author: Peter Hatina <phatina(a)redhat.com>
Date: Fri Aug 9 11:01:10 2013 +0200
code cleanup, LMIFormatter, which, get_pager
>---------------------------------------------------------------
cli/lmi/shell/LMIFormatter.py | 86 ++++++++++++++++++++++-------------------
1 files changed, 46 insertions(+), 40 deletions(-)
diff --git a/cli/lmi/shell/LMIFormatter.py b/cli/lmi/shell/LMIFormatter.py
index 5e139cc..cd4d3bf 100644
--- a/cli/lmi/shell/LMIFormatter.py
+++ b/cli/lmi/shell/LMIFormatter.py
@@ -26,6 +26,51 @@ from LMIUtil import lmi_raise_or_dump_exception
from LMIExceptions import LMINoPagerError
+def _is_executable(fpath):
+ """
+ Returns True, if provided path is executable, False otherwise.
+
+ Arguments:
+ fpath -- string containing a path to executable
+ """
+ return os.path.exists(fpath) and os.access(fpath, os.X_OK)
+
+def _which(program):
+ """
+ Returns a full path of a selected binary.
+
+ Arguments:
+ program -- string containing a path to executable
+ """
+ (fpath, fname) = os.path.split(program)
+ if fpath:
+ if _is_executable(program):
+ return program
+ else:
+ for path in os.environ["PATH"].split(os.pathsep):
+ exe_file = os.path.join(path, program)
+ if _is_executable(exe_file):
+ return exe_file
+ return None
+
+def _get_pager_with_params():
+ """
+ Returns a list containing a binary with its CLI arguments.
+ """
+ if "PAGER" in os.environ:
+ path = _which(os.environ["PAGER"])
+ if path:
+ return [path]
+ for p in ["less", "more"]:
+ path = _which(p)
+ if not path:
+ continue
+ elif p == "less":
+ return [path, "-S"]
+ return [path]
+ lmi_raise_or_dump_exception(LMINoPagerError("No default pager found"))
+ return []
+
class LMITextFormatter(object):
"""
Text formatter class. Used when printing a block of text to output stream.
@@ -86,45 +131,6 @@ class LMIFormatter(object):
"""
pass
- @staticmethod
- def __which(program):
- """
- Returns a full path of a selected binary. Similar to LMIShell's which.
-
- Arguments:
- program -- executable name
- """
- is_exe = lambda fpath: os.path.isfile(fpath) and os.access(fpath, os.X_OK)
- fpath, fname = os.path.split(program)
- if fpath:
- if is_exe(program):
- return program
- else:
- for path in os.environ["PATH"].split(os.pathsep):
- exe_file = os.path.join(path, program)
- if is_exe(exe_file):
- return exe_file
- return None
-
- @staticmethod
- def __get_pager():
- """
- Returns a list containing a binary with its CLI arguments.
- """
- if "PAGER" in os.environ:
- pager = os.environ["PAGER"].split()
- if os.path.exists(pager[0]) and os.access(pager[0], os.X_OK):
- return pager
- for p in ["less", "more"]:
- path = LMIFormatter.__which(p)
- if not path:
- continue
- elif p == "less":
- return [path, "-S"]
- return [path]
- lmi_raise_or_dump_exception(LMINoPagerError("No default pager found"))
- return []
-
def fancy_format(self, interactive):
"""
Formats a block of text. If the LMIShell is running in interactive
@@ -139,7 +145,7 @@ class LMIFormatter(object):
f = os.fdopen(tmpfile[0], "w")
self.format(0, 0, self._width, f)
f.close()
- subprocess_params = LMIFormatter.__get_pager()
+ subprocess_params = _get_pager_with_params()
if not subprocess_params:
return
subprocess_params.append(tmpfile[1])
10 years, 8 months
[cura-tools] master: cast constant values to native python types (46c6d40)
by phatina@fedoraproject.org
Repository : http://git.fedorahosted.org/cgit/cura-tools.git
On branch : master
>---------------------------------------------------------------
commit 46c6d40785292a39b6d0acaf590cd0fdf66c469f
Author: Peter Hatina <phatina(a)redhat.com>
Date: Fri Aug 9 10:16:21 2013 +0200
cast constant values to native python types
>---------------------------------------------------------------
cli/lmi/shell/LMIConstantValues.py | 14 +++++-----
cli/lmi/shell/LMIUtil.py | 48 +++++++++++++++++++++++++++++++----
2 files changed, 49 insertions(+), 13 deletions(-)
diff --git a/cli/lmi/shell/LMIConstantValues.py b/cli/lmi/shell/LMIConstantValues.py
index 6e564ac..002c594 100644
--- a/cli/lmi/shell/LMIConstantValues.py
+++ b/cli/lmi/shell/LMIConstantValues.py
@@ -17,7 +17,7 @@ import abc
import sys
from LMIBaseObject import LMIBaseObject
-from LMIUtil import lmi_cast_to_cim
+from LMIUtil import lmi_cast_to_lmi
class LMIConstantValues(LMIBaseObject):
"""
@@ -25,7 +25,7 @@ class LMIConstantValues(LMIBaseObject):
"""
__metaclass__ = abc.ABCMeta
- def __init__(self, cim_obj):
+ def __init__(self, cim_obj, cast_type):
"""
Constructs a object.
@@ -34,6 +34,7 @@ class LMIConstantValues(LMIBaseObject):
CIMMethod. Construction of this object requires to have a member "_cast_type"
to properly cast CIM object. When constructing defived objects, make sure,
that the mentioned member is present before calling this constructor.
+ cast_type -- parameter/property cast type
"""
# Keys can contain various undesirable characters, such as python
# operators, etc. So we drop them.
@@ -42,11 +43,12 @@ class LMIConstantValues(LMIBaseObject):
values = cim_obj.qualifiers["ValueMap"].value
self._value_map = {}
self._value_map_inv = {}
+ self._cast_type = cast_type
# Fill two dictionaries for bidirectional access to constant values.
for i in range(0, len(keys)):
try:
key = keys[i]
- val = lmi_cast_to_cim(self._cast_type, values[i])
+ val = lmi_cast_to_lmi(self._cast_type, values[i])
self._value_map[key] = val
self._value_map_inv[val] = key
except ValueError, e:
@@ -128,8 +130,7 @@ class LMIConstantValuesParamProp(LMIConstantValues):
cim_property -- CIMProperty or CIMParameter object. Both objects have
necessary member "type" which is needed for proper casting.
"""
- self._cast_type = cim_property.type
- super(LMIConstantValuesParamProp, self).__init__(cim_property)
+ super(LMIConstantValuesParamProp, self).__init__(cim_property, cim_property.type)
class LMIConstantValuesMethodReturnType(LMIConstantValues):
"""
@@ -142,5 +143,4 @@ class LMIConstantValuesMethodReturnType(LMIConstantValues):
Arguments:
cim_method -- CIMMethod object
"""
- self._cast_type = cim_method.return_type
- super(LMIConstantValuesMethodReturnType, self).__init__(cim_method)
+ super(LMIConstantValuesMethodReturnType, self).__init__(cim_method, cim_method.return_type)
diff --git a/cli/lmi/shell/LMIUtil.py b/cli/lmi/shell/LMIUtil.py
index 5954b96..990ac8d 100644
--- a/cli/lmi/shell/LMIUtil.py
+++ b/cli/lmi/shell/LMIUtil.py
@@ -124,6 +124,27 @@ def lmi_raise_or_dump_exception(e=None):
else:
raise type(e), e, tb
+def _lmi_do_cast(t, value, cast):
+ """
+ Helper function, which preforms the actual cast.
+
+ Arguments:
+ t -- string of CIM type
+ value -- variable to cast
+ cast -- dictionary with type:cast_func
+ """
+ cast_func = cast[t.lower()] if t.lower() in cast else lambda x: x
+ if isinstance(value, dict):
+ return dict(
+ zip(value.keys()),
+ map(lambda val: _lmi_do_cast(t, val, cast), value.values())
+ )
+ elif isinstance(value, list):
+ return map(lambda val: _lmi_do_cast(t, val, cast), value)
+ elif isinstance(value, tuple):
+ return tuple(map(lambda val: _lmi_do_cast(t, val, cast), value))
+ return cast_func(value)
+
def lmi_cast_to_cim(t, value):
"""
Casts the value to CIM type.
@@ -143,12 +164,27 @@ def lmi_cast_to_cim(t, value):
"uint64" : lambda x: pywbem.Uint64(x),
"reference": lambda x: x.path if isinstance(x, LMIObjectFactory().LMIInstance) else x
}
- cast_func = cast[t] if t.lower() in cast else lambda x: x
- if isinstance(value, list):
- return map(cast_func, value)
- elif isinstance(value, tuple):
- return tuple(map(cast_func, value))
- return cast_func(value)
+ return _lmi_do_cast(t, value, cast)
+
+def lmi_cast_to_lmi(t, value):
+ """
+ Casts the value to LMI (python) type.
+
+ Arguments:
+ t -- string of CIM type
+ value -- variable to cast
+ """
+ cast = {
+ "sint8" : lambda x: int(x),
+ "uint8" : lambda x: int(x),
+ "sint16" : lambda x: int(x),
+ "uint16" : lambda x: int(x),
+ "sint32" : lambda x: int(x),
+ "uint32" : lambda x: int(x),
+ "sint64" : lambda x: int(x),
+ "uint64" : lambda x: int(x),
+ }
+ return _lmi_do_cast(t, value, cast)
def lmi_wrap_cim_namespace(conn, cim_namespace_name):
"""
10 years, 8 months