zoukankan      html  css  js  c++  java
  • python语法31[keywords+builtins+modules]

    一 使用如下代码将keywords+builtins+modules输出到文件

    import sys

    def stdoutToFile(filename, function, args ):
        oldStdout 
    = sys.stdout
        f 
    = open(filename, "w" )
        sys.stdout 
    = f 
        function(args)
        
    #sys.stdout.flush()
        #f.close()
        sys.stdout = oldStdout


    if __name__=='__main__':
      
    print("modules")
      stdoutToFile(
    "modules.txt", help, "modules")
      
    print("builtins")
      stdoutToFile(
    "builtins.txt", help, "builtins")
      
    print("keywords")
      stdoutToFile(
    "keyword.txt", help, "keywords")

    但是此代码中有个问题,modules和keywords会输出到同一个文件。为什么???

    二 keywords

    help("keywords")

    关键字:

    Here is a list of the Python keywords.  Enter any keyword to get more help.

    and                 elif                import              return
    as                  
    else                in                  try
    assert              except              is                  while
    break               finally             lambda              with
    class               for                 not                 yield
    continue            from                or                  
    def                 global              pass                
    del                 if                  raise               

    三 builtins

    help("builtins")

    内置类型:

    builtin class
    CLASSES
        object
            BaseException
                Exception
                    ArithmeticError
                        FloatingPointError
                        OverflowError
                        ZeroDivisionError
                    AssertionError
                    AttributeError
                    BufferError
                    EOFError
                    EnvironmentError
                        IOError
                        OSError
                            WindowsError
                    ImportError
                    LookupError
                        IndexError
                        KeyError
                    MemoryError
                    NameError
                        UnboundLocalError
                    ReferenceError
                    RuntimeError
                        NotImplementedError
                    StopIteration
                    SyntaxError
                        IndentationError
                            TabError
                    SystemError
                    TypeError
                    ValueError
                        UnicodeError
                            UnicodeDecodeError
                            UnicodeEncodeError
                            UnicodeTranslateError
                    Warning
                        BytesWarning
                        DeprecationWarning
                        FutureWarning
                        ImportWarning
                        PendingDeprecationWarning
                        RuntimeWarning
                        SyntaxWarning
                        UnicodeWarning
                        UserWarning
                GeneratorExit
                KeyboardInterrupt
                SystemExit
            bytearray
            bytes
            classmethod
            complex
            dict
            enumerate
            filter
            float
            frozenset
            int
                bool
            list
            map
            memoryview
            property
            range
            reversed
            set
            slice
            staticmethod
            str
            super
            tuple
            type
            zip

    内置函数:

    FUNCTIONS
        
    __build_class__(...)
            
    __build_class__(func, name, *bases, metaclass=None, **kwds) -> class
            
            Internal helper function used by the 
    class statement.
        
        
    __import__(...)
            
    __import__(name, globals={}, locals={}, fromlist=[], level=-1-> module
            
            Import a module.  The globals are only used to determine the context;
            they are 
    not modified.  The locals are currently unused.  The fromlist
            should be a list of names to emulate ``
    from name import ...''or an
            empty list to emulate ``
    import name''.
            When importing a module 
    from a package, note that __import__('A.B', ...)
            returns package A when fromlist 
    is empty, but its submodule B when
            fromlist 
    is not empty.  Level is used to determine whether to perform 
            absolute 
    or relative imports.  -1 is the original strategy of attempting
            both absolute 
    and relative imports, 0 is absolute, a positive number
            
    is the number of parent directories to search relative to the current module.
        
        abs(...)
            abs(number) 
    -> number
            
            Return the absolute value of the argument.
        
        all(...)
            all(iterable) 
    -> bool
            
            Return True 
    if bool(x) is True for all values x in the iterable.
        
        any(...)
            any(iterable) 
    -> bool
            
            Return True 
    if bool(x) is True for any x in the iterable.
        
        ascii(...)
            ascii(object) 
    -> string
            
            As repr(), 
    return a string containing a printable representation of an
            object, but escape the non
    -ASCII characters in the string returned by
            repr() using \x, \u 
    or \U escapes.  This generates a string similar
            to that returned by repr() 
    in Python 2.
        
        bin(...)
            bin(number) 
    -> string
            
            Return the binary representation of an integer 
    or long integer.
        
        chr(...)
            chr(i) 
    -> Unicode character
            
            Return a Unicode string of one character with ordinal i; 0 
    <= i <= 0x10ffff.
            If 
    0x10000 <= i, a surrogate pair is returned.
        
        compile(...)
            compile(source, filename, mode[, flags[, dont_inherit]]) 
    -> code object
            
            Compile the source string (a Python module, statement 
    or expression)
            into a code object that can be executed by 
    exec() or eval().
            The filename will be used 
    for run-time error messages.
            The mode must be 
    'exec' to compile a module, 'single' to compile a
            single (interactive) statement, 
    or 'eval' to compile an expression.
            The flags argument, 
    if present, controls which future statements influence
            the compilation of the code.
            The dont_inherit argument, 
    if non-zero, stops the compilation inheriting
            the effects of any future statements 
    in effect in the code calling
            compile; 
    if absent or zero these statements do influence the compilation,
            
    in addition to any features explicitly specified.
        
        delattr(...)
            delattr(object, name)
            
            Delete a named attribute on an object; delattr(x, 
    'y'is equivalent to
            ``
    del x.y''.
        
        dir(...)
            dir([object]) 
    -> list of strings
            
            If called without an argument, 
    return the names in the current scope.
            Else, 
    return an alphabetized list of names comprising (some of) the attributes
            of the given object, 
    and of attributes reachable from it.
            If the object supplies a method named 
    __dir__, it will be used; otherwise
            the default dir() logic 
    is used and returns:
              
    for a module object: the module's attributes.
              for a class object:  its attributes, and recursively the attributes
                of its bases.
              
    for any other object: its attributes, its class's attributes, and
                recursively the attributes of its class's base classes.
        
        divmod(...)
            divmod(x, y) 
    -> (div, mod)
            
            Return the tuple ((x
    -x%y)/y, x%y).  Invariant: div*+ mod == x.
        
        eval(...)
            eval(source[, globals[, locals]]) 
    -> value
            
            Evaluate the source 
    in the context of globals and locals.
            The source may be a string representing a Python expression
            
    or a code object as returned by compile().
            The globals must be a dictionary 
    and locals can be any mapping,
            defaulting to the current globals 
    and locals.
            If only globals 
    is given, locals defaults to it.
        
        
    exec(...)
            
    exec(object[, globals[, locals]])
            
            Read 
    and execute code from a object, which can be a string or a code
            object.
            The globals 
    and locals are dictionaries, defaulting to the current
            globals 
    and locals.  If only globals is given, locals defaults to it.
        
        format(...)
            format(value[, format_spec]) 
    -> string
            
            Returns value.
    __format__(format_spec)
            format_spec defaults to 
    ""
        
        getattr(...)
            getattr(object, name[, default]) 
    -> value
            
            Get a named attribute 
    from an object; getattr(x, 'y'is equivalent to x.y.
            When a default argument 
    is given, it is returned when the attribute doesn't
            exist; without it, an exception is raised in that case.
        
        globals(...)
            globals() 
    -> dictionary
            
            Return the dictionary containing the current scope
    's global variables.
        
        hasattr(...)
            hasattr(object, name) 
    -> bool
            
            Return whether the object has an attribute with the given name.
            (This 
    is done by calling getattr(object, name) and catching exceptions.)
        
        hash(...)
            hash(object) 
    -> integer
            
            Return a hash value 
    for the object.  Two objects with the same value have
            the same hash value.  The reverse 
    is not necessarily true, but likely.
        
        hex(...)
            hex(number) 
    -> string
            
            Return the hexadecimal representation of an integer 
    or long integer.
        
        id(...)
            id(object) 
    -> integer
            
            Return the identity of an object.  This 
    is guaranteed to be unique among
            simultaneously existing objects.  (Hint: it
    's the object's memory address.)
        
        input(...)
            input([prompt]) 
    -> string
            
            Read a string 
    from standard input.  The trailing newline is stripped.
            If the user hits EOF (Unix: Ctl
    -D, Windows: Ctl-Z+Return), raise EOFError.
            On Unix, GNU readline 
    is used if enabled.  The prompt string, if given,
            
    is printed without a trailing newline before reading.
        
        isinstance(...)
            isinstance(object, 
    class-or-type-or-tuple) -> bool
            
            Return whether an object 
    is an instance of a class or of a subclass thereof.
            With a type as second argument, 
    return whether that is the object's type.
            The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
            isinstance(x, A) 
    or isinstance(x, B) or ... (etc.).
        
        issubclass(...)
            issubclass(C, B) 
    -> bool
            
            Return whether 
    class C is a subclass (i.e., a derived class) of class B.
            When using a tuple as the second argument issubclass(X, (A, B, ...)),
            
    is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).
        
        iter(...)
            iter(iterable) 
    -> iterator
            iter(callable, sentinel) 
    -> iterator
            
            Get an iterator 
    from an object.  In the first form, the argument must
            supply its own iterator, 
    or be a sequence.
            In the second form, the callable 
    is called until it returns the sentinel.
        
        len(...)
            len(object) 
    -> integer
            
            Return the number of items of a sequence 
    or mapping.
        
        locals(...)
            locals() 
    -> dictionary
            
            Update 
    and return a dictionary containing the current scope's local variables.
        
        max(...)
            max(iterable[, key
    =func]) -> value
            max(a, b, c, ...[, key
    =func]) -> value
            
            With a single iterable argument, 
    return its largest item.
            With two 
    or more arguments, return the largest argument.
        
        min(...)
            min(iterable[, key
    =func]) -> value
            min(a, b, c, ...[, key
    =func]) -> value
            
            With a single iterable argument, 
    return its smallest item.
            With two 
    or more arguments, return the smallest argument.
        
        next(...)
            next(iterator[, default])
            
            Return the next item 
    from the iterator. If default is given and the iterator
            
    is exhausted, it is returned instead of raising StopIteration.
        
        oct(...)
            oct(number) 
    -> string
            
            Return the octal representation of an integer 
    or long integer.
        
        open(...)
            Open file 
    and return a stream.  Raise IOError upon failure.
            
            file 
    is either a text or byte string giving the name (and the path
            
    if the file isn't in the current working directory) of the file to
            be opened or an integer file descriptor of the file to be
            wrapped. (If a file descriptor 
    is given, it is closed when the
            returned I
    /O object is closed, unless closefd is set to False.)
            
            mode 
    is an optional string that specifies the mode in which the file
            
    is opened. It defaults to 'r' which means open for reading in text
            mode.  Other common values are 
    'w' for writing (truncating the file if
            it already exists), 
    and 'a' for appending (which on some Unix systems,
            means that all writes append to the end of the file regardless of the
            current seek position). In text mode, 
    if encoding is not specified the
            encoding used 
    is platform dependent. (For reading and writing raw
            bytes use binary mode 
    and leave encoding unspecified.) The available
            modes are:
            
            
    ========= ===============================================================
            Character Meaning
            
    --------- ---------------------------------------------------------------
            
    'r'       open for reading (default)
            
    'w'       open for writing, truncating the file first
            
    'a'       open for writing, appending to the end of the file if it exists
            
    'b'       binary mode
            
    't'       text mode (default)
            
    '+'       open a disk file for updating (reading and writing)
            
    'U'       universal newline mode (for backwards compatibility; unneeded
                      
    for new code)
            
    ========= ===============================================================
            
            The default mode 
    is 'rt' (open for reading text). For binary random
            access, the mode 
    'w+b' opens and truncates the file to 0 bytes, while
            
    'r+b' opens the file without truncation.
            
            Python distinguishes between files opened 
    in binary and text modes,
            even when the underlying operating system doesn
    't. Files opened in
            binary mode (appending 'b' to the mode argument) return contents as
            bytes objects without any decoding. In text mode (the default, 
    or when
            
    't' is appended to the mode argument), the contents of the file are
            returned as strings, the bytes having been first decoded using a
            platform
    -dependent encoding or using the specified encoding if given.
            
            buffering 
    is an optional integer used to set the buffering policy. By
            default full buffering 
    is on. Pass 0 to switch buffering off (only
            allowed 
    in binary mode), 1 to set line buffering, and an integer > 1
            
    for full buffering.
            
            encoding 
    is the name of the encoding used to decode or encode the
            file. This should only be used 
    in text mode. The default encoding is
            platform dependent, but any encoding supported by Python can be
            passed.  See the codecs module 
    for the list of supported encodings.
            
            errors 
    is an optional string that specifies how encoding errors are to
            be handled
    ---this argument should not be used in binary mode. Pass
            
    'strict' to raise a ValueError exception if there is an encoding error
            (the default of None has the same effect), 
    or pass 'ignore' to ignore
            errors. (Note that ignoring encoding errors can lead to data loss.)
            See the documentation 
    for codecs.register for a list of the permitted
            encoding error strings.
            
            newline controls how universal newlines works (it only applies to text
            mode). It can be None, 
    '''\n''\r'and '\r\n'.  It works as
            follows:
            
            
    * On input, if newline is None, universal newlines mode is
              enabled. Lines 
    in the input can end in '\n''\r'or '\r\n'and
              these are translated into 
    '\n' before being returned to the
              caller. If it 
    is '', universal newline mode is enabled, but line
              endings are returned to the caller untranslated. If it has any of
              the other legal values, input lines are only terminated by the given
              string, 
    and the line ending is returned to the caller untranslated.
            
            
    * On output, if newline is None, any '\n' characters written are
              translated to the system default line separator, os.linesep. If
              newline 
    is '', no translation takes place. If newline is any of the
              other legal values, any 
    '\n' characters written are translated to
              the given string.
            
            If closefd 
    is False, the underlying file descriptor will be kept open
            when the file 
    is closed. This does not work when a file name is given
            
    and must be True in that case.
            
            open() returns a file object whose type depends on the mode, 
    and
            through which the standard file operations such as reading 
    and writing
            are performed. When open() 
    is used to open a file in a text mode ('w',
            
    'r''wt''rt', etc.), it returns a TextIOWrapper. When used to open
            a file 
    in a binary mode, the returned class varies: in read binary
            mode, it returns a BufferedReader; 
    in write binary and append binary
            modes, it returns a BufferedWriter, 
    and in read/write mode, it returns
            a BufferedRandom.
            
            It 
    is also possible to use a string or bytearray as a file for both
            reading 
    and writing. For strings StringIO can be used like a file
            opened 
    in a text mode, and for bytes a BytesIO can be used like a file
            opened 
    in a binary mode.
        
        ord(...)
            ord(c) 
    -> integer
            
            Return the integer ordinal of a one
    -character string.
            A valid surrogate pair 
    is also accepted.
        
        pow(...)
            pow(x, y[, z]) 
    -> number
            
            With two arguments, equivalent to x
    **y.  With three arguments,
            equivalent to (x
    **y) % z, but may be more efficient (e.g. for longs).
        
        
    print(...)
            
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
            
            Prints the values to a stream, 
    or to sys.stdout by default.
            Optional keyword arguments:
            file: a file
    -like object (stream); defaults to the current sys.stdout.
            sep:  string inserted between values, default a space.
            end:  string appended after the last value, default a newline.
        
        repr(...)
            repr(object) 
    -> string
            
            Return the canonical string representation of the object.
            For most object types, eval(repr(object)) 
    == object.
        
        round(...)
            round(number[, ndigits]) 
    -> number
            
            Round a number to a given precision 
    in decimal digits (default 0 digits).
            This returns an int when called with one argument, otherwise the
            same type as the number. ndigits may be negative.
        
        setattr(...)
            setattr(object, name, value)
            
            Set a named attribute on an object; setattr(x, 
    'y', v) is equivalent to
            ``x.y 
    = v''.
        
        sorted(...)
            sorted(iterable, key
    =None, reverse=False) --> new sorted list
        
        sum(...)
            sum(iterable[, start]) 
    -> value
            
            Returns the sum of an iterable of numbers (NOT strings) plus the value
            of parameter 
    'start' (which defaults to 0).  When the iterable is
            empty, returns start.
        
        vars(...)
            vars([object]) 
    -> dictionary
            
            Without arguments, equivalent to locals().
            With an argument, equivalent to object.
    __dict__.

    四 modules

    help("modules")

    python安装后带有的modules:

    Please wait a moment while I gather a list of all available modules...

    WConio              base64              importlib           shelve
    _WConio             bdb                 inspect             shlex
    __future__          binascii            io                  shutil
    _abcoll             binhex              itertools           signal
    _ast                bisect              json                site
    _bisect             build_class         keyword             smtpd
    _codecs             builtins            lib2to3             smtplib
    _codecs_cn          bz2                 linecache           sndhdr
    _codecs_hk          cProfile            locale              socket
    _codecs_iso2022     calendar            logging             socketserver
    _codecs_jp          cgi                 macpath             sqlite3
    _codecs_kr          cgitb               macurl2path         sre_compile
    _codecs_tw          chunk               mailbox             sre_constants
    _collections        cmath               mailcap             sre_parse
    _compat_pickle      cmd                 marshal             ssl
    _csv                code                math                stat
    _ctypes             codecs              mimetypes           stdredirect
    _ctypes_test        codeop              mmap                string
    _dummy_thread       collections         modulefinder        stringprep
    _elementtree        colorsys            msilib              struct
    _functools          compileall          msvcrt              subprocess
    _hashlib            configparser        multiprocessing     sunau
    _heapq              contextlib          netrc               symbol
    _io                 copy                nntplib             symtable
    _json               copyreg             nt                  sys
    _locale             csv                 ntpath              tabnanny
    _lsprof             ctypes              nturl2path          tarfile
    _markupbase         curses              numbers             telnetlib
    _md5                datetime            opcode              tempfile
    _msi                dbm                 operator            test
    _multibytecodec     decimal             optparse            textwrap
    _multiprocessing    difflib             os                  this
    _pickle             dis                 os2emxpath          thread
    _pyio               distutils           parser              threading
    _random             doctest             pdb                 time
    _sha1               dummy_threading     pickle              timeit
    _sha256             email               pickletools         tkinter
    _sha512             encodings           pipes               token
    _socket             errno               pkgutil             tokenize
    _sqlite3            filecmp             platform            trace
    _sre                fileinput           plistlib            traceback
    _ssl                fnmatch             poplib              tty
    _strptime           formatter           posixpath           turtle
    _struct             fractions           pprint              types
    _subprocess         ftplib              profile             unicodedata
    _symtable           functools           pstats              unittest
    _testcapi           gc                  pty                 urllib
    _thread             genericpath         py_compile          uu
    _threading_local    getopt              pyclbr              uuid
    _tkinter            getpass             pydoc               warnings
    _warnings           gettext             pydoc_data          wave
    _weakref            glob                pyexpat             weakref
    _weakrefset         gzip                pythontips          webbrowser
    abc                 hashlib             queue               winreg
    activestate         heapq               quopri              winsound
    aifc                hmac                random              wsgiref
    antigravity         html                re                  xdrlib
    array               http                reprlib             xml
    ast                 httplib2            rlcompleter         xmlrpc
    asynchat            idlelib             rpyc                xxsubtype
    asyncore            imaplib             runpy               zipfile
    atexit              imghdr              sched               zipimport
    audioop             imp                 select              zlib

    Enter any module name to get more help.  Or, type 
    "modules spam" to search
    for modules whose descriptions contain the word "spam".

    完!

  • 相关阅读:
    C#网络编程之---TCP协议的同步通信(二)
    CentOS6.4 X86_64 kvm+PXE备忘
    Rsyslog远程传输的几种方式
    ADB工具【转载】
    docker 常用命令
    容灾测试(未完)
    docker 运维实践
    Day 15 图像和办公文档的处理
    服务器调优
    软件测试1 正规流程
  • 原文地址:https://www.cnblogs.com/itech/p/1946952.html
Copyright © 2011-2022 走看看