Пример #1
0
def show_generators(parent):
    dialog = gtk.Dialog('Value Generators', parent,
                        gtk.DialogFlags.DESTROY_WITH_PARENT,
                        (gtk.STOCK_CLOSE, gtk.ResponseType.OK))

    L = gtk.Label()
    scroll = gtk.ScrolledWindow()
    scroll.set_size_request(550, 400)
    scroll.set_shadow_type(gtk.ShadowType.ETCHED_IN)

    scroll.add_with_viewport(L)
    dialog.vbox.pack_start(scroll, True, True, 0)
    dialog.show_all()

    td = pydoc.TextDoc()

    text = list()
    for f in functions.registered.items():
        s = td.docroutine(f[1].__init__)
        text.append( '<b>{f}</b>:  {doc}' \
          .format(f=f[0],doc=s[ (s.find('method')+6): ] ))

    text = '\n'.join(text)
    L.set_markup(text)

    # Close dialog on user response
    dialog.connect("response", lambda d, r: d.destroy())
    dialog.show()
Пример #2
0
def test_pydoc():
    """
    Verify that public items show up in pydoc output while private items do not
    """
    pytest.debug_func()
    present = ['__call__', '__eq__', '__init__', '__repr__', '__str__',
               'dst',
               'epoch',
               'localtime',
               'class duration',
               'class Indexable',
               'class moment',
               'class month',
               'class week',
               'class Parser',
               'class prepositions',
               'class time_units',
               'class Stub',
               'class InitError',
               ]

    absent = ['_DAY', '_end_of_day', '_end_of_month', '_end_of_week',
              '_guess_format', '_MONTHS', '_MONTH_LEN', '_nl_match',
              '_parse_return', '_WEEK', '_week_ago', '_WEEKDAYS',
              'month_index', 'month_names', 'weekday_index', 'weekday_names',
              'parse'
              ]

    docker = pydoc.TextDoc()
    result = re.sub("\x08.", "", docker.document(nldt))
    for item in present:
        assert item in result
    for item in absent:
        pattern = r"\W" + item + r"\W"
        assert not re.search(pattern, result)
Пример #3
0
    def __init__(self, func, cachedir, ignore=None, mmap_mode=None,
                 compress=False, verbose=1, timestamp=None):
        """
            Parameters
            ----------
            func: callable
                The function to decorate
            cachedir: string
                The path of the base directory to use as a data store
            ignore: list or None
                List of variable names to ignore.
            mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
                The memmapping mode used when loading from cache
                numpy arrays. See numpy.load for the meaning of the
                arguments.
            compress : boolean, or integer
                Whether to zip the stored data on disk. If an integer is
                given, it should be between 1 and 9, and sets the amount
                of compression. Note that compressed arrays cannot be
                read by memmapping.
            verbose: int, optional
                Verbosity flag, controls the debug messages that are issued
                as functions are evaluated. The higher, the more verbose
            timestamp: float, optional
                The reference time from which times in tracing messages
                are reported.
            immutable: If True then numpy arrays are replaced with

        """
        Logger.__init__(self)
        self.mmap_mode = mmap_mode
        self.func = func
        if ignore is None:
            ignore = []
        self.ignore = ignore

        self._verbose = verbose
        self.cachedir = cachedir
        self.compress = compress
        if compress and self.mmap_mode is not None:
            warnings.warn('Compressed results cannot be memmapped',
                          stacklevel=2)
        if timestamp is None:
            timestamp = time.time()
        self.timestamp = timestamp
        mkdirp(self.cachedir)
        try:
            functools.update_wrapper(self, func)
        except:
            " Objects like ufunc don't like that "
        if inspect.isfunction(func):
            doc = pydoc.TextDoc().document(func)
            # Remove blank line
            doc = doc.replace('\n', '\n\n', 1)
            # Strip backspace-overprints for compatibility with autodoc
            doc = re.sub('\x08.', '', doc)
        else:
            # Pydoc does a poor job on other objects
            doc = func.__doc__
        self.__doc__ = 'Memoized version of %s' % doc
Пример #4
0
def main():
    parser = argparse.ArgumentParser(prog=os.path.basename(__file__),
                                     description=__doc__)
    parser.add_argument('-D',
                        '--docstrings',
                        action='store_true',
                        help='show all the docstrings using pydoc')
    parser.add_argument(
        '-v',
        '--verbose',
        action='store_true',
        help='turn on verbosity and debug-level debugging output',
    )
    options = parser.parse_args()
    logging.basicConfig(
        format=
        '%(asctime)-15s  %(levelname)s  %(filename)s:%(lineno)d  %(message)s',
        level=(logging.DEBUG if options.verbose else logging.INFO))
    if options.docstrings:
        doc = pydoc.TextDoc()
        pager = pydoc.getpager()
        pager(doc.docmodule(sys.modules[__name__]))
    else:
        suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
        unittest.TextTestRunner(
            verbosity=(2 if options.verbose else 0)).run(suite)
Пример #5
0
def cmd_doc(ch, cmd, arg):
    """Return Python documentation for the specified module, class, function,
       etc... for example:
       
       > doc char.Char

       Will return all available documentation for the Char class.
    """
    if arg == "":
        ch.page("\r\n".join(display.pagedlist({ "Topics" : suggested_reading },
                                              header = "Suggested doc readings include:")))
    else:
        # just because sometimes I forget periods
        arg = arg.replace(" ", ".")

        # are we looking for a shortcut value?
        if arg in shortcuts:
            arg = shortcuts[arg]

        # try to find what we're documenting
        todoc = pydoc.locate(arg)
        if todoc == None:
            ch.send("Could not find Python documentation on: '%s'" % arg)
        else:
            doc = pydoc.TextDoc()
            ch.page(doc.document(todoc).replace("{", "{{"))
Пример #6
0
    def test_builtin_with_more_than_four_children(self):
        """Tests help on builtin object which have more than four child classes.

        When running help() on a builtin class which has child classes, it
        should contain a "Built-in subclasses" section and only 4 classes
        should be displayed with a hint on how many more subclasses are present.
        For example:

        >>> help(object)
        Help on class object in module builtins:

        class object
         |  The most base type
         |
         |  Built-in subclasses:
         |      async_generator
         |      BaseException
         |      builtin_function_or_method
         |      bytearray
         |      ... and 82 other subclasses
        """
        doc = pydoc.TextDoc()
        text = doc.docclass(object)
        snip = (" |  Built-in subclasses:\n"
                " |      async_generator\n"
                " |      BaseException\n"
                " |      builtin_function_or_method\n"
                " |      bytearray\n"
                " |      ... and \\d+ other subclasses")
        self.assertRegex(text, snip)
Пример #7
0
    def test_builtin_with_child(self):
        """Tests help on builtin object which have only child classes.

        When running help() on a builtin class which has child classes, it
        should contain a "Built-in subclasses" section. For example:

        >>> help(ArithmeticError)
        Help on class ArithmeticError in module builtins:

        class ArithmeticError(Exception)
         |  Base class for arithmetic errors.
         |
         ...
         |
         |  Built-in subclasses:
         |      FloatingPointError
         |      OverflowError
         |      ZeroDivisionError
        """
        doc = pydoc.TextDoc()
        text = doc.docclass(ArithmeticError)
        snip = (" |  Built-in subclasses:\n"
                " |      FloatingPointError\n"
                " |      OverflowError\n"
                " |      ZeroDivisionError")
        self.assertIn(snip, text)
Пример #8
0
    def test_builtin_no_child(self):
        """Tests help on builtin object which have no child classes.

        When running help() on a builtin class which has no child classes, it
        should not contain any "Built-in subclasses" section. For example:

        >>> help(ZeroDivisionError)

        Help on class ZeroDivisionError in module builtins:

        class ZeroDivisionError(ArithmeticError)
         |  Second argument to a division or modulo operation was zero.
         |
         |  Method resolution order:
         |      ZeroDivisionError
         |      ArithmeticError
         |      Exception
         |      BaseException
         |      object
         |
         |  Methods defined here:
         ...
        """
        doc = pydoc.TextDoc()
        text = doc.docclass(ZeroDivisionError)
        # Testing that the subclasses section does not appear
        self.assertNotIn('Built-in subclasses', text)
Пример #9
0
    def test_builtin_with_grandchild(self):
        """Tests help on builtin classes which have grandchild classes.

        When running help() on a builtin class which has child classes, it
        should contain a "Built-in subclasses" section. However, if it also has
        grandchildren, these should not show up on the subclasses section.
        For example:

        >>> help(Exception)
        Help on class Exception in module builtins:

        class Exception(BaseException)
         |  Common base class for all non-exit exceptions.
         |
         ...
         |
         |  Built-in subclasses:
         |      ArithmeticError
         |      AssertionError
         |      AttributeError
         ...
        """
        doc = pydoc.TextDoc()
        text = doc.docclass(Exception)
        snip = (" |  Built-in subclasses:\n"
                " |      ArithmeticError\n"
                " |      AssertionError\n"
                " |      AttributeError")
        self.assertIn(snip, text)
        # Testing that the grandchild ZeroDivisionError does not show up
        self.assertNotIn('ZeroDivisionError', text)
Пример #10
0
def execute_command(the_command, m):
    '''Find the_command amongst the list of commands like cmd_one in module m
    
    This returns a string containing the response, or a -1 if a quit is commanded.'''
    the_functions = dict(checkTemperature=m.cmd_checkTemperature,
                         setTemperature=m.cmd_setTemperature,
                         establishLink=m.cmd_establishLink,
                         closeLink=m.cmd_closeLink,
                         getCCDParams=m.cmd_getCCDParams,
                         enableRegulation=m.cmd_enableRegulation,
                         disableRegulation=m.cmd_disableRegulation,
                         changeBinning=m.cmd_changeBinning,
                         imageType=m.cmd_imageType,
                         exposeAndWait=m.cmd_exposeAndWait,
                         abortExposure=m.cmd_abortExposure)
    commands = string.split(the_command)
    if len(commands) == 0:
        return ""
    if commands[0] == "help":
        if (len(commands) == 1):
            return 'checkTemperature\nsetTemperature\nestablishLink\ncloseLink\ngetCCDParams\nenableRegulation\ndisableRegulation\nchangeBinning\nimageType\nexposeAndWait\nabortExposure'
        elif commands[1] in the_functions:
            td = pydoc.TextDoc()
            return td.docroutine(the_functions[commands[1]])
        else:
            return "ERROR: " + commands[1] + " is not a valid command."
    elif commands[0] == 'exit' or commands[0] == 'bye' or commands[0] == 'quit':
        return -1
    elif commands[0] in the_functions:
        return the_functions[commands[0]](the_command)
    else:
        return "ERROR: Command not found."
Пример #11
0
def get_pydoc_link(module):
    "Returns a documentation web link of a module"
    dirname = os.path.dirname
    basedir = dirname(dirname(os.path.realpath(__file__)))
    doc = pydoc.TextDoc()
    loc = doc.getdocloc(module, basedir=basedir)
    return loc
Пример #12
0
def execute_command(the_command, m):
    '''Find the_command amongst the list of commands like cmd_one in module m
    
    This returns a string containing the response, or a -1 if a quit is commanded.'''
    the_functions = dict(humidity=m.cmd_humidity,
                         temperature=m.cmd_temperature,
                         ljtemp=m.cmd_ljtemp,
                         status=m.cmd_status,
                         numHomes=m.cmd_numHomes,
                         dome=m.cmd_dome,
                         slits=m.cmd_slits,
                         ok=m.cmd_ok,
                         BackLED=m.cmd_BackLED)
    commands = string.split(the_command)
    if len(commands) == 0:
        return ""
    if commands[0] == "help":
        if (len(commands) == 1):
            return 'humidity\ntemperature\nljtemp\nstatus\nnumHomes\ndome\nslits\nok\nBackLED'
        elif commands[1] in the_functions:
            td = pydoc.TextDoc()
            return td.docroutine(the_functions[commands[1]])
        else:
            return "ERROR: " + commands[1] + " is not a valid command."
    elif commands[0] == 'exit' or commands[0] == 'bye' or commands[0] == 'quit':
        return -1
    elif commands[0] in the_functions:
        return the_functions[commands[0]](the_command)
    else:
        return "ERROR: Command not found."
Пример #13
0
def execute_command(the_command, m):
    '''Find the_command amongst the list of commands like cmd_one in module m
    
    This returns a string containing the response, or a -1 if a quit is commanded.'''
    the_functions = dict(clarity=m.cmd_clarity,
                         light=m.cmd_light,
                         rain=m.cmd_rain,
                         tempair=m.cmd_tempair,
                         tempsky=m.cmd_tempsky,
                         status=m.cmd_status,
                         safe=m.cmd_safe)
    commands = string.split(the_command)
    if len(commands) == 0:
        return ""
    if commands[0] == "help":
        if (len(commands) == 1):
            return 'clarity\nlight\nrain\ntempair\ntempsky\nstatus\nsafe'
        elif commands[1] in the_functions:
            td = pydoc.TextDoc()
            return td.docroutine(the_functions[commands[1]])
        else:
            return "ERROR: " + commands[1] + " is not a valid command."
    elif commands[0] == 'exit' or commands[0] == 'bye' or commands[0] == 'quit':
        return -1
    elif commands[0] in the_functions:
        return the_functions[commands[0]](the_command)
    else:
        return "ERROR: Command not found."
Пример #14
0
 def __init__(self,
              func,
              cachedir,
              ignore=None,
              save_npy=True,
              mmap_mode=None,
              verbose=1,
              timestamp=None):
     """
         Parameters
         ----------
         func: callable
             The function to decorate
         cachedir: string
             The path of the base directory to use as a data store
         ignore: list or None
             List of variable names to ignore.
         save_npy: boolean, optional
             If True, numpy arrays are saved outside of the pickle
             files in the cache, as npy files.
         mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
             The memmapping mode used when loading from cache
             numpy arrays. See numpy.load for the meaning of the
             arguments. Only used if save_npy was true when the
             cache was created.
         verbose: int, optional
             Verbosity flag, controls the debug messages that are issued
             as functions are revaluated. The higher, the more verbose
         timestamp: float, optional
             The reference time from which times in tracing messages
             are reported.
     """
     Logger.__init__(self)
     self._verbose = verbose
     self.cachedir = cachedir
     self.func = func
     self.save_npy = save_npy
     self.mmap_mode = mmap_mode
     if timestamp is None:
         timestamp = time.time()
     self.timestamp = timestamp
     if ignore is None:
         ignore = []
     self.ignore = ignore
     if not os.path.exists(self.cachedir):
         os.makedirs(self.cachedir)
     try:
         functools.update_wrapper(self, func)
     except:
         " Objects like ufunc don't like that "
     if inspect.isfunction(func):
         doc = pydoc.TextDoc().document(func).replace('\n', '\n\n', 1)
     else:
         # Pydoc does a poor job on other objects
         doc = func.__doc__
     self.__doc__ = 'Memoized version of %s' % doc
Пример #15
0
def get_pydoc_text(module):
    """Returns pydoc generated output as text"""
    doc = pydoc.TextDoc()
    loc = doc.getdocloc(pydoc_mod) or ''
    if loc:
        loc = '\nMODULE DOCS\n    ' + loc + '\n'
    output = doc.docmodule(module)
    patt = re.compile('\x08.')
    output = patt.sub('', output)
    return output.strip(), loc
Пример #16
0
 def __init__(self,
              func,
              cachedir,
              ignore=None,
              mmap_mode=None,
              compress=False,
              verbose=1,
              timestamp=None):
     """
         Parameters
         ----------
         func: callable
             The function to decorate
         cachedir: string
             The path of the base directory to use as a data store
         ignore: list or None
             List of variable names to ignore.
         mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
             The memmapping mode used when loading from cache
             numpy arrays. See numpy.load for the meaning of the
             arguments.
         verbose: int, optional
             Verbosity flag, controls the debug messages that are issued
             as functions are revaluated. The higher, the more verbose
         timestamp: float, optional
             The reference time from which times in tracing messages
             are reported.
     """
     Logger.__init__(self)
     self._verbose = verbose
     self.cachedir = cachedir
     self.func = func
     self.mmap_mode = mmap_mode
     self.compress = compress
     if compress and mmap_mode is not None:
         warnings.warn('Compressed results cannot be memmapped',
                       stacklevel=2)
     if timestamp is None:
         timestamp = time.time()
     self.timestamp = timestamp
     if ignore is None:
         ignore = []
     self.ignore = ignore
     mkdirp(self.cachedir)
     try:
         functools.update_wrapper(self, func)
     except:
         " Objects like ufunc don't like that "
     if inspect.isfunction(func):
         doc = pydoc.TextDoc().document(func).replace('\n', '\n\n', 1)
     else:
         # Pydoc does a poor job on other objects
         doc = func.__doc__
     self.__doc__ = 'Memoized version of %s' % doc
Пример #17
0
def get_pydoc_text(module):
    "Returns pydoc generated output as text"
    doc = pydoc.TextDoc()
    loc = doc.getdocloc(pydoc_mod) or ""
    if loc:
        loc = "\nMODULE DOCS\n    " + loc + "\n"

    output = doc.docmodule(module)

    # clean up the extra text formatting that pydoc performs
    patt = re.compile('\b.')
    output = patt.sub('', output)
    return output.strip(), loc
Пример #18
0
    def __init__(self,
                 func,
                 location,
                 backend='local',
                 ignore=None,
                 mmap_mode=None,
                 compress=False,
                 verbose=1,
                 timestamp=None):
        Logger.__init__(self)
        self.mmap_mode = mmap_mode
        self.compress = compress
        self.func = func

        if ignore is None:
            ignore = []
        self.ignore = ignore
        self._verbose = verbose

        # retrieve store object from backend type and location.
        self.store_backend = _store_backend_factory(
            backend,
            location,
            verbose=verbose,
            backend_options=dict(compress=compress, mmap_mode=mmap_mode),
        )
        if self.store_backend is not None:
            # Create func directory on demand.
            self.store_backend.\
                store_cached_func_code([_build_func_identifier(self.func)])

        if timestamp is None:
            timestamp = time.time()
        self.timestamp = timestamp
        try:
            functools.update_wrapper(self, func)
        except:
            " Objects like ufunc don't like that "
        if inspect.isfunction(func):
            doc = pydoc.TextDoc().document(func)
            # Remove blank line
            doc = doc.replace('\n', '\n\n', 1)
            # Strip backspace-overprints for compatibility with autodoc
            doc = re.sub('\x08.', '', doc)
        else:
            # Pydoc does a poor job on other objects
            doc = func.__doc__
        self.__doc__ = 'Memoized version of %s' % doc

        self._func_code_info = None
        self._func_code_id = None
Пример #19
0
def full_help(module):
    placeholder = object()
    orig_all = getattr(module, "__all__", placeholder)

    module.__all__ = dir(module)
    try:
        # pydoc is using backspace to bold output
        # https://stackoverflow.com/questions/6827011/decoding-a-string-in-python-with-x08-x08-d-x08de-x08el-x08li-x08it-x08te
        return re.sub(r".\x08", "", pydoc.TextDoc().docmodule(module))
    finally:
        if orig_all is placeholder:
            del module.__all__
        else:
            module.__all__ = orig_all
Пример #20
0
    def test_class_dir_for_help(self):
        """
        should not cause pydoc.TextDoc().docclass() to raise AttributeError.
        This method is used internally by the help() function, and if it cannot
        resolve the class of even one attribute (as in the case of the
        attributes delegated to the Relation class), the help text will be
        blank. I know this is a huge hack, so if you can think of a better way
        to do it, please do so!

        """
        try:
            pydoc.TextDoc().docclass(DirModel)
        except AttributeError, ex:
            self.fail('expected call not to raise an exception.\n' +
                      'Exception was: %s' % repr(ex))
Пример #21
0
def document_function(handle,
                      module_name,
                      function_name,
                      new_name,
                      pkg_name=None):
    module = import_module(module_name)
    function = getattr(module, function_name)
    handle.write(
        '### %s%s.%s()\n\n' %
        ('%s.' % pkg_name if pkg_name else '', new_name, function_name))
    handle.write('```\n')
    handle.write('from %s%s import %s\n' %
                 ('%s.' % pkg_name, new_name, function_name))
    handle.write('help(%s)\n' % function_name)
    handle.write(pydoc.plain(pydoc.TextDoc().docroutine(function)))
    handle.write('```\n')
Пример #22
0
 def execute_command(self, the_command):
     '''Find the_command amongst the list of commands like cmd_one in module m
 
     This returns a string containing the response, or a -1 if a quit is commanded.'''
     m = self.module_with_functions
     the_functions = dict(open=m.cmd_open,
                          initialize=m.cmd_initialize,
                          close=m.cmd_close,
                          heater=m.cmd_heater,
                          setgain=m.cmd_setgain,
                          seti=m.cmd_seti,
                          setnestgain=m.cmd_setnestgain,
                          setnesti=m.cmd_setnesti,
                          getvs=m.cmd_getvs,
                          gettemp=m.cmd_gettemp,
                          getresistance=m.cmd_getresistance,
                          lqgstart=m.cmd_lqgstart,
                          lqgsilent=m.cmd_lqgsilent,
                          lqgverbose=m.cmd_lqgverbose,
                          startrec=m.cmd_startrec,
                          stoprec=m.cmd_stoprec,
                          lqgstop=m.cmd_lqgstop,
                          pidstart=m.cmd_pidstart,
                          pidstop=m.cmd_pidstop,
                          cryostart=m.cmd_cryostart,
                          cryostop=m.cmd_cryostop,
                          setpoint=m.cmd_setpoint)
     commands = the_command.split()
     #Make sure we ignore case.
     commands[0] = commands[0].lower()
     if len(commands) == 0:
         return ""
     if commands[0] == "help":
         if (len(commands) == 1):
             return '** Available Commands **\nexit\nopen\ninitialize\nclose\nheater\nsetgain\nseti\nsetnestgain\nsetnesti\ngetvs\ngettemp\ngetresistance\nlqgstart\nlqgsilent\nlqgverbose\nstartrec\nstoprec\nlqgstop\npidstart\npidstop\ncryostart\ncryostop\nsetpoint\n'
         elif commands[1] in the_functions:
             td = pydoc.TextDoc()
             return td.docroutine(the_functions[commands[1]])
         else:
             return "ERROR: " + commands[1] + " is not a valid command."
     elif commands[0] == 'exit' or commands[0] == 'bye' or commands[
             0] == 'quit':
         return -1
     elif commands[0] in the_functions:
         return the_functions[commands[0]](the_command)
     else:
         return "ERROR: Command not found - {0:s} ".format(commands[0])
Пример #23
0
def execute_command(the_command, m):
    '''Find the_command amongst the list of commands like cmd_one in module m
    
    This returns a string containing the response, or a -1 if a quit is commanded.'''
    the_functions = dict(checkTemperature=m.cmd_checkTemperature,
                         setTemperature=m.cmd_setTemperature,
                         establishLink=m.cmd_establishLink,
                         closeLink=m.cmd_closeLink,
                         getCCDParams=m.cmd_getCCDParams,
                         enableRegulation=m.cmd_enableRegulation,
                         disableRegulation=m.cmd_disableRegulation,
                         changeBinning=m.cmd_changeBinning,
                         imageType=m.cmd_imageType,
                         exp=m.cmd_exp,
                         exposeAndWait=m.cmd_exposeAndWait,
                         abortExposure=m.cmd_abortExposure,
                         ljtemp=m.cmd_ljtemp,
                         heater=m.cmd_heater,
                         backLED=m.cmd_backLED,
                         ippower=m.cmd_ippower,
                         agitator=m.cmd_agitator,
                         status=m.cmd_status,
                         inject=m.cmd_inject,
                         abortLoop=m.cmd_abortLoop,
                         pulse=m.cmd_pulse,
                         object=m.cmd_object,
                         servo=m.cmd_servo,
                         spectemp=m.cmd_spectemp,
                         pa=m.cmd_pa,
                         mov_rhoth=m.cmd_mov_rhoth)
    commands = string.split(the_command)
    if len(commands) == 0:
        return ""
    if commands[0] == "help":
        if (len(commands) == 1):
            return 'checkTemperature\nsetTemperature\nestablishLink\ncloseLink\ngetCCDParams\nenableRegulation\ndisableRegulation\nchangeBinning\nimageType\nexp\nexposeAndWait\nabortExposure\nljtemp\nheater\nbackLED\nippower\nagitator\nstatus\ninject\nabortLoop\nled\npulse\nobject\nservo\nspectemp\npa\nmov_rhoth'
        elif commands[1] in the_functions:
            td = pydoc.TextDoc()
            return td.docroutine(the_functions[commands[1]])
        else:
            return "ERROR: " + commands[1] + " is not a valid command."
    elif commands[0] == 'exit' or commands[0] == 'bye' or commands[0] == 'quit':
        return -1
    elif commands[0] in the_functions:
        return the_functions[commands[0]](the_command)
    else:
        return "ERROR: Command not found - {0:s} ".format(commands[0])
Пример #24
0
def hgd_mk_pydoc():
    """ Generate HGD Python documentation """

    outdir = "pydoc"
    if (not os.path.exists(outdir)):
        os.mkdir(outdir)

    # HTML doc disabled for now
    #for doctype in ["txt", "html"]:
    for doctype in ["txt"]:

        if (not os.path.exists(outdir + "/" + doctype)):
            os.mkdir(outdir + "/" + doctype)

        if (doctype == ("txt")):
            d = pydoc.TextDoc()
        else:
            d = pydoc.HTMLDoc()

        # first make top level docs
        f = open("%s/%s/index.%s" % (outdir, doctype, doctype), "w")

        if (doctype == "html"):
            content = d.page("HGD Python API", d.docmodule(sys.modules["hgd"]))
        else:
            content = d.docmodule(sys.modules["hgd"])

        f.write(content)
        f.close()

        # now each module in the hgd package which is not builtin
        mods = ["hgd.playlist", "hgd.doccer"]

        for mod in mods:
            f = open("%s/%s/%s.%s" % (outdir, doctype, mod, doctype), "w")

            if (doctype == "html"):
                content = d.page("HGD Python API",
                                 d.docmodule(sys.modules[mod]))
            else:
                content = d.docmodule(sys.modules[mod])

            f.write(content)
            f.close()

    return 0
Пример #25
0
def DevHelp(arg, full=0, device_list=[None]):
    import pydoc
    import MDSplus

    if isinstance(arg, MDSplus.TreeNode):
        try:
            elt = int(arg.conglomerate_elt)
            if elt == 0:
                return ""
            if elt == 1:
                return DevHelp(arg.record.model, full)
            else:
                cls = arg.head.record.getDevice()
                return cls.parts[elt-2].get('help', "")
        except Exception as e:
            return "ERROR: %s" % (e,)
    else:
        full = int(full)
        devtype = arg.upper()
        if device_list[0] is None:
            alldevices = MDSplus.Data.execute('MDSDEVICES()')
            device_list[0] = [item[0].strip() for item in alldevices]
        if ('*' in devtype) or ('?' in devtype):
            devnames = []
            for device in device_list[0]:
                if MDSplus.Data.execute(
                        'MdsShr->StrMatchWild(descr($), descr($))',
                        (device.upper(), devtype)) & 1:
                    devnames.append(DevHelp(device, -1))
            return '\n'.join(devnames)
        else:
            try:
                cls = MDSplus.Device.PyDevice(devtype)
                if full == 1:
                    return pydoc.TextDoc().docclass(cls)
                elif full == -1:
                    return "%s: python device" % devtype
                else:
                    return cls.__doc__
            except Exception as e:
                for device in device_list[0]:
                    if device.upper() == devtype:
                        return "%s: tdi, java or shared library device" % (
                                device,)
                return "Error obtaining help on device %s: %s" % (devtype, e)
Пример #26
0
def query_alg_tooltip(widget, x, y, keyboard_tip, tooltip):
    is_row, x, y, algs, path, iter = widget.get_tooltip_context(
        x, y, keyboard_tip)
    if not is_row:
        return False

    iter = algs.get_iter(path[0:1])  # only consider root for alg
    alg, = algs.get(iter, algs.LABEL)

    td = pydoc.TextDoc()
    markup = td.docroutine(algorithms[alg]['actual_func'])
    markup = ''.join(re.split('\x08.', markup))
    markup = '\n'.join(markup.split('\n')[0:20])
    markup += '\n...\n<b>For more, see scipy.optimize</b>'
    tooltip.set_markup(markup)
    widget.set_tooltip_row(tooltip, path)

    return True
Пример #27
0
def main():
    print(hello("world"), "*HELLO*")
    print(bye("world"), "*BYE*")

    print(hello.args[0]("WORLD"))
    import inspect

    print("**", inspect.getdoc(hello))

    import pydoc
    d = pydoc.TextDoc()
    print(d.docroutine(boo))
    print(d.docroutine(hello))

    class Doc(pydoc.TextDoc):
        pass

    print(inspect.isroutine(hello), inspect.signature(hello))
Пример #28
0
def show_arbwavefunctions(parent):
    from ..processor.engine import Arbwave
    dialog = gtk.Dialog('Arbwave functions', parent,
                        gtk.DialogFlags.DESTROY_WITH_PARENT,
                        (gtk.STOCK_CLOSE, gtk.ResponseType.OK))

    L = gtk.Label()
    scroll = gtk.ScrolledWindow()
    scroll.set_size_request(550, 400)
    scroll.set_shadow_type(gtk.ShadowType.ETCHED_IN)

    scroll.add_with_viewport(L)
    dialog.vbox.pack_start(scroll, True, True, 0)
    dialog.show_all()

    td = pydoc.TextDoc()

    text = list()
    for f in [
        ('Arbwave.add_runnable', Arbwave.add_runnable),
        ('Arbwave.update', Arbwave.update),
        ('Arbwave.update_static', Arbwave.update_static),
        ('Arbwave.update_plotter', Arbwave.update_plotter),
        ('Arbwave.stop_check', Arbwave.stop_check),
        ('Arbwave.save_waveform', Arbwave.save_waveform),
        ('Arbwave.find', Arbwave.find),
        ('Arbwave.find_group', Arbwave.find_group),
        ('Arbwave.find_channel', Arbwave.find_channel),
    ]:
        s = td.docroutine(f[1]).split('\n')
        args = s[0][s[0].find('('):(1 + s[0].find(')'))]
        text.append('\n'.join(['<b>{f}{args}</b>'.format(f=f[0], args=args)] +
                              s[1:]))

    text = '\n'.join(text)
    L.set_markup(text)

    # Close dialog on user response
    dialog.connect("response", lambda d, r: d.destroy())
    dialog.show()
Пример #29
0
def execute_command(the_command, m):
    '''Find the_command amongst the list of commands like cmd_one in module m
    
    This returns a string containing the response, or a -1 if a quit is commanded.'''
    the_functions = dict(captureImages=m.cmd_captureImages,brightStarCoords=m.cmd_brightStarCoords,adjustExposure=m.cmd_adjustExposure,setCameraValues=m.cmd_setCameraValues,starDistanceFromCenter=m.cmd_starDistanceFromCenter,orientationCapture=m.cmd_orientationCapture,calculateCameraOrientation=m.cmd_calculateCameraOrientation,Chop=m.cmd_Chop,imageCube=m.cmd_imageCube,defineCenter=m.cmd_defineCenter,centerIsHere=m.cmd_centerIsHere,currentExposure=m.cmd_currentExposure,changeExposure=m.cmd_changeExposure)
    commands = string.split(the_command)
    if len(commands) == 0:
        return ""
    if commands[0] == "help":
        if (len(commands) == 1):
            return 'captureImages\nbrightStarCoords\nadjustExposure\nsetCameraValues\nstarDistanceFromCenter\norientationCapture\ncalculateCameraOrientation\nChop\nimageCube\ndefineCenter\ncenterIsHere\ncurrentExposure\nchangeExposure'
        elif commands[1] in the_functions:
            td=pydoc.TextDoc()
            return td.docroutine(the_functions[commands[1]])
        else:
            return "ERROR: "+commands[1]+" is not a valid command."
    elif commands[0] == 'exit' or commands[0] == 'bye' or commands[0] == 'quit':
        return -1
    elif commands[0] in the_functions:
        return the_functions[commands[0]](the_command)
    else:
        return "ERROR: Command not found."
Пример #30
0
def execute_command(the_command, m):
    '''Find the_command amongst the list of commands like cmd_one in module m
    
    This returns a string containing the response, or a -1 if a quit is commanded.'''
    the_functions = dict(uber=m.cmd_uber,Sched=m.cmd_Sched,AddJob=m.cmd_AddJob)
    commands = string.split(the_command)
    if len(commands) == 0:
        return ""
    if commands[0] == "help":
        if (len(commands) == 1):
            return 'uber\nSched\nAddJob'
        elif commands[1] in the_functions:
            td=pydoc.TextDoc()
            return td.docroutine(the_functions[commands[1]])
        else:
            return "ERROR: "+commands[1]+" is not a valid command."
    elif commands[0] == 'exit' or commands[0] == 'bye' or commands[0] == 'quit':
        return -1
    elif commands[0] in the_functions:
        return the_functions[commands[0]](the_command)
    else:
        return "ERROR: Command not found."