设为首页 收藏本站
查看: 544|回复: 0

[经验分享] python语法31[keywords+builtins+modules]

[复制链接]

尚未签到

发表于 2015-4-23 08:00:50 | 显示全部楼层 |阅读模式
  
  一 使用如下代码将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  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".  
  
  完!
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-59791-1-1.html 上篇帖子: Python的getattr(),setattr(),delattr(),hasattr() 下篇帖子: Python学习笔记(0)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表