精华内容
下载资源
问答
  • python with语句

    千次阅读 2017-11-14 09:27:29
    python with语句

             with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,

    比如文件使用后自动关闭、线程中锁的自动获取和释放等。

     示例:

    '''
    try:
        f=open('dsad.txt','r')
        for ea in f:
                print(ea)
    except OSError as aaa:
        print('异常:'+ str(aaa))
    finally:
        f.close()                             #由于试图关闭一个不存在的文件所以此处会报异常
        print('!=============!')
    
    '''
    
    #改良
    #使用with自动调用f.close()方法
    try:
        with open('dsad.txt','r') as f:
            for ea in f:
                print(ea)
    except OSError as aaa:
        print('异常:'+ str(aaa))

    推荐有关with语句的相关文档:浅谈Python的with语句
    展开全文
  • Parsing C++ in Python with Clang

    千次阅读 2014-05-16 11:21:56
    Parsing C++ in Python with Clang July 3rd, 2011 at 5:15 am People that need to parse and analyze C code in Python are usually really excited to run into pycparser. However, when the tas

    原文地址:http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang/

    Parsing C++ in Python with Clang

    July 3rd, 2011 at 5:15 am

    People that need to parse and analyze C code in Python are usually really excited to run into pycparser. However, when the task is to parse C++, pycparser is not the solution. When I get asked about plans to support C++ in pycparser, my usual answer is – there are no such plans [1], you should look elsewhere. Specifically, at Clang.

    Clang is a front-end compiler for C, C++ and Objective C. It’s a liberally licensed open-source project backed by Apple, which uses it for its own tools. Along with its parent project – the LLVM compiler backend, Clang starts to become a formidable alternative to gcc itself these days. The dev team behind Clang (and LLVM) is top-notch and its source is one of the best designed bodies of C++ code in the wild. Clang’s development is very active, closely following the latest C++ standards.

    So what I point people to when I’m asked about C++ parsing is Clang. There’s a slight problem with that, however. People like pycparser because it’s Python, and Clang’s API is C++ – which is not the most high-level hacking friendly language out there, to say the least.

    libclang

    Enter libclang. Not so long ago, the Clang team wisely recognized that Clang can be used not only as a compiler proper, but also as a tool for analyzing C/C++/ObjC code. In fact, Apple’s own Xcode development tools use Clang as a library under the hood for code completion, cross-referencing, and so on.

    The component through which Clang enables such usage is called libclang. It’s a C API [2] that the Clang team vows to keep relatively stable, allowing the user to examine parsed code at the level of an abstract syntax tree (AST) [3].

    More technically, libclang is a shared library that packages Clang with a public-facing API defined in a single C header file: clang/include/clang-c/Index.h.

    Python bindings to libclang

    libclang comes with Python bindings, which reside in clang/bindings/python, in module clang.cindex. This module relies on ctypes to load the dynamic libclang library and tries to wrap as much of libclang as possible with a Pythonic API.

    Documentation?

    Unfortunately, the state of documentation for libclang and its Python bindings is dire. The official documentation according to the devs is the source (and auto-generated Doxygen HTML). In addition, all I could find online is a presentation and a couple of outdated email messages from the Clang dev mailing list.

    On the bright side, if you just skim the Index.h header file keeping in mind what it’s trying to achieve, the API isn’t hard to understand (and neither is the implementation, especially if you’re a bit familiar with Clang’s internals). Another place to look things up is the clang/tools/c-index-test tool, which is used to test the API and demonstrates its usage.

    For the Python bindings, there is absolutely no documentation as well, except the source plus a couple of examples that are distributed alongside it. So I hope this article will be helpful!

    Setting up

    Setting up usage of the Python bindings is very easy:

    • Your script needs to be able to find the clang.cindex module. So either copy it appropriately or set up PYTHONPATH to point to it [4].
    • clang.cindex needs to be able to find the libclang.so shared library. Depending on how you build/install Clang, you will need to copy it appropriately or set up LD_LIBRARY_PATH to point to its location. On Windows, this is libclang.dll and it should be on PATH.

    That arranged, you’re ready to import clang.cindex and start rolling.

    Simple example

    Let’s start with a simple example. The following script uses the Python bindings of libclang to find all references to some type in a given file:

    #!/usr/bin/env python
    """ Usage: call with <filename> <typename>
    """
    
    import sys
    import clang.cindex
    
    def find_typerefs(node, typename):
        """ Find all references to the type named 'typename'
        """
        if node.kind.is_reference():
            ref_node = clang.cindex.Cursor_ref(node)
            if ref_node.spelling == typename:
                print 'Found %s [line=%s, col=%s]' % (
                    typename, node.location.line, node.location.column)
        # Recurse for children of this node
        for c in node.get_children():
            find_typerefs(c, typename)
    
    index = clang.cindex.Index.create()
    tu = index.parse(sys.argv[1])
    print 'Translation unit:', tu.spelling
    find_typerefs(tu.cursor, sys.argv[2])
    

    Suppose we invoke it on this dummy C++ code:

    class Person {
    };
    
    
    class Room {
    public:
        void add_person(Person person)
        {
            // do stuff
        }
    
    private:
        Person* people_in_room;
    };
    
    
    template <class T, int N>
    class Bag<T, N> {
    };
    
    
    int main()
    {
        Person* p = new Person();
        Bag<Person, 42> bagofpersons;
    
        return 0;
    }
    

    Executing to find referenced to type Person, we get:

    Translation unit: simple_demo_src.cpp
    Found Person [line=7, col=21]
    Found Person [line=13, col=5]
    Found Person [line=24, col=5]
    Found Person [line=24, col=21]
    Found Person [line=25, col=9]
    

    Understanding how it works

    To see what the example does, we need to understand its inner workings on 3 levels:

    • Conceptual level – what is the information we’re trying to pull from the parsed source and how it’s stored
    • libclang level – the formal C API of libclang, since it’s much better documented (albeit only in comments in the source) than the Python bindings
    • The Python bindings, since this is what we directly invoke

    Creating the index and parsing the source

    We’ll start at the beginning, with these lines:

    index = clang.cindex.Index.create()
    tu = index.parse(sys.argv[1])
    

    An "index" represents a set of translation units compiled and linked together. We need some way of grouping several translation units if we want to reason across them. For example, we may want to find references to some type defined in a header file, in a set of other source files. Index.create() invokes the C API function clang_createIndex.

    Next, we use Index‘s parse method to parse a single translation unit from a file. This invokes clang_parseTranslationUnit, which is a key function in the C API. Its comment says:

    This routine is the main entry point for the Clang C API, providing the ability to parse a source file into a translation unit that can then be queried by other functions in the API.

    This is a powerful function – it can optionally accept the full set of flags normally passed to the command-line compiler. It returns an opaque CXTranslationUnit object, which is encapsulated in the Python bindings as TranslationUnit. This TranslationUnit can be queried, for example the name of the translation unit is available in the spelling property:

    print 'Translation unit:', tu.spelling
    

    Its most important property is, however, cursor. A cursor is a key abstraction in libclang, it represents some node in the AST of a parsed translation unit. The cursor unifies the different kinds of entities in a program under a single abstraction, providing a common set of operations, such as getting its location and children cursors. TranslationUnit.cursor returns the top-level cursor of the translation unit, which serves as the stating point for exploring its AST. I will use the terms cursor and node interchangeably from this point on.

    Working with cursors

    The Python bindings encapsulate the libclang cursor in the Cursor object. It has many attributes, the most interesting of which are:

    • kind – an enumeration specifying the kind of AST node this cursor points at
    • spelling – the source-code name of the node
    • location – the source-code location from which the node was parsed
    • get_children – its children nodes

    get_children requires special explanation, because this is a particular point at which the C and Python APIs diverge.

    The libclang C API is based on the idea of visitors. To walk the AST from a given cursor, the user code provides a callback function to clang_visitChildren. This function is then invoked on all descendants of a given AST node.

    The Python bindings, on the other hand, encapsulate visiting internally, and provide a more Pythonic iteration API via Cursor.get_children, which returns the children nodes (cursors) of a given cursor. It’s still possible to access the original visitation APIs directly through Python, but using get_children is much more convenient. In our example, we use get_children to recursively visit all the children of a given node:

    for c in node.get_children():
        find_typerefs(c, typename)
    

    Some limitations of the Python bindings

    Unfortunately, the Python bindings aren’t complete and still have some bugs, because it is a work in progress. As an example, suppose we want to find and report all the function calls in this file:

    bool foo()
    {
        return true;
    }
    
    void bar()
    {
        foo();
        for (int i = 0; i < 10; ++i)
            foo();
    }
    
    int main()
    {
        bar();
        if (foo())
            bar();
    }
    

    Let’s write this code:

    import sys
    import clang.cindex
    
    def callexpr_visitor(node, parent, userdata):
        if node.kind == clang.cindex.CursorKind.CALL_EXPR:
            print 'Found %s [line=%s, col=%s]' % (
                    node.spelling, node.location.line, node.location.column)
        return 2 # means continue visiting recursively
    
    index = clang.cindex.Index.create()
    tu = index.parse(sys.argv[1])
    clang.cindex.Cursor_visit(
            tu.cursor,
            clang.cindex.Cursor_visit_callback(callexpr_visitor),
            None)
    

    This time we’re using the libclang visitation API directly. The result is:

    Found None [line=8, col=5]
    Found None [line=10, col=9]
    Found None [line=15, col=5]
    Found None [line=16, col=9]
    Found None [line=17, col=9]
    

    While the reported locations are fine, why is the node name None? After some perusal of libclang‘s code, it turns out that for expressions, we shouldn’t be printing the spelling, but rather the display name. In the C API it means clang_getCursorDisplayName and not clang_getCursorSpelling. But, alas, the Python bindings don’t have clang_getCursorDisplayName exposed!

    We won’t let this stop us, however. The source code of the Python bindings is quite straightforward, and simply uses ctypes to expose additional functions from the C API. Adding these lines to bindings/python/clang/cindex.py:

    Cursor_displayname = lib.clang_getCursorDisplayName
    Cursor_displayname.argtypes = [Cursor]
    Cursor_displayname.restype = _CXString
    Cursor_displayname.errcheck = _CXString.from_result
    

    And we can now use Cursor_displayname. Replacing node.spelling by clang.cindex.Cursor_displayname(node) in the script, we now get the desired output:

    Found foo [line=8, col=5]
    Found foo [line=10, col=9]
    Found bar [line=15, col=5]
    Found foo [line=16, col=9]
    Found bar [line=17, col=9]
    

    Update (06.07.2011): Inspired by this article, I submitted a patch to the Clang project to expose Cursor_displayname, as well as to fix a few other problems with the Python bindings. It was committed by Clang’s core devs in revision 134460 and should now be available from trunk.

    Some limitations of libclang

    As we have seen above, limitations in the Python bindings are relatively easy to overcome. Since libclang provides a straightforward C API, it’s just a matter of exposing additional functionality with appropriate ctypes constructs. To anyone even moderately experienced with Python, this isn’t a big problem.

    Some limitations are in libclang itself, however. For example, suppose we wanted to find all the return statements in a chunk of code. Turns out this isn’t possible through the current API of libclang. A cursory look at the Index.h header file reveals why.

    enum CXCursorKind enumerates the kinds of cursors (nodes) we may encounter via libclang. This is the portion related to statements:

    /* Statements */
    CXCursor_FirstStmt                     = 200,
    /**
     * \brief A statement whose specific kind is not exposed via this
     * interface.
     *
     * Unexposed statements have the same operations as any other kind of
     * statement; one can extract their location information, spelling,
     * children, etc. However, the specific kind of the statement is not
     * reported.
     */
    CXCursor_UnexposedStmt                 = 200,
    
    /** \brief A labelled statement in a function.
     *
     * This cursor kind is used to describe the "start_over:" label statement in
     * the following example:
     *
     * \code
     *   start_over:
     *     ++counter;
     * \endcode
     *
     */
    CXCursor_LabelStmt                     = 201,
    
    CXCursor_LastStmt                      = CXCursor_LabelStmt,
    

    Ignoring the placeholders CXCursor_FirstStmt and CXCursor_LastStmt which are used for validity testing, the only statement recognized here is the label statement. All other statements are going to be represented with CXCursor_UnexposedStmt.

    To understand the reason for this limitation, it’s constructive to ponder the main goal of libclang. Currently, this API’s main use is in IDEs, where we want to know everything about types and references to symbols, but don’t particularly care what kind of statement or expression we see [5].

    Forgunately, from discussions in the Clang dev mailing lists it can be gathered that these limitations aren’t really intentional. Things get added to libclang on a per-need basis. Apparently no one needed to discern different statement kinds through libclang yet, so no one added this feature. If it’s important enough for someone, he can feel free to suggest a patch to the mailing list. In particular, this specific limitation (lack of statement kinds) is especially easy to overcome. Looking at cxcursor::MakeCXCursor in libclang/CXCursor.cpp, it’s obvious how these "kinds" are generated (comments are mine):

    CXCursor cxcursor::MakeCXCursor(Stmt *S, Decl *Parent,
                                    CXTranslationUnit TU) {
      assert(S && TU && "Invalid arguments!");
      CXCursorKind K = CXCursor_NotImplemented;
    
      switch (S->getStmtClass()) {
      case Stmt::NoStmtClass:
        break;
    
      case Stmt::NullStmtClass:
      case Stmt::CompoundStmtClass:
      case Stmt::CaseStmtClass:
    
      ... // many other statement classes
    
      case Stmt::MaterializeTemporaryExprClass:
        K = CXCursor_UnexposedStmt;
        break;
    
      case Stmt::LabelStmtClass:
        K = CXCursor_LabelStmt;
        break;
    
      case Stmt::PredefinedExprClass:
    
      .. //  many other statement classes
    
      case Stmt::AsTypeExprClass:
        K = CXCursor_UnexposedExpr;
        break;
    
      .. // more code
    

    This is simply a mega-switch on Stmt.getStmtClass() (which is Clang’s internal statement class), and only for Stmt::LabelStmtClass there is a kind that isn’t CXCursor_UnexposedStmt. So recognizing additional "kinds" is trivial:

    1. Add another enum value to CXCursorKind, between CXCursor_FirstStmt and CXCursor_LastStmt
    2. Add another case to the switch in cxcursor::MakeCXCursor to recognize the appropriate class and return this kind
    3. Expose the enumeration value in (1) to the Python bindings

    Conclusion

    Hopefully this article has been a useful introduction to libclang‘s Python bindings (and libclang itself along the way). Although there is a dearth of external documentation for these components, they are well written and commented, and their source code is thus straightforward enough to be reasonably self-documenting.

    It’s very important to keep in mind that these APIs wrap an extremely powerful C/C++/ObjC parser engine that is being very actively developed. In my personal opinion, Clang is one’s best bet for an up-to-date open-source C++ parsing library these days. Nothing else comes even close.

    A small fly in the ointment is some limitations in libclang itself and its Python bindings. These are a by-product of libclang being a relatively recent addition to Clang, which itself is a very young project.

    Fortunately, as I hope this article demonstrated, these limitations aren’t terribly difficult to work around. Only a small amount of Python and C expertise is required to extend the Python bindings, while a bit of understanding of Clang lays the path to enhancements to libclang itself. In addition, since libclang is still being actively developed, I’m quite confident that this API will keep improving over time, so it will have less and less limitations and omissions as time goes by.

    http://eli.thegreenplace.net/wp-content/uploads/hline.jpg

    [1] For me, there are a few reasons for not wanting to get into C++ parsing. First, I like my projects being born from a need. I needed to parse C, so pycparser was created. I have no need parsing C++. Second, as hard as C is to parse, C++ is much harder since its grammar is even more ambiguous. Third, a great tool for parsing C++ already exists – Clang.
    [2] C for better interoperability with non C/C++ based languages and tools. For example, the Python bindings would be much harder to implement on top of a C++ API.
    [3] The key word here is stable. While Clang as a whole is designed in a library-based approach and its parts can be used directly, these are internal APIs the development team isn’t obliged to keep stable between releases.
    [4] Note that the Python bindings are part of the source distribution of Clang.
    [5] Expression kinds are also severely limited in libclang.

    Related posts:

    1. Adventures in parsing C: ASTs for switch statements
    2. Basic source-to-source transformation with Clang
    3. How Clang handles the type / variable name ambiguity of C/C++
    4. Python internals: adding a new statement to Python
    5. Parsing VHDL is [very] hard
    展开全文
  • 关于python with的用法及异常处理

    千次阅读 2020-01-11 16:50:01
    关于python with的用法及异常处理 在网上看到一些人博客使用 with 用于异常处理,但是我在网仔细查阅,发现 该关键字不是用于处理异常的。 实际上 实际上,在with后面的代码块抛出异常时,exit()方法被执行。开发库...

    关于python with的用法及异常处理

    在网上看到一些人博客使用 with 用于异常处理,但是我在网仔细查阅,发现
    该关键字不是用于处理异常的。

    实际上

    实际上,在with后面的代码块抛出异常时,exit()方法被执行。开发库时,清理资源,关闭文件等操作,都可以放在exit()方法中。
    总之,with-as表达式极大的简化了每次写finally的工作,这对代码的优雅性是有极大帮助的。
    如果有多项,可以这样写:

    With open('1.txt') as f1, open('2.txt') as  f2:
        do something
    
    说道with 就不得不说道 __enter__ 和 __exit__

    简单来说 __enter__ 是在with 调用时执行(就如__init__ 优先执行)
    而__exit__ (有点类似于__del__ 后执行销毁操作) 当然你可以自定义
    因为套路过于固定,不是很适合由于异常处理。

    如果没有with语句,则可能会写以下内容:
    如果不用with语句,代码如下:

    file = open("/tmp/foo.txt")
    data = file.read()
    file.close()
    

    这里有两个烦人的事情。首先,您最终忘记关闭文件处理程序。第二个是如何处理一旦获得文件处理程序可能发生的异常。可以这样写来解决这个问题:
    这里有两个问题。一是可能忘记关闭文件句柄;二是文件读取数据发生异常,没有进行任何处理。下面是处理异常的加强版本:

    file = open("/tmp/foo.txt")
    try:
        data = file.read()
    finally:
        file.close()
    

    虽然这很好用,但它不必要地冗长。这是with有用的地方。除了更好的语法外,关于它的好处是,它是非常好的处理异常的方法。当与以下代码一起使用时,上面的代码将如下所示:
    有时就是使用一展身手的时候了。除了有更优雅的语法,用还可以很好的处理周围环境产生的异常。下面是用版本的代码:

    with open("/tmp /foo.txt") as file:
        data = file.read()
    

    with_example01.py

    class Sample:
        def __enter__(self):
            print "In __enter__()"
            return "Foo"
     
        def __exit__(self, type, value, trace):
            print "In __exit__()"
     
                
    def get_sample():
        return Sample()
     
     
    with get_sample() as sample:
        print "sample:", sample
    

    执行后,将导致:

    bash-3.2$ ./with_example01.py
    In __enter__()
    sample: Foo
    In __exit__()
    

    如您所见,执行__enter __()函数返回的值-在这种情况下,将“ Foo”分配给sample执行该块的主体,从而打印出sample的值。“ Foo”调用__exit __()函数。真正强大的功能在于它可以处理异常。您可能已经注意到Sample的__exit __()函数带有三个参数-val,type和trace。这些在异常处理中很有用。让我们通过修改上面的示例来了解其工作原理。

    如果要使用捕获异常可以使用:

    try:
        print("执行11")
        num#未下定义变量
        print("执行22")
    except:
        print("try发生异常时执行")
    finally:
        print("无论有无发生异常都会执行")
    
    

    输出结果:
    >>>runfile(‘E:/pythonnew/test.py’, wdir=‘E:/pythonnew’)
    执行11
    try发生异常时执行
    无论有无发生异常都会执行

    总结

    开发库时,清理资源关闭文件等操作,都可以放在exit()方法中。
    比较详细处理异常时没使用 try except finally
    展开全文
  • Python with用法

    千次阅读 2014-03-07 16:04:57
    Pythonwith用法,详解!
    一 with介绍
             with从Python 2.5就有,需要from __future__ import with_statement,但python 2.6开始,成为默认关键字。在What's new in python2.6/3.0中,明确提到:
          The ‘with‘ statement is a control-flow structure whose basicstructure is:
           with expression [as variable]:
                   with-block
           也就是说with是一个控制流语句,跟if/for/while/try之类的是一类的,with可以用来简化try finally代码,看起来可以比try finally更清晰。
          这里新引入了一个"上下文管理协议"context management protocol“,实现方法是为一个类定义__enter__和__exit__两个函数。with expresion as variable的执行过程是,首先执行__enter__函数,它的返回值会赋给as后面的variable,想让它返回什么就返回什么,只要你知道怎么处理就可以了,如果不写as variable,返回值会被忽略。然后,开始执行with-block中的语句,不论成功失败(比如发生异常、错误,设置sys.exit()),在with-block执行完成后,会执行__exit__函数。

     这样的过程其实等价于:
       try:
           执行 __enter__的内容
           执行 with_block.
      finally:
           执行 __exit__内容
     
    只不过,现在把一部分代码封装成了__enter__函数,清理代码封装成__exit__函数。

    二 代码实现
         class echo :
             def output(self) :
              print 'hello world'
        def __enter__(self):
             print 'enter'
             return self
        def __exit__(self, exception_type, exception_value, exception_traceback):
             print 'exit'
             if exception_type == ValueError :
                 return True
            else:
                 return False

         with echo() as e:
             e.output()
             print 'do something inside'
             print '-----------'
         with echo() as e:
             raise ValueError('value error')
             print '-----------'
         with echo() as e:
             raise Exception('can not detect')


    运行结果:
    enter
    hello world
    do something inside
    exit
    -----------
    enter
    exit
    -----------
    enter
    exit
    Traceback (most recent call last):
      File "exception.py", line 102, in <module>
        raise Exception('can not detect')
    Exception: can not detect

    注意:
    1,e不是test()的值,test()返回的是"context manager object",是给with用的。e获得的是__enter__函数的返回值,这是with拿到echo()的对象执行之后的结果.

    2,__exit__函数的返回值用来指示with-block部分发生的异常是否要re-raise,如果返回False,则会re-raise with-block的异常,如果返回True,则就像什么都没发生。

    三 使用环境
    1.这样要打开一个文件,处理它的内容,并且保证关闭它,你就可以简单地这样做:
         with open("x.txt") as f:
         data = f.read()
         do something with data

    2.Flask中初始化数据库的代码:
         def init_db():
             with app.app_context():
                 db = get_db()
                 with app.open_resource('shema.sql', mode='r') as f:
                     db.cursor().executescript(f.read())
              db.commit()     
    3.contextlib是为了加强with语句,提供上下文机制的模块,它是通过Generator实现的。通过定义类以及写__enter__和__exit__来进行上下文管理虽然不难,但是很繁琐。contextlib中的contextmanager作为装饰器来提供一种针对函数级别的上下文管理机制。常用框架如下:

    from contextlib import contextmanager
     
    @contextmanager
        def make_context() :
              print 'enter'
         try :
              yield {}
        except RuntimeError, err :
            print 'error' , err
        finally :
            print 'exit'
     

    with make_context() as value :
        print value 

    contextlib还有连个重要的东西,一个是nested,一个是closing,前者用于创建嵌套的上下文,后则用于帮你执行定义好的close函数。但是nested已经过时了,因为with已经可以通过多个上下文的直接嵌套了。下面是一个例子:

    from contextlib import contextmanager
    from contextlib import nested
    from contextlib import closing
    @contextmanager
    def make_context(name) :
        print 'enter', name
        yield name
        print 'exit', name
     
    with nested(make_context('A'), make_context('B')) as (a, b) :
        print a
        print b
     
    with make_context('A') as a, make_context('B') as b :
        print a
        print b
     
    class Door(object) :
        def open(self) :
            print 'Door is opened'
        def close(self) :
            print 'Door is closed'
     
    with closing(Door()) as door :
        door.open() 

    运行结果:


    closing函数的使用:

    from contextlib import closing 
    import urllib 
       
    with closing(urllib.urlopen('http://www.python.org')) as page: 
        for line in page: 
        print line  

    四 小结
            python有很多强大的特性,由于我们平常总习惯于之前C++或java的一些编程习惯,时常忽略这些好的机制。因此,要学会使用这些python特性,让我们写的python程序更像是python。 

    展开全文
  • Python with上下文管理及自定义上下文管理 一、上下文管理器 上下文管理器是对Context Manager的翻译 ,上下文是 context 直译的叫法,在程序中用来表示代码执行过程中所处的前后环境. 在文件操作时,需要打开,...
  • with open("file_location") as f: body
  • python with的使用

    千次阅读 2019-09-04 20:34:13
    with关键字的使用 对于系统资源如文件、数据库连接、socket 而言,应用程序打开这些资源并执行完业务逻辑之后,必须做的一件事就是要关闭(断开)该资源。 比如 Python 程序打开一个文件,往文件中写内容,写完之后...
  • 其实这是一篇译文,看官方文档的时候觉得不好对重点做标记,加上以后遗忘的时候...1. Extending Python with C or C++ C编写的扩展模块源码文件构成: 1.功能函数 spam_system 2.模块的方法表(Method Table)SpamMet
  • Python With语句

    千次阅读 2013-12-14 10:52:45
    从Java转过来,习惯性try, catch, finally ,然后在 finally里面 释放...使用with上下文管理器。 直接来代码,以Python 操作MySQL为例。 #! -*-coding: utf-8 -*- import sys import logging import MySQLdb from
  • Python with 关键字详解

    千次阅读 2015-10-09 20:22:17
    Pythonwith关键字很常用,相信你也经常遇见,例如: if isinstance(self.commands, str): with(settings(warn_only = True)): sudo(self.commands, shell=False)你或许会困惑with到底是个什么东西?其实with...
  • Python with open语句

    千次阅读 2017-09-19 17:54:54
    在读写文件时为了保证无论是否出错都能正确地关闭文件,我们可以使用try ... finally来实现: ... f.close()但是每次都这么写实在太繁琐,所以,Python引入了with语句来自动帮我们调用close()方法
  • python with用法

    万次阅读 2011-10-27 13:28:04
    pythonwith可以明显改进代码友好度,比如: with open('a.txt') as f: print f.readlines() 为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可: >>> class A: def __enter...
  • Configure and compile Python with Zlib

    千次阅读 2009-02-25 15:16:00
    « Spam solutions wont workGet ZMySQLDA to retrieve MySQL Stored Procedures »Configure and compile Python with ZlibPublishedby Gregon June 26, 2005in Linux, Python and Zope.
  • python with关键字用法

    万次阅读 2012-11-21 10:37:21
    withPython 2.5就有,需要from __future__ import with_statement。自python 2.6开始,成为默认关键字。在What's new in python2.6/3.0中,明确提到: The 'with' statement is a control-flow structure whose ...
  • debugging python with IDLE

    千次阅读 2014-06-28 08:37:34
    Python 2.5”→“IDLE(Python GUI)” 2. open your source file window From python shell, select file->open... 3. show debug control From python shell, select Debug->Debuger 4.
  • python with as语法

    万次阅读 2012-06-13 14:06:28
    withPython 2.5就有,需要from __future__ import with_statement。自python 2.6开始,成为默认关键字。  也就是说with是一个控制流语句,跟if/for/while/try之类的是一类的,with可以用来简化try finally代码...
  • python with as 用法

    千次阅读 2015-11-13 15:16:34
    基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。 紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被...
  • Python with语句定义及使用

    万次阅读 2018-09-10 09:07:10
    如果你有一些对象(比如一个文件、网络连接或锁),需要支持 with 语句,下面介绍两种定义方法。 方法(1): 首先介绍下with 工作原理 (1)紧跟with后面的语句被求值后,返回对象的“__enter__()”方法被调用,...
  • Python with_metaclass 继承测试

    千次阅读 2019-05-30 13:59:41
    /usr/bin/python from six import with_metaclass class A(type): def TestA(self): print('TestA') class B(object): def TestB(self): print('TestB') class C(with_metaclass(A,B)): def TestC(...
  • python with关键字——I/O好伴侣

    千次阅读 2020-09-24 23:59:37
    学习python的朋友都知道文件读写的基本操作,通常我们读写文本的姿势是这个样子的: f = open(file_name) ... f.close() 每次定义一个文件读写对象,在操作完成后,我们都需要进行关闭操作,如果你一不小心忘记了,...
  • python with/as

    千次阅读 2013-07-16 14:44:52
    看代码时遇到with/as语句,查阅相关资料,现总结如下: with/as是一种异常相关语句,可虑下列代码: set things up try: do something finally: tear things down "set things up“可以是打开一...
  • python with as 进行文件读取

    千次阅读 2016-12-07 11:35:51
    1. 用with...as...来做文件内容的读取(在内容不多的情况下,如果文件巨大,还是一行一行读取吧) filename = os.path.join(self._data_path, 'Annotations', index + '.txt' with open(filename) as f: lines = [x...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 233,540
精华内容 93,416
关键字:

pythonwith

python 订阅