background preloader

Understanding Python's "with" statement

Understanding Python's "with" statement
Fredrik Lundh | October 2006 | Originally posted to Judging from comp.lang.python and other forums, Python 2.5’s new with statement (dead link) seems to be a bit confusing even for experienced Python programmers. As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code: set things up try: do something finally: tear things down Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. def controlled_execution(callback): set things up try: callback(thing) finally: tear things down def my_function(thing): do something controlled_execution(my_function) This wasn’t very difficult, was it?

python中的异常 - 如果你想看看某人的灵魂,只要问问他做了什么梦就行了 当你的程序中出现异常情况时就需要异常处理。比如当你打开一个不存在的文件时。当你的程序中有一些无效的语句时,Python会提示你有错误存在。 下面是一个拼写错误的例子,print写成了Print。 >>> Print 'Hello World' File "", line 1 Print 'Hello World' ^ SyntaxError: invalid syntax >>> print 'Hello World' Hello World 1、try...except语句 try...except语句可以用于捕捉并处理错误。 #! 运行输出如下: $ python Enter something --> Why did you do an EOF on me? 说明:每个try语句都必须有至少一个except语句。 2、引发异常 你可以用raise语句来引发一个异常。 #! $ python 请输入 --> 你输入了一个结束标记EOF $ python 请输入 --> --> ab ShortInputException: 输入的长度是 2, 长度至少应是 3 $ python 请输入 --> abc 没有异常发生. 3、try...finally语句 当你正在读文件或还未关闭文件时发生了异常该怎么办呢? #! $ python Programming is fun When the work is done Cleaning up...closed the file Traceback (most recent call last): File "", line 12, in ? 说明:我们在两秒这段时间内按下了Ctrl-c,这将产生一个KeyboardInterrupt异常,我们并没有处理这个异常,那么Python将调用默认的处理器,并终止程序,在程序终止之前,finally块中的语句将执行。 本系列的文章来源是

HowTo/Sorting Original version by Andrew Dalke with a major update by Raymond Hettinger Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here. Sorting Basics A simple ascending sort is very easy -- just call the sorted() function. >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] You can also use the list.sort() method of a list. >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] Another difference is that the list.sort() method is only defined for lists. Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons. For example, here's a case-insensitive string comparison: The same technique works for objects with named attributes.

Python异常处理_aimee Python的异常处理能力是很强大的,可向用户准确反馈出错信息。在Python中,异常也是对象,可对它进行操作。所有异常都是基类Exception的成员。所有异常都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。 方式一:try语句: 1使用try和except语句来捕获异常 try: block except [exception,[data…]]: block try: block except [exception,[data...]]: block else: block 该种异常处理语法的规则是: · 执行try下的语句,如果引发异常,则执行过程会跳到第一个except语句。 · 如果第一个except中定义的异常与引发的异常匹配,则执行该except中的语句。 · 如果引发的异常不匹配第一个except,则会搜索第二个except,允许编写的except数量没有限制。 · 如果所有的except都不匹配,则异常会传递到下一个调用本代码的最高层try代码中。 · 如果没有发生异常,则执行else块代码。 例: try: f = open(“file.txt”,”r”) except IOError, e: print e 捕获到的IOError错误的详细原因会被放置在对象e中,然后运行该异常的except代码块 捕获所有的异常 try: a=b b=c except Exception,ex: print Exception,":",ex 使用except子句需要注意的事情,就是多个except子句截获异常时,如果各个异常类之间具有继承关系,则子类应该写在前面,否则父类将会直接截获子类异常。 2 使用try跟finally: 语法如下: try: block finally: block 该语句的执行规则是: · 执行try下的代码。 · 如果发生异常,在该异常传递到下一级try时,执行finally中的代码。 · 如果没有发生异常,则执行finally中的代码。 第二种try语法在无论有没有发生异常都要执行代码的情况下是很有用的。 这两种形式相互冲突,使用了一种就不允许使用另一种,而功能又各异 2. raise [exception[,data]] 3. 格式: 4. 或者以如下的形式:

5.3. Defining Classes Python is fully object-oriented: you can define your own classes, inherit from your own or built-in classes, and instantiate the classes you've defined. Defining a class in Python is simple. As with functions, there is no separate interface definition. Just define the class and start coding. A Python class starts with the reserved word class, followed by the class name. Example 5.3. class Loaf: pass Of course, realistically, most classes will be inherited from other classes, and they will define their own class methods and attributes. Example 5.4. from UserDict import UserDict class FileInfo(UserDict): Python supports multiple inheritance. 5.3.1. This example shows the initialization of the FileInfo class using the __init__ method. Example 5.5. class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): 5.3.2. When defining your class methods, you must explicitly list self as the first argument for each method, including __init__. Whew.

使用NotePad++编辑python代码_简简单单 以前用过emacs编辑过python代码,虽然那个Tab一键完成比较爽,但是emacs配置太麻烦(windows下),而且还会产生.file#之类的文件,看着就心烦!前天弄了一下notepad++,觉得相当不错! 以下文章转载自:萧萧—sina博客 Notepad++ 是一个开源的文本编辑器,功能强大而且使用方便。 我是在 上下载的 Notepad++ Portable ,它的好处是可以在每次关闭程序的时候把所需的配置文件单独保存,省却每台机器上重新配置的烦恼。 Tab长度和空格转换 因为 Python 对缩进要求严格,我们将 Tab 设置成4个空格,在 "设置->首选项->编辑->制表符设置" 中修改。 语法高亮 只要正确设置了扩展名,Notepad++ 就会自动识别语言并进行语法高亮。 自动完成 Notepad++ 也提供了自动完成和输入提示功能,在 "设置->首选项->备份与自动完成" 中可以设置。 运行程序 点击 "运行->运行" (默认快捷键是 F5 ),在弹出的菜单中输入: cmd /k C:/Python30/python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT 选择 "保存",就可以给这条命令设置一个快捷键并起一个名字,比如叫 "Run Python"。 如果想修改这条命令,目前只能通过修改 shortcuts.xml 文件,这个文件保存在 Notepad++ 的配置文件中,可能在 Notepad++ 的目录,也可能在 Documents and Settings 下的 Application Data 内。

Understanding Python Iterables and Iterators | Shut Up and Ship Decorators have been in Python since version 2.4. They are the lines that start with @ symbol just before a function or a class definition. Probably you encountered them when you defined class methods, properties etc. Or perhaps you encountered them in a web framework like Django and used them to magically add login requirements for certain pages by adding a @login_required line before your view function. Decorator formalities First let us deal with the formalities like definition, syntax, etc. Here is the template of a decorator without arguments. @decoratordef F(arg): pass # is same asdef F(arg): passF = decorator(f) And here is a decorator with arguments. @decorator(n)def F(arg): pass # is same asdef F(arg): passF = decorator(n)(F) As you can see, strictly speaking we don’t need the decorator syntax. Writing our own decorators Here are a couple of functions in our module. def simpleinterest(n, p, r): return n*p*r/100.0 def compoundinterest(n, p, r): return p*(1+r/100.0)**n-p It works!

Notepad++编辑Pyhton文件的自动缩进的问题(图文)(转) - ksharp_dabu的日志 Ps:notepad++还有很多功能不知道,自己也没安装什么插件,以后看来要和它多打交道了。 原文链接: 这个问题一直困扰我很久,Python对缩进很敏感,一般建议缩进用空格,而Notepad++的自动缩进是用的TAB,google过,baidu过, 都提到在首选项中有个将TAB用4个空格代替的选项,可我一直找不到这个选项,经过N个版本更新后依然如初,甚至还下载过一些插件希望能解决,但无果。 今天终于在帮助文档中找到答案了(HELP很重要啊!!!),特记录之,免日久又忘掉。 如果你想打开自动缩进,可以在 设置-》首选项-》其他 中进行设置 勾选了这个后,你换行是就会自动缩进了,下面还要设置将TAB更换成4个空格 设置-》首选项-》语言-》标签设置 不要改“Default”,现在做得很灵活了,可以对不同的语言进行设置,我们可以选上Pyhton,将默认去掉,选“以空格取代” 现在你的Notepad++可以很好的编辑Pyhton文件了 随便说说运行的设置,在运行(F5)中输入 cmd /k C:\Python26\python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT , 注意:上面的输入相当于在cmd运行python.exe的绝对路径,所以你要根据自己的python的路径修改就性了。 点击保存,自己起个名字,以后在“运行”菜单下就可以运行你的Python程序了

Charming Python: Iterators and simple generators Welcome to the world of exotic flow control. With Python 2.2 (now in its third alpha release -- see Resources later in this article), programmers will get some new options for making programs tick that were not available -- or at least not as convenient -- in earlier Python versions. While what Python 2.2 gives us is not quite as mind-melting as the full continuations and microthreads that are possible in Stackless Python, generators and iterators do something a bit different from traditional functions and classes. Let's consider iterators first, since they are simpler to understand. A generator is a little more complicated and general. In some ways, a generator is like the closures which were discussed in previous installments of this column discussing functional programming (see Resources). Fortunately, using a generator is much less work than understanding all the conceptual issues of program flow and state. Taking a random walk Utilizing this function is as simple as: Back to top

Python正则表达式指南 - AstralWind 本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例。本文的内容不包括如何编写高效的正则表达式、如何优化正则表达式,这些主题请查看其他教程。 注意:本文基于Python2.4完成;如果看到不明白的词汇请记得百度谷歌或维基,whatever。 尊重作者的劳动,转载请注明作者及原文地址 >.<html 1. 1.1. 正则表达式并不是Python的一部分。 下图展示了使用正则表达式进行匹配的流程: 正则表达式的大致匹配过程是:依次拿出表达式和文本中的字符比较,如果每一个字符都能匹配,则匹配成功;一旦有匹配不成功的字符则匹配失败。 下图列出了Python支持的正则表达式元字符和语法: 1.2. 正则表达式通常用于在文本中查找匹配的字符串。 1.3. 与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。 1.4. 正则表达式提供了一些可用的匹配模式,比如忽略大小写、多行匹配等,这部分内容将在Pattern类的工厂方法re.compile(pattern[, flags])中一起介绍。 2. re模块 2.1. Python通过re模块提供对正则表达式的支持。 re.compile(strPattern[, flag]): 这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同) M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图) S(DOTALL): 点任意匹配模式,改变'.' re提供了众多模块方法用于完成正则表达式的功能。 re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/? 2.2. Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。 属性: string: 匹配时使用的文本。 方法: group([group1, …]): 获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。 2.3. Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。 pattern: 编译时用的表达式字符串。

The Python Standard Library While The Python Language Reference describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. It also describes some of the optional components that are commonly included in Python distributions. Python’s standard library is very extensive, offering a wide range of facilities as indicated by the long table of contents listed below. The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.