Exemplo n.º 1
0
    def browserObj(self):
        from objbrowser import browse
        objstr = self.sender().text()

        def getRootObj(objstr):
            if objstr in self.locals:
                return self.locals[objstr]
            elif objstr in self.globals:
                return self.globals[objstr]
            else:
                return None

        if '.' not in objstr:
            obj = getRootObj(objstr)
            if obj:
                browse(obj)
            else:
                print("root obj not found")
        else:
            objlist = objstr.split('.')
            ret = getRootObj(objlist[0])
            if ret:
                try:
                    for attr in objlist[1:]:
                        ret = getattr(ret, attr)
                    browse(ret)
                except Exception as e:
                    print(e)
            else:
                print("root obj not found")
Exemplo n.º 2
0
def main():
    utc_now = datetime.utcnow()
    lst = [5, 6, 7]
    if 1:
        browse(locals(), "locals")
    else:
        browse(locals())
Exemplo n.º 3
0
def my_browse(*args, **kwargs):
    """ Creates and starts an ObjectBrowser with modified summary column.
    """
    attribute_columns = copy.deepcopy(DEFAULT_ATTR_COLS)
    summary_column = [col for col in attribute_columns if col.name == 'summary'][0]
    summary_column.data_fn = my_summary
    return browse(*args, attribute_columns = attribute_columns, **kwargs)
Exemplo n.º 4
0
def call_viewer_small_test():
    """ Test procedure. 
    """
    a = 6
    b = ['seven', 'eight']
    nested_list = [5, 6, 'a', ['r', 2, []], (a, b), range(1, 100)]
    exit_code = browse(obj = nested_list, obj_name='nested_list', show_root_node = True)
    return exit_code
Exemplo n.º 5
0
def my_browse(*args, **kwargs):
    """ Creates and starts an ObjectBrowser with added sqrt columns.
    """
    doc_str = "The sqrt of an object if it can be calculated"
    width = 120 # pixels
    
    # 1: The data_fn should be a TreeItem to string (or unicode) function. If you have 
    #    a function with one input and one output parameter (e.g. the sqrt function), 
    #    you must wrap it with a lambda expression like this.
    sqrt_attr_model_1 = AttributeModel('sqrt 1', 
        doc         = doc_str, 
        data_fn     = lambda tree_item: str(sqrt(tree_item.obj)),
        col_visible = True,
        width       = width,   
        alignment   = Qt.AlignRight) 

    # 2) Example 1 above displays an error message in the cell in case of an exception.
    #    To prevent this, you can use the safe_tio_call that that returns an empty  
    #    string in case of an exception.
    sqrt_attr_model_2 = AttributeModel('sqrt 2', 
        doc         = doc_str, 
        data_fn     = lambda tree_item: safe_tio_call(sqrt, tree_item),
        col_visible = True,
        width       = width,   
        alignment   = Qt.AlignRight) 
    
    # 3) Of course you can also write a wrapper function yourself.
    sqrt_attr_model_3 = AttributeModel('sqrt 3', 
        doc         = doc_str, 
        data_fn     = safe_tio_sqrt,
        col_visible = True,
        width       = width,   
        alignment   = Qt.AlignRight) 

    # 4) The simplest solution is to use the safe_data_fn function which creates the
    #    wrapped function.
    sqrt_attr_model_4 = AttributeModel('sqrt 4', 
        doc         = doc_str, 
        data_fn     = safe_data_fn(sqrt),
        col_visible = True,
        width       = width,   
        alignment   = Qt.AlignRight) 

    attribute_columns = list(DEFAULT_ATTR_COLS)
    attribute_columns.insert(5, sqrt_attr_model_1)
    attribute_columns.insert(6, sqrt_attr_model_2)
    attribute_columns.insert(7, sqrt_attr_model_3)
    attribute_columns.insert(8, sqrt_attr_model_4)
    
    # You can also add the attribute to the details pane
    attribute_details = list(DEFAULT_ATTR_DETAILS)
    attribute_details.insert(0, sqrt_attr_model_1)
    
    return browse(*args, 
                  attribute_columns = attribute_columns,
                  attribute_details = attribute_details,  
                  **kwargs)
Exemplo n.º 6
0
def main():
    """ Main program to test stand alone 
    """
    logging_basic_config('DEBUG')
    logger.info('Started example')

    fig1 = make_fig('figure1')
    exit_code = browse(fig1, name='fig1', show_special_attributes=False)

    logging.info('Done example')
    sys.exit(exit_code)
Exemplo n.º 7
0
def my_browse(*args, **kwargs):
    """ Creates and starts an ObjectBrowser with added sqrt column.
    """
    sqrt_attr_model = AttributeModel('sqrt', 
        doc         = "The sqrt of an object if it can be calculated", 
        data_fn     = safe_data_fn(sqrt),
        col_visible = True,
        width       = 120,   
        alignment   = Qt.AlignRight) 

    attribute_columns = list(DEFAULT_ATTR_COLS)
    attribute_columns.insert(5, sqrt_attr_model)
    
    return browse(*args, attribute_columns = attribute_columns, **kwargs)
Exemplo n.º 8
0
def my_browse(*args, **kwargs):
    """ Creates and starts an ObjectBrowser for showing unicode properties
    """
    # Use some standard columns with adjusted widths
    attribute_columns = copy.deepcopy([ATTR_MODEL_NAME, ATTR_MODEL_UNICODE, ATTR_MODEL_REPR])
    for attr_col in attribute_columns:
        attr_col.width = SMALL_COL_WIDTH
    
    # Add columns from the Unicode database
    function_settings = [(unicodedata.name, True, 300), 
                         (unicodedata.decimal, False, SMALL_COL_WIDTH),
                         (unicodedata.digit, False, SMALL_COL_WIDTH),
                         (unicodedata.numeric, False, SMALL_COL_WIDTH),
                         (unicodedata.category, True, SMALL_COL_WIDTH),
                         (unicodedata.bidirectional, False, SMALL_COL_WIDTH),
                         (unicodedata.combining, False, SMALL_COL_WIDTH),
                         (unicodedata.east_asian_width, False, SMALL_COL_WIDTH),
                         (unicodedata.mirrored, False, SMALL_COL_WIDTH),
                         (unicodedata.decomposition, False, SMALL_COL_WIDTH)]
    
    for function, visible, width in function_settings:
        attr_model = AttributeModel(function.__name__, 
            doc         = "Character meta data from the {!r} function".format(function.__name__), 
            data_fn     = safe_data_fn(function),
            col_visible = visible,
            width       = width)
        
        attribute_columns.append(attr_model) 
    
    overview_model = AttributeModel("Overview", 
        doc         = "Character overview", 
        data_fn     = overview)
    
    return browse(*args, 
                  attribute_columns = attribute_columns,
                  attribute_details = [overview_model], 
                  **kwargs)
Exemplo n.º 9
0
def main():
    utc_now = datetime.utcnow()
    lst = [5, 6, 7]
    browse(locals())
Exemplo n.º 10
0
    exit_code = execute()
    return exit_code
    

def call_viewer_small_test():
    """ Test procedure. 
    """
    try:
        raise ValueError("my value error")
    except ValueError, ex:
        my_value_error = ex

    a = 6
    b = ['seven', 'eight']
    nested_list = [5, 6, 'a', ['r', 2, []], (a, b), range(1, 100), my_value_error]
    exit_code = browse(obj = nested_list, obj_name='nested_list', show_root_node = True)
    return exit_code
    
        
def main():
    """ Main program to test stand alone 
    """
    logging_basic_config('DEBUG')
    logger.info('Started example')
    
    if 1:
        exit_code = call_viewer_test()
    else: 
        exit_code = call_viewer_small_test() 
    
    logging.info('Done example')
Exemplo n.º 11
0
def call_viewer_test():
    """ Test procedure. 
    """
    import types, os
    from os.path import join
    
    if 1:
        # In Python 3 there is no OldStyleClass anymore. The definition below will result in a 
        # new style class as well.
        class OldStyleClass: 
            """ An old style class (pre Python 2.2)
                See: http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes
            """
            static_member = 'static_value'
            def __init__(self, s, i):
                'constructor'            
                self._member_str = s
                self.__member_int = i
                
        class NewStyleClass(object):
            """ A new style class (Python 2.2 and later). Note it inherits 'object'.
                See: http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes
            """
            static_member = 'static_value'
            def __init__(self, s, i):
                'constructor'
                self._member_str = s
                self.__member_int = i
                
            @property
            def member_int(self):
                return self.__member_int
                
            @member_int.setter
            def member_int(self, value):
                self.__member_int = value
                
            def method(self):
                pass
         
            @staticmethod       
            def static_method(self):
                pass
            
            @classmethod       
            def class_method(self):
                pass
        
        old_style_object = OldStyleClass('member_value', 44)    
        new_style_object = NewStyleClass('member_value', -66)    

    # Some comments just above
    # the function definition.
    def my_function(param):
        "demo function"
        return param
    
    _copyright = types.__builtins__['copyright'] 
    
    x_plus_2 = lambda x: x+2
    
    Int = int
    a = 6
    b = 'seven'
    c = 8j + 3 # complex number
    d = {'4': 44, 's': 11, c: None}
    e = 2.718281828
    f_large = 7.77e14 # different str and repr?
    f_avogadro = 6.02214129e23
    ellip = Ellipsis
    my_slice = slice(None, 3, -1)
    n = None
    not_impl = NotImplemented
    tup = ('this', 'is', 'a tuple')
    lst = [4, '4', d, ['r', dir], main]
    my_set = set([3, 4, 4, 8])
    my_frozenset = frozenset([3, 4, 5, 6, 6])
    
    dict_regular = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
    dict_ordered = OrderedDict(sorted(dict_regular.items(), key=lambda t: t[1])) # sorted by value

    __special_dict_item__ = """A variable that begins and end with to underscores but is a
        dictionary item, opposed to an attribute. It should therefore always be displayed, even
        if the 'show __special_attributes__' view option is toggled off
    """

    dt_now = dt.datetime.now()
    date_now = dt.date(2014, 3, 23) 
    date_first = date_now.min
    date_last = date_now.max
    
    t = dt.time(13, 33, 1)
    
    try:
        import numpy as np
    except ImportError as ex:
        logger.warn(ex)
    else:
        arr = np.arange(24, dtype=np.uint16).reshape(8, 3)
        pi_16bit = np.float16(np.pi)

    try:
        import serial
    except ImportError as ex:
        logger.warn(ex)
    else:
        # PySerial object. Does not work if the port/device is closed. I cannot fix this.
        ser = serial.Serial()

    
    # These will give error in the str() representation. 
    # I deliberately did not use string.encode('ascii', 'backslashreplace') to 
    # demonstrate the difference between str() and repr()
    u1 = six.unichr(40960) + u'ab\ncd' + six.unichr(1972)
    u2 = u"a\xac\u1234\u20ac\U00008000"
    u3 = u'all ASCII chars'
    multi_line_str = """hello\r\nworld
                        the\rend."""
    
    browse(locals(), reset = False, # without obj_name
           show_special_attributes = None,
           show_callable_attributes = None)
    if 0: 
        browse(globals(), name = 'globals()',
               attribute_columns = ALL_ATTR_MODELS, 
               attribute_details = ALL_ATTR_MODELS[1:4])