显示标签为“Python”的博文。显示所有博文
显示标签为“Python”的博文。显示所有博文

2013年7月23日星期二

Pythoner

Préfèrez :

la beauté à la laideur,
l’explicite à l’implicite,
le simple au complexe
et le complexe au compliqué,
le déroulé à l’imbriqué,
l’aéré au compact.
Prends en compte la lisibilité.
Les cas particuliers ne le sont jamais assez pour violer les règles.
Mais, à la pureté, privilégie l’aspect pratique.
Ne passe pas les erreurs sous silence,
... ou bâillonne-les explicitement.
Face à l’ambiguïté, à deviner ne te laisse pas aller.
Sache qu’il ne devrait avoir qu’une et une seule façon de procéder,
même si, de prime abord, elle n’est pas évidente, à moins d’être Néerlandais.
Mieux vaut maintenant que jamais.
Cependant jamais est souvent mieux qu’immédiatement.
Si l’implémentation s’explique difficilement, c’est une mauvaise idée.
Si l’implémentation s’explique aisément, c’est peut-être une bonne idée.
Les espaces de nommage ! Sacrée bonne idée ! Faisons plus de trucs comme ça.

2012年8月1日星期三

Python Cookbook 4.1 复制(拷贝)对象(浅复制和深复制)

需求:

你想复制一个对象.因为在Python中,无论你把对象做为参数传递,做为函数返回值,都是引用传递的.

讨论:

标准库中的copy模块提供了两个方法来实现拷贝.一个方法是copy,它返回和参数包含内容一样的对象.

import copy
new_list = copy.copy(existing_list)

有些时候,你希望对象中的属性也被复制,可以使用deepcopy方法:

import copy
new_list_of_dicts = copy.deepcopy(existing_list_of_dicts)

当你对一个对象赋值的时候(做为参数传递,或者做为返回值),Python和Java一样,总是传递原始对象的引用,而不是一个副本.其它一些语言当赋值的时候总是传递副本.Python从不猜测用户的需求 ,如果你想要一个副本,你必须显式的要求.
Python的行为很简单,迅速,而且一致.然而,如果你需要一个对象拷贝而并没有显式的写出来,会出现问题的,比如:

>>> a = [1, 2, 3]
>>> b = a
>>> b.append(5)
>>> print a, b
[1, 2, 3, 5] [1, 2, 3, 5]

在这里,变量a和b都指向同一个对象(一个列表),所以,一旦你修改了二者之一,另外一个也会受到影响.无论怎样,都会修改原来的对象.
注意:
要想成为一个Python高手,首先要注意的问题就是对象的变更操作和赋值,它们都是针对对象的引用操作的.一个语句比如a = []将a重新绑定给一个新对象,但不会影响以前的对象.然而,对象复制却不同,当对象复制后,对象变更操作就有了区别.
如 果你想修改一个对象,而且想让原始的对象不受影响,那你就需要对象复制.正如本节说的一样,你可以使用copy模块中的两个方法来实现需求.一般的,可以 使用copy.copy,它可以进行对象的浅复制(shallow copy),它复制了对象,但对于对象中的元素,依然使用引用.
浅复制,有时无法获得一个和原来对象完全一致的副本,如果你想修改对象中的元素,不仅仅是对象本身的话:

>>> list_of_lists = [ ['a'], [1, 2], ['z', 23] ]
>>> copy_lol = copy.copy(lists_of_lists)
>>> copy_lol[1].append('boo')
>>> print list_of_lists, copy_lol
[['a'], [1, 2, 'boo'], ['z', 23]] [['a'], [1, 2, 'boo'], ['z', 23]]

在这里,变量list_of_lists,copy_lol指向了两个不同的对象,所以我们可以修改它们任何一个, 而不影响另外一个.然而,如果我们修改了一个对象中的元素,那么另一个也会受影响,因为它们中的元素还是共享引用.
如果你希望复制一个容器对象,以及它里面的所有元素(包含元素的子元素),使用copy.deepcopy,这个方法会消耗一些时间和空间,不过,如果你需要完全复制,这是唯一的方法.
对于一般的浅拷贝,使用copy.copy就可以了,当然,你需要了解你要拷贝的对象.要复制列表L,使用list(L),要复制一个字典d,使用dict(d),要复制一个集合s,使用set(s),这样,我们总结出一个规律,如果你要复制一个对象o,它属于内建的类型t,那么你可以使用t(o)来 获得一个拷贝.dict也提供了一个复制版本,dict.copy,这个和dict(d)是一样,我推荐你使用后者,这个使得代码更一致,而且还少几个字符.
要复制一个别的类型,无论是你自己写的还是使用库中的,使用copy.copy,如果你自己写一个类,没有必要费神去写clone和copy函数,如果你想定义自己的类复制的方式,实现一个__copy__,或者__getstate__和__setstate__.如果你想定义自己类型的deepcopy,实现方法__deepcopy__.
注意你不用复制不可修改对象(string,数字,元组),因为你不用担心修改它们.如果你想尝试一下复制,依然会得到原来的.虽然无伤大雅,不过真的浪费尽力:

>>> s = 'cat'
>>> t = copy.copy(s)
>>> s is t
True

is操作符用于不仅判断两个对象是否完全一致,而且是同一个对象(is判断标识符,要比较内容,使用==),判断标识符是否相等对于不可修改对象没有什么意义.然而 ,判断标识符对于可修改对象有时候是很重要的,比如,你不确定a和b是否指向同一个对象,使用a is b会立刻得到结果.这样你可以自己判断是否需要使用对象拷贝.
注意:
你可以使用另一种拷贝方式,给定一个列表L,无论是完整切片L[:]或者列表解析[x for x in L],都会获得L的浅拷贝,试试L+[],L*1...但是上面两种方法都会使人迷惑,使用list(L)最清晰和快速,当然,由于历史原因,你可能会经常看到L[:]的写法.
对于dict,你可能见过下面的复制方法:
>>> for somekey in d:
... d1[somekey] = d[somekey]

或者更简单一些的方法,d1={},d1.update(d),无论怎样,这些代码都是缺乏效率的,使用d1=dict(d)吧.

相关说明:

copy(x)
    Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.

deepcopy(x, memo=None, _nil=[])
    Deep copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.


PEP: 8 Style Guide for Python Code

PEP:      8
Title:      Style Guide for Python Code
Version:      00f8e3bb1197
Last-Modified:      2011-06-13 12:48:33 -0400 (Mon, 13 Jun 2011)
Author:      Guido van Rossum <guido at python.org>, Barry Warsaw <barry at python.org>
Status:      Active
Type:      Process
Created:      05-Jul-2001
Post-History:      05-Jul-2001
Introduction
    This document gives coding conventions for the Python code comprising the
    standard library in the main Python distribution.  Please see the
    companion informational PEP describing style guidelines for the C code in
    the C implementation of Python[1].

    This document was adapted from Guido's original Python Style Guide
    essay[2], with some additions from Barry's style guide[5].  Where there's
    conflict, Guido's style rules for the purposes of this PEP.  This PEP may
    still be incomplete (in fact, it may never be finished <wink>).


A Foolish Consistency is the Hobgoblin of Little Minds
    One of Guido's key insights is that code is read much more often than it
    is written.  The guidelines provided here are intended to improve the
    readability of code and make it consistent across the wide spectrum of
    Python code.  As PEP 20 [6] says, "Readability counts".

    A style guide is about consistency.  Consistency with this style guide is
    important.  Consistency within a project is more important. Consistency
    within one module or function is most important.

    But most importantly: know when to be inconsistent -- sometimes the style
    guide just doesn't apply.  When in doubt, use your best judgment.  Look
    at other examples and decide what looks best.  And don't hesitate to ask!

    Two good reasons to break a particular rule:

    (1) When applying the rule would make the code less readable, even for
        someone who is used to reading code that follows the rules.

    (2) To be consistent with surrounding code that also breaks it (maybe for
        historic reasons) -- although this is also an opportunity to clean up
        someone else's mess (in true XP style).


Code lay-out
  Indentation

    Use 4 spaces per indentation level.

    For really old code that you don't want to mess up, you can continue to
    use 8-space tabs.

    Continuation lines should align wrapped elements either vertically using
    Python's implicit line joining inside parentheses, brackets and braces, or
    using a hanging indent.  When using a hanging indent the following
    considerations should be applied; there should be no arguments on the
    first line and further indentation should be used to clearly distinguish
    itself as a continuation line.

    Yes:  # Aligned with opening delimiter
          foo = long_function_name(var_one, var_two,
                                   var_three, var_four)

          # More indentation included to distinguish this from the rest.
          def long_function_name(
                  var_one, var_two, var_three,
                  var_four):
              print(var_one)

    No:   # Arguments on first line forbidden when not using vertical alignment
          foo = long_function_name(var_one, var_two,
              var_three, var_four)

          # Further indentation required as indentation is not distinguishable
          def long_function_name(
              var_one, var_two, var_three,
              var_four):
              print(var_one)

    Optional:
          # Extra indentation is not necessary.
          foo = long_function_name(
            var_one, var_two,
            var_three, var_four)

  Tabs or Spaces?

    Never mix tabs and spaces.

    The most popular way of indenting Python is with spaces only.  The
    second-most popular way is with tabs only.  Code indented with a mixture
    of tabs and spaces should be converted to using spaces exclusively.  When
    invoking the Python command line interpreter with the -t option, it issues
    warnings about code that illegally mixes tabs and spaces.  When using -tt
    these warnings become errors.  These options are highly recommended!

    For new projects, spaces-only are strongly recommended over tabs.  Most
    editors have features that make this easy to do.

  Maximum Line Length

    Limit all lines to a maximum of 79 characters.

    There are still many devices around that are limited to 80 character
    lines; plus, limiting windows to 80 characters makes it possible to have
    several windows side-by-side.  The default wrapping on such devices
    disrupts the visual structure of the code, making it more difficult to
    understand.  Therefore, please limit all lines to a maximum of 79
    characters.  For flowing long blocks of text (docstrings or comments),
    limiting the length to 72 characters is recommended.

    The preferred way of wrapping long lines is by using Python's implied line
    continuation inside parentheses, brackets and braces.  Long lines can be
    broken over multiple lines by wrapping expressions in parentheses. These
    should be used in preference to using a backslash for line continuation.
    Make sure to indent the continued line appropriately.  The preferred place
    to break around a binary operator is *after* the operator, not before it.
    Some examples:

    class Rectangle(Blob):

        def __init__(self, width, height,
                     color='black', emphasis=None, highlight=0):
            if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
                raise ValueError("sorry, you lose")
            if width == 0 and height == 0 and (color == 'red' or
                                               emphasis is None):
                raise ValueError("I don't think so -- values are %s, %s" %
                                 (width, height))
            Blob.__init__(self, width, height,
                          color, emphasis, highlight)

  Blank Lines

    Separate top-level function and class definitions with two blank lines.

    Method definitions inside a class are separated by a single blank line.

    Extra blank lines may be used (sparingly) to separate groups of related
    functions.  Blank lines may be omitted between a bunch of related
    one-liners (e.g. a set of dummy implementations).

    Use blank lines in functions, sparingly, to indicate logical sections.

    Python accepts the control-L (i.e. ^L) form feed character as whitespace;
    Many tools treat these characters as page separators, so you may use them
    to separate pages of related sections of your file.  Note, some editors
    and web-based code viewers may not recognize control-L as a form feed
    and will show another glyph in its place.

  Encodings (PEP 263)

    Code in the core Python distribution should always use the ASCII or
    Latin-1 encoding (a.k.a. ISO-8859-1).  For Python 3.0 and beyond,
    UTF-8 is preferred over Latin-1, see PEP 3120.

    Files using ASCII should not have a coding cookie.  Latin-1 (or
    UTF-8) should only be used when a comment or docstring needs to
    mention an author name that requires Latin-1; otherwise, using
    \x, \u or \U escapes is the preferred way to include non-ASCII
    data in string literals.

    For Python 3.0 and beyond, the following policy is prescribed for
    the standard library (see PEP 3131): All identifiers in the Python
    standard library MUST use ASCII-only identifiers, and SHOULD use
    English words wherever feasible (in many cases, abbreviations and
    technical terms are used which aren't English). In addition,
    string literals and comments must also be in ASCII. The only
    exceptions are (a) test cases testing the non-ASCII features, and
    (b) names of authors. Authors whose names are not based on the
    latin alphabet MUST provide a latin transliteration of their
    names.

    Open source projects with a global audience are encouraged to
    adopt a similar policy.


Imports
    - Imports should usually be on separate lines, e.g.:

        Yes: import os
             import sys

        No:  import sys, os

      it's okay to say this though:

        from subprocess import Popen, PIPE

    - Imports are always put at the top of the file, just after any module
      comments and docstrings, and before module globals and constants.

      Imports should be grouped in the following order:

      1. standard library imports
      2. related third party imports
      3. local application/library specific imports

      You should put a blank line between each group of imports.

      Put any relevant __all__ specification after the imports.

    - Relative imports for intra-package imports are highly discouraged.
      Always use the absolute package path for all imports.
      Even now that PEP 328 [7] is fully implemented in Python 2.5,
      its style of explicit relative imports is actively discouraged;
      absolute imports are more portable and usually more readable.

    - When importing a class from a class-containing module, it's usually okay
      to spell this

        from myclass import MyClass
        from foo.bar.yourclass import YourClass

      If this spelling causes local name clashes, then spell them

        import myclass
        import foo.bar.yourclass

      and use "myclass.MyClass" and "foo.bar.yourclass.YourClass"


Whitespace in Expressions and Statements
  Pet Peeves

    Avoid extraneous whitespace in the following situations:

    - Immediately inside parentheses, brackets or braces.

      Yes: spam(ham[1], {eggs: 2})
      No:  spam( ham[ 1 ], { eggs: 2 } )

    - Immediately before a comma, semicolon, or colon:

      Yes: if x == 4: print x, y; x, y = y, x
      No:  if x == 4 : print x , y ; x , y = y , x

    - Immediately before the open parenthesis that starts the argument
      list of a function call:

      Yes: spam(1)
      No:  spam (1)

    - Immediately before the open parenthesis that starts an indexing or
      slicing:

      Yes: dict['key'] = list[index]
      No:  dict ['key'] = list [index]

    - More than one space around an assignment (or other) operator to
      align it with another.

      Yes:

          x = 1
          y = 2
          long_variable = 3

      No:

          x             = 1
          y             = 2
          long_variable = 3


  Other Recommendations

    - Always surround these binary operators with a single space on
      either side: assignment (=), augmented assignment (+=, -= etc.),
      comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not),
      Booleans (and, or, not).

    - Use spaces around arithmetic operators:

      Yes:

          i = i + 1
          submitted += 1
          x = x * 2 - 1
          hypot2 = x * x + y * y
          c = (a + b) * (a - b)

      No:

          i=i+1
          submitted +=1
          x = x*2 - 1
          hypot2 = x*x + y*y
          c = (a+b) * (a-b)

    - Don't use spaces around the '=' sign when used to indicate a
      keyword argument or a default parameter value.

      Yes:

          def complex(real, imag=0.0):
              return magic(r=real, i=imag)

      No:

          def complex(real, imag = 0.0):
              return magic(r = real, i = imag)

    - Compound statements (multiple statements on the same line) are
      generally discouraged.

      Yes:

          if foo == 'blah':
              do_blah_thing()
          do_one()
          do_two()
          do_three()

      Rather not:

          if foo == 'blah': do_blah_thing()
          do_one(); do_two(); do_three()

    - While sometimes it's okay to put an if/for/while with a small
      body on the same line, never do this for multi-clause
      statements.  Also avoid folding such long lines!

      Rather not:

          if foo == 'blah': do_blah_thing()
          for x in lst: total += x
          while t < 10: t = delay()

      Definitely not:

          if foo == 'blah': do_blah_thing()
          else: do_non_blah_thing()

          try: something()
          finally: cleanup()

          do_one(); do_two(); do_three(long, argument,
                                       list, like, this)

          if foo == 'blah': one(); two(); three()

Comments
    Comments that contradict the code are worse than no comments.  Always make
    a priority of keeping the comments up-to-date when the code changes!

    Comments should be complete sentences.  If a comment is a phrase or
    sentence, its first word should be capitalized, unless it is an identifier
    that begins with a lower case letter (never alter the case of
    identifiers!).

    If a comment is short, the period at the end can be omitted.  Block
    comments generally consist of one or more paragraphs built out of complete
    sentences, and each sentence should end in a period.

    You should use two spaces after a sentence-ending period.

    When writing English, Strunk and White apply.

    Python coders from non-English speaking countries: please write
    your comments in English, unless you are 120% sure that the code
    will never be read by people who don't speak your language.


  Block Comments

    Block comments generally apply to some (or all) code that follows them,
    and are indented to the same level as that code.  Each line of a block
    comment starts with a # and a single space (unless it is indented text
    inside the comment).

    Paragraphs inside a block comment are separated by a line containing a
    single #.

  Inline Comments

    Use inline comments sparingly.

    An inline comment is a comment on the same line as a statement.  Inline
    comments should be separated by at least two spaces from the statement.
    They should start with a # and a single space.

    Inline comments are unnecessary and in fact distracting if they state
    the obvious.  Don't do this:

        x = x + 1                 # Increment x

    But sometimes, this is useful:

        x = x + 1                 # Compensate for border


Documentation Strings
    Conventions for writing good documentation strings (a.k.a. "docstrings")
    are immortalized in PEP 257 [3].

    - Write docstrings for all public modules, functions, classes, and
      methods.  Docstrings are not necessary for non-public methods, but you
      should have a comment that describes what the method does.  This comment
      should appear after the "def" line.

    - PEP 257 describes good docstring conventions.  Note that most
      importantly, the """ that ends a multiline docstring should be on a line
      by itself, and preferably preceded by a blank line, e.g.:

      """Return a foobang

      Optional plotz says to frobnicate the bizbaz first.

      """

    - For one liner docstrings, it's okay to keep the closing """ on the same
      line.


Version Bookkeeping
    If you have to have Subversion, CVS, or RCS crud in your source file, do
    it as follows.

        __version__ = "$Revision: 00f8e3bb1197 $"
        # $Source$

    These lines should be included after the module's docstring, before any
    other code, separated by a blank line above and below.


Naming Conventions
    The naming conventions of Python's library are a bit of a mess, so we'll
    never get this completely consistent -- nevertheless, here are the
    currently recommended naming standards.  New modules and packages
    (including third party frameworks) should be written to these standards,
    but where an existing library has a different style, internal consistency
    is preferred.

  Descriptive: Naming Styles

    There are a lot of different naming styles.  It helps to be able to
    recognize what naming style is being used, independently from what they
    are used for.

    The following naming styles are commonly distinguished:

    - b (single lowercase letter)

    - B (single uppercase letter)

    - lowercase

    - lower_case_with_underscores

    - UPPERCASE

    - UPPER_CASE_WITH_UNDERSCORES

    - CapitalizedWords (or CapWords, or CamelCase -- so named because
      of the bumpy look of its letters[4]).  This is also sometimes known as
      StudlyCaps.

      Note: When using abbreviations in CapWords, capitalize all the letters
      of the abbreviation.  Thus HTTPServerError is better than
      HttpServerError.

    - mixedCase (differs from CapitalizedWords by initial lowercase
      character!)

    - Capitalized_Words_With_Underscores (ugly!)

    There's also the style of using a short unique prefix to group related
    names together.  This is not used much in Python, but it is mentioned for
    completeness.  For example, the os.stat() function returns a tuple whose
    items traditionally have names like st_mode, st_size, st_mtime and so on.
    (This is done to emphasize the correspondence with the fields of the
    POSIX system call struct, which helps programmers familiar with that.)

    The X11 library uses a leading X for all its public functions.  In Python,
    this style is generally deemed unnecessary because attribute and method
    names are prefixed with an object, and function names are prefixed with a
    module name.

    In addition, the following special forms using leading or trailing
    underscores are recognized (these can generally be combined with any case
    convention):

    - _single_leading_underscore: weak "internal use" indicator.  E.g. "from M
      import *" does not import objects whose name starts with an underscore.

    - single_trailing_underscore_: used by convention to avoid conflicts with
      Python keyword, e.g.

      Tkinter.Toplevel(master, class_='ClassName')

    - __double_leading_underscore: when naming a class attribute, invokes name
      mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

    - __double_leading_and_trailing_underscore__: "magic" objects or
      attributes that live in user-controlled namespaces.  E.g. __init__,
      __import__ or __file__.  Never invent such names; only use them
      as documented.

  Prescriptive: Naming Conventions

    Names to Avoid

      Never use the characters `l' (lowercase letter el), `O' (uppercase
      letter oh), or `I' (uppercase letter eye) as single character variable
      names.

      In some fonts, these characters are indistinguishable from the numerals
      one and zero.  When tempted to use `l', use `L' instead.

    Package and Module Names

      Modules should have short, all-lowercase names.  Underscores can be used
      in the module name if it improves readability.  Python packages should
      also have short, all-lowercase names, although the use of underscores is
      discouraged.

      Since module names are mapped to file names, and some file systems are
      case insensitive and truncate long names, it is important that module
      names be chosen to be fairly short -- this won't be a problem on Unix,
      but it may be a problem when the code is transported to older Mac or
      Windows versions, or DOS.

      When an extension module written in C or C++ has an accompanying Python
      module that provides a higher level (e.g. more object oriented)
      interface, the C/C++ module has a leading underscore (e.g. _socket).

    Class Names

      Almost without exception, class names use the CapWords convention.
      Classes for internal use have a leading underscore in addition.

    Exception Names

      Because exceptions should be classes, the class naming convention
      applies here.  However, you should use the suffix "Error" on your
      exception names (if the exception actually is an error).

    Global Variable Names

      (Let's hope that these variables are meant for use inside one module
      only.)  The conventions are about the same as those for functions.

      Modules that are designed for use via "from M import *" should use the
      __all__ mechanism to prevent exporting globals, or use the older
      convention of prefixing such globals with an underscore (which you might
      want to do to indicate these globals are "module non-public").

    Function Names

      Function names should be lowercase, with words separated by underscores
      as necessary to improve readability.

      mixedCase is allowed only in contexts where that's already the
      prevailing style (e.g. threading.py), to retain backwards compatibility.

    Function and method arguments

      Always use 'self' for the first argument to instance methods.

      Always use 'cls' for the first argument to class methods.

      If a function argument's name clashes with a reserved keyword, it is
      generally better to append a single trailing underscore rather than use
      an abbreviation or spelling corruption.  Thus "print_" is better than
      "prnt".  (Perhaps better is to avoid such clashes by using a synonym.)

    Method Names and Instance Variables

      Use the function naming rules: lowercase with words separated by
      underscores as necessary to improve readability.

      Use one leading underscore only for non-public methods and instance
      variables.

      To avoid name clashes with subclasses, use two leading underscores to
      invoke Python's name mangling rules.

      Python mangles these names with the class name: if class Foo has an
      attribute named __a, it cannot be accessed by Foo.__a.  (An insistent
      user could still gain access by calling Foo._Foo__a.)  Generally, double
      leading underscores should be used only to avoid name conflicts with
      attributes in classes designed to be subclassed.

      Note: there is some controversy about the use of __names (see below).

    Constants

       Constants are usually defined on a module level and written in all
       capital letters with underscores separating words.  Examples include
       MAX_OVERFLOW and TOTAL.

    Designing for inheritance

      Always decide whether a class's methods and instance variables
      (collectively: "attributes") should be public or non-public.  If in
      doubt, choose non-public; it's easier to make it public later than to
      make a public attribute non-public.

      Public attributes are those that you expect unrelated clients of your
      class to use, with your commitment to avoid backward incompatible
      changes.  Non-public attributes are those that are not intended to be
      used by third parties; you make no guarantees that non-public attributes
      won't change or even be removed.

      We don't use the term "private" here, since no attribute is really
      private in Python (without a generally unnecessary amount of work).

      Another category of attributes are those that are part of the "subclass
      API" (often called "protected" in other languages).  Some classes are
      designed to be inherited from, either to extend or modify aspects of the
      class's behavior.  When designing such a class, take care to make
      explicit decisions about which attributes are public, which are part of
      the subclass API, and which are truly only to be used by your base
      class.

      With this in mind, here are the Pythonic guidelines:

      - Public attributes should have no leading underscores.

      - If your public attribute name collides with a reserved keyword, append
        a single trailing underscore to your attribute name.  This is
        preferable to an abbreviation or corrupted spelling.  (However,
        notwithstanding this rule, 'cls' is the preferred spelling for any
        variable or argument which is known to be a class, especially the
        first argument to a class method.)

        Note 1: See the argument name recommendation above for class methods.

      - For simple public data attributes, it is best to expose just the
        attribute name, without complicated accessor/mutator methods.  Keep in
        mind that Python provides an easy path to future enhancement, should
        you find that a simple data attribute needs to grow functional
        behavior.  In that case, use properties to hide functional
        implementation behind simple data attribute access syntax.

        Note 1: Properties only work on new-style classes.

        Note 2: Try to keep the functional behavior side-effect free, although
        side-effects such as caching are generally fine.

        Note 3: Avoid using properties for computationally expensive
        operations; the attribute notation makes the caller believe
        that access is (relatively) cheap.

      - If your class is intended to be subclassed, and you have attributes
        that you do not want subclasses to use, consider naming them with
        double leading underscores and no trailing underscores.  This invokes
        Python's name mangling algorithm, where the name of the class is
        mangled into the attribute name.  This helps avoid attribute name
        collisions should subclasses inadvertently contain attributes with the
        same name.

        Note 1: Note that only the simple class name is used in the mangled
        name, so if a subclass chooses both the same class name and attribute
        name, you can still get name collisions.

        Note 2: Name mangling can make certain uses, such as debugging and
        __getattr__(), less convenient.  However the name mangling algorithm
        is well documented and easy to perform manually.

        Note 3: Not everyone likes name mangling.  Try to balance the
        need to avoid accidental name clashes with potential use by
        advanced callers.


Programming Recommendations
    - Code should be written in a way that does not disadvantage other
      implementations of Python (PyPy, Jython, IronPython, Pyrex, Psyco,
      and such).

      For example, do not rely on CPython's efficient implementation of
      in-place string concatenation for statements in the form a+=b or a=a+b.
      Those statements run more slowly in Jython.  In performance sensitive
      parts of the library, the ''.join() form should be used instead.  This
      will ensure that concatenation occurs in linear time across various
      implementations.

    - Comparisons to singletons like None should always be done with
      'is' or 'is not', never the equality operators.

      Also, beware of writing "if x" when you really mean "if x is not None"
      -- e.g. when testing whether a variable or argument that defaults to
      None was set to some other value.  The other value might have a type
      (such as a container) that could be false in a boolean context!

    - When implementing ordering operations with rich comparisons, it is best to
      implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__,
      __ge__) rather than relying on other code to only exercise a particular
      comparison.

      To minimize the effort involved, the functools.total_ordering() decorator
      provides a tool to generate missing comparison methods.

      PEP 207 indicates that reflexivity rules *are* assumed by Python.  Thus,
      the interpreter may swap y>x with x<y, y>=x with x<=y, and may swap the
      arguments of x==y and x!=y.  The sort() and min() operations are
      guaranteed to use the < operator and the max() function uses the >
      operator.  However, it is best to implement all six operations so that
      confusion doesn't arise in other contexts.

    - Use class-based exceptions.

      String exceptions in new code are forbidden, because this language
      feature is being removed in Python 2.6.

      Modules or packages should define their own domain-specific base
      exception class, which should be subclassed from the built-in Exception
      class.  Always include a class docstring.  E.g.:

        class MessageError(Exception):
            """Base class for errors in the email package."""

      Class naming conventions apply here, although you should add the suffix
      "Error" to your exception classes, if the exception is an error.
      Non-error exceptions need no special suffix.

    - When raising an exception, use "raise ValueError('message')" instead of
      the older form "raise ValueError, 'message'".

      The paren-using form is preferred because when the exception arguments
      are long or include string formatting, you don't need to use line
      continuation characters thanks to the containing parentheses.  The older
      form will be removed in Python 3000.

    - When catching exceptions, mention specific exceptions
      whenever possible instead of using a bare 'except:' clause.

      For example, use:

          try:
              import platform_specific_module
          except ImportError:
              platform_specific_module = None

      A bare 'except:' clause will catch SystemExit and KeyboardInterrupt
      exceptions, making it harder to interrupt a program with Control-C,
      and can disguise other problems.  If you want to catch all
      exceptions that signal program errors, use 'except Exception:'.

      A good rule of thumb is to limit use of bare 'except' clauses to two
      cases:

         1) If the exception handler will be printing out or logging
            the traceback; at least the user will be aware that an
            error has occurred.

         2) If the code needs to do some cleanup work, but then lets
            the exception propagate upwards with 'raise'.
            'try...finally' is a better way to handle this case.

    - Additionally, for all try/except clauses, limit the 'try' clause
      to the absolute minimum amount of code necessary.  Again, this
      avoids masking bugs.

      Yes:

          try:
              value = collection[key]
          except KeyError:
              return key_not_found(key)
          else:
              return handle_value(value)

      No:

          try:
              # Too broad!
              return handle_value(collection[key])
          except KeyError:
              # Will also catch KeyError raised by handle_value()
              return key_not_found(key)

    - Use string methods instead of the string module.

      String methods are always much faster and share the same API with
      unicode strings.  Override this rule if backward compatibility with
      Pythons older than 2.0 is required.

    - Use ''.startswith() and ''.endswith() instead of string slicing to check
      for prefixes or suffixes.

      startswith() and endswith() are cleaner and less error prone.  For
      example:

        Yes: if foo.startswith('bar'):

        No:  if foo[:3] == 'bar':

      The exception is if your code must work with Python 1.5.2 (but let's
      hope not!).

    - Object type comparisons should always use isinstance() instead
      of comparing types directly.

        Yes: if isinstance(obj, int):

        No:  if type(obj) is type(1):

      When checking if an object is a string, keep in mind that it might be a
      unicode string too!  In Python 2.3, str and unicode have a common base
      class, basestring, so you can do:

        if isinstance(obj, basestring):

    - For sequences, (strings, lists, tuples), use the fact that empty
      sequences are false.

      Yes: if not seq:
           if seq:

      No: if len(seq)
          if not len(seq)

    - Don't write string literals that rely on significant trailing
      whitespace.  Such trailing whitespace is visually indistinguishable and
      some editors (or more recently, reindent.py) will trim them.

    - Don't compare boolean values to True or False using ==

        Yes:   if greeting:

        No:    if greeting == True:

        Worse: if greeting is True:

Rules that apply only to the standard library
    - Do not use function type annotations in the standard library.
      These are reserved for users and third-party modules.  See
      PEP 3107 and the bug 10899 for details.


References
    [1] PEP 7, Style Guide for C Code, van Rossum

    [2] http://www.python.org/doc/essays/styleguide.html

    [3] PEP 257, Docstring Conventions, Goodger, van Rossum

    [4] http://www.wikipedia.com/wiki/CamelCase

    [5] Barry's GNU Mailman style guide
        http://barry.warsaw.us/software/STYLEGUIDE.txt

    [6] PEP 20, The Zen of Python

    [7] PEP 328, Imports: Multi-Line and Absolute/Relative


Copyright
    This document has been placed in the public domain.


python学习资料收集

Python基本安装:

    * http://www.python.org/ 官方标准Python开发包和支持环境,同时也是Python的官方网站;
    * http://www.activestate.com/ 集成多个有用插件的强大非官方版本,特别是针对Windows环境有不少改进;

Python文档:

    * http://www.python.org/doc/current/lib/lib.html Python库参考手册。
    * http://www.byteofpython.info/ 可以代替Tutorial使用,有中文译版的入门书籍。
    * http://diveintopython.org/ 一本比较全面易懂的入门书,中文版翻译最近进步为很及时的5.4了。
    * http://www.python.org/peps/pep-0008.html 建议采用的Python编码风格。
    * http://doc.zoomquiet.org/ 包括Python内容的一个挺全面的文档集。

常用插件:

    * http://www.pfdubois.com/numpy/ Python的数学运算库,有时候一些别的库也会调用里面的一些功能,比如数组什么的;
    * http://www.pythonware.com/products/pil/ Python下著名的图像处理库Pil;
    * http://simpy.sourceforge.net/ 利用Python进行仿真、模拟的解决方案;
    * Matplotlib 据说是一个用来绘制二维图形的Python模块,它克隆了许多Matlab中的函数, 用以帮助Python用户轻松获得高质量(达到出版水平)的二维图形;
    * http://www.amk.ca/python/code/crypto python的加解密扩展模块;
    * http://cjkpython.i18n.org/ 提供与python有关的CJK语言支持功能:转码、显示之类。
    * Psyco、Pyrex:两个用于提高Python代码运行效率的解决方案;
    * Pyflakes、PyChecker、PyLint:都是用来做Python代码语法检查的工具。
    * http://wxpython.sourceforge.net/ 基于wxWindows的易用且强大的图形界面开发包wxPython;
    * http://www.pygame.org/ 用Python帮助开发游戏的库,也可以用这个来播放视频或者音频什么的,大概依靠的是SDL;
    * http://starship.python.net/crew/theller/py2exe/ win下将Python程序编译为可执行程序的工具,是一个让程序脱离Python运行环境的办法,也可以生成Windows服务或者COM组件。其他能完成Python脚本到可执行文件这个工作的还有Gordon McMillan's Installer、Linux专用的freeze以及py2app、setuptools等。不过此类工具难免与一些模块有一些兼容性的问题,需要现用现测一下。
    * 嵌入式数据库:BerkeleyDB的Python版,当然还有其他的好多。
    * PEAK提供一些关于超轻量线程框架等基础性重要类库实现。

部分常用工具:

    * http://www.scons.org/ Java有Ant这个巨火的构建工具,Python的特性允许我们构建更新类型的构建工具,就是scons了。
    * Python Sidebar for Mozilla FireFox的一个插件,提供一个用来查看Python文档、函数库的侧边栏。
    * IPython 很好用的Python Shell。wxPython发行版还自带了PyCrust、PyShell、PyAlaCarte和PyAlaMode等几个工具,分别是图形界面Shell和代码编辑器等,分别具有不同特点可以根据自己的需要选用。
    * Easy Install 快速安装Python模块的易用性解决方案。

推荐资源:

    * Parnassus山的拱顶 巨大的Python代码库,包罗万象。既可以从上面下载代码参考学习,同时也是与Python有关程序的大列表。
    * Python号星际旅行船 著名Python社区,代码、文档、高人这里都有。
    * faqts.com的Python程序设计知识数据库 Python程序设计知识库,都是与Python有关的程序设计问题及解决方法。
    * 啄木鸟 Pythonic 开源社区 著名的(也可以说是最好的)国内Python开源社区。

代码示例:

    * http://newedit.tigris.org/technical.htm Limodou的NewEdit编辑器的技术手册,讨论了一些关于插件接口实现、i18实现、wxPython使用有关的问题,值得参考。

其他东西:

    * http://www.forum.nokia.com/main/0,,034-821,00.html Nokia居然发布了在Series 60系统上运行Python程序(图形界面用wxPython)的库,还有一个Wiki页是关于这个的:http://www.postneo.com/postwiki/moin.cgi/PythonForSeries60 。Python4Symbian这个页面是记录的我的使用经验。
    * pyre:使用Python完成高性能计算需求的包,真的可以做到么?还没研究。
    * Parallel Python:纯Python的并行计算解决方案。相关中文参考页面
    * Pexpect:用Python作为外壳控制其他命令行程序的工具(比如Linux下标准的ftp、telnet程序什么的),还没有测试可用程度如何。
    * pyjamas:Google GWT的Python克隆,还处在早期版本阶段。
    * Durus:Python的对象数据库。

有意思的东西:

    * Howie:用Python实现的MSN对话机器人。
    * Cankiri:用一个Python脚本实现的屏幕录像机。

参考资料

    * ZDNET文章:学习Python语言必备的资源
    * Pythonic Web 应用平台对比
    * 在wxPython下进行图像处理的经验 (其实,仅使用wxPython也可以完成很多比较基础的图像处理工作,具体可以参照《wxPython in Action》一书的第12节)
    * 通过win32扩展接口使用Python获得系统进程列表的方法
    * 如何获得Python脚本所在的目录位置
    * Python的缩进问题
    * py2exe使用中遇到的问题
    * idle的中文支持问题
    * 序列化存储 Python 对象

Python IDE

我的IDE选择经验

    * http://www.xored.com Trustudio 一个基于Eclipse的、同时支持Python和PHP的插件,曾经是我最喜欢的Python IDE环境,功能相当全了,不过有些细节不完善以致不大好用。
    * http://pydev.sourceforge.net/ 另一个基于Eclipse的,非常棒的Python环境,改进速度非常快,现在是我最喜欢的IDE。
    * http://www-900.ibm.com/developerWorks/cn/opensource/os-ecant/index.shtml 用 Eclipse 和 Ant 进行 Python 开发
    * http://www.die-offenbachs.de/detlev/eric3.html ERIC3 基于QT实现的不错的PYTHON IDE,支持调试,支持自动补全,甚至也支持重构,曾经在Debian下用它,但图形界面开发主要辅助qt,我倾向wxpython,所以最后还是放弃了这个。
    * http://www.scintilla.org/ 同时支持Win和Linux的源代码编辑器,似乎支持Python文件的编辑。
    * http://boa-constructor.sourceforge.net/ 著名的基于WxPython的GUI快速生成用的Python IDE,但是开发进度实在太差了……
    * http://pype.sourceforge.net/ 成熟的Python代码编辑器,号称功能介于EMACS和IDLE之间的编辑器。
    * http://www.stani.be/python/spe SPE:号称是一个Full Featured编辑器,集成WxGlade支持GUI设计。


python os模块



这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。一个例子就是使用os.sep可以取代操作系统特定的路径分割符。

下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。

    os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

    os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。

    os.getenv()和os.putenv()函数分别用来读取和设置环境变量。

    os.listdir()返回指定目录下的所有文件和目录名。

    os.remove()函数用来删除一个文件。

    os.system()函数用来运行shell命令。

    os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。

    os.path.split()函数返回一个路径的目录名和文件名。

    >>> os.path.split('/home/swaroop/byte/code/poem.txt')
    ('/home/swaroop/byte/code', 'poem.txt')

    os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。

你可以利用Python标准文档去探索更多有关这些函数和变量的详细知识。你也可以使用help(sys)等等。

python学习笔记1

通过实例学习python
1.从HelloWorld开始
#!/usr/bin/python
# -*- coding:utf-8 -*- (当需要使用中文字体的时候,需要使用这行的注释)
__author__ = 'ericssonxiao'
firstString='HelloWorld!'
secString='你好,python!'
print firstString
print secString
print "%s is %d." % ("Python",1)

2.获得用户输入,可以使用raw_input()函数
#!/usr/bin/python
# -*- coding:utf-8 -*-
__author__ = 'ericssonxiao'
username = raw_input('please input your username:')
userpwd = raw_input('please input your userpwd:')
print 'your username is',username,'userpwd is',userpwd



2012年7月27日星期五

每天进步一点点 --- python xmlrpc模块学习笔记

一、简介:
本文介绍了在开发分布式系统过程中,python的作用。开发分布式的系统,是一个困难的挑战。而远程过程调用(Remote Procedure Call)提供了一种简单的构建分布式系统的方式。网络通信的时候,把RPC服务通过接口暴露出来,这样看起来就像是一个普通的过程调用。当你调用远程服务器的一个函数的时候,RPC系统负责处理通信所有的细节。现在流行的云计算平台,例如openstack系统,该系统在内部实现中,各个服务之间大量使用了RPC服务做通信。
自己所知道的RPC接口有三种:CORBA(Common Object Request Broker Architecture),PB(Twisted 的 Perspective Broker), Simple XML-RPC.

CORBA是一个 “重型” 的协议,虽然功能丰富,有专用的打包和传输层,但是不容易掌握。python有一个开源的模块:http://omniorb.sourceforge.net/  提供了CORBA的实现,建议使用。
PB也很轻量化,但是提供了比XML-RPC更丰富的功能。它提供了异步的网络事务处理模式,这也是Twisted的特点,这种异步模式是Twisted的核心,对于网络的应用,异步模式在性能和可伸缩性上有巨大的优势。
XML-RPC是一个更轻量级,易于使用的协议,数据传输使用XML打包,通过HTTP传输。虽然功能不如CORBA丰富,但因为简单,轻量,所以流传很广,便于使用。
XML-RPC的规范,请参考:http://xmlrpc.scripting.com/spec

二、XML-RPC的具体实现
python中提供了一个SimpleXMLRPCServer模块,用于编写XML-RPC的服务器。
然后客户端使用xmlrpc模块来访问XML-RPC服务器。

XML-RPC的服务器代码:

# -*- coding: utf-8 -*-
import SimpleXMLRPCServer

class MyObject:
    def sayHello(self):
        return "hello xmlprc"

obj = MyObject()
server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 80))
server.register_instance(obj)

print "Listening on port 80"
server.serve_forever()

XML-RPC客户端代码:

# -*- coding: utf-8 -*-
import xmlrpclib

server = xmlrpclib.ServerProxy("http://localhost:80")
words = server.sayHello()
print "result:" + words

2012年1月19日星期四

pythonchallenge 通关秘籍 Level 2

url: http://www.pythonchallenge.com/pc/def/map.html
题目图片上写着:
K ---> M
O ---> Q
E ----> G
实际上是对每一个字母的ascii编码 + 2
In [6]: str_list=['K','M','O','Q','E','G']

In [7]: for x in str_list:
   ...:     print 'ascii code:',ord(x),'chr:',x
   ...:    
   ...:    
ascii code: 75 chr: K
ascii code: 77 chr: M
ascii code: 79 chr: O
ascii code: 81 chr: Q
ascii code: 69 chr: E
ascii code: 71 chr: G

代码:
import string
str = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
table=string.maketrans('abcdefghijklmnopqrstuvwxyz','cdefghijklmnopqrstuvwxyzab')
print str.translate(table)
执行结果:
i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.

map转换为ocr
然后进入第二关:http://www.pythonchallenge.com/pc/def/ocr.html




pythonchallenge 通关秘籍 Level 1

学习python的朋友,可以去http://www.pythonchallenge.com 网站看看
下面说说Level 1的通关秘籍:
url: http://www.pythonchallenge.com/pc/def/0.html
答案:按照图片上说的计算2的38次方。
进入ipython:
In [2]: 2**38
Out[2]: 274877906944L

现在修改url地址:http://www.pythonchallenge.com/pc/def/274877906944.html

通关!

2010年12月24日星期五

转载一个文章 “Python vs. PHP”


Posted on 30th March 2005 by Nio in 程序人生

PHP Everywhere 贴出一篇《Python never had a chance against PHP》的文章,这并不是在对 Python 进行挑衅,而是较为客观地对 PHP 和 Python 进行分析,认为在 Web 应用方面,Python 比不上 PHP:


Python is not a template language, in the sense that you cannot mix code and html easily. PHP is a wonderfully flexible in this respect.

Python is a so-so string processing language. One reason being it treats strings as immutable. PHP has much better string processing facilities: embedded "$var in strings", mutable strings, auto-conversion of other data types to strings, output buffering, etc.

PHP's documentation is cleaner and much easier to understand than Python's. Probably because PHP is a much simpler language.

PHP has tighter integration of a lot of web related stuff. For example, HTTP and SERVER variables.

对于各种语言,我的观点从来都是:存在即是合理的,每个语言都有其应用的空间。就对于 Python 而言,在 Web 方面不如 PHP,但其在通用编程方面功能却要比 PHP 强大得多。而现在流行 Web 编程,所以 PHP 这方面的优势也就决定了增长势头要比 Python 猛得多。



关于此文章的评论也很值得一看。I'll certainly concede that PHP has some important advantages over Python, especially in terms of deployment, isolation, and the ease of starting projects. But I can't agree with much of these particular reasons.


* Templating language: this is true, though you can template perfectly well in Python ― there exist PHP-like systems, as well as templating languages implemented on top of Python. Python itself isn't a templating language so there's no single convention. Of course, even PHP has things like Smarty.

* Python is way, way, WAY better at handling strings compared to PHP. This is the thing that has always driven me crazy in PHP. The $'s are nice ― except for the quoting rules so that $'s aren't interpreted in single quoted strings. That drives me nuts. Python does very good auto-conversion in interpolated strings (%s), and explicit conversion is easy enough. Python also has lots of techniques for buffering ― the specific pattern that PHP uses isn't common, but it's easy to do anyway (StringIO). Python has a concise and fast set of string methods, it has decent regular expression support (more convenient than PHP's at least), and it has really good unicode support. Oh, and NO MAGIC QUOTING. Quoting bugs don't come up that often in Python.

* I don't know what to say about the documentation. I like php.net's comments. I find the original documentation quite poor, and obviously the structure of the language is non-existant, lacking namespaces, modules, classes for most (all?) core types, and other basic organization. Also, most of the Python standard library is implemented in Python, and the source is readable. But it's not an uncommon complaint, so apparently it's something that bothers people.

* Don't good PHP programmers avoid the HTTP and SERVER variables? (register globals or whatever it is) If you just mean a global variable with those values from the request ($_POST?), that's easy in Python, and some frameworks use that. Python works with markup, like HTML and XML, better than PHP ― that's the kind of thing I'd think of if I was thinking about web integration.


� Ian BickingPlease don't forget:


* Smarty is just a rework of PHP itself - its a templating language written in a language already capable of templating. A pointless project from the start, in my opinion, which increases the workload, development time, execution time, and adds an aditional layer where issues can occur.

* Single quotes are there for a reason - so that we don't have to escape special characters all the time. I use single quotes and concattenation for everything, which can be a major speed increase when working with strings in PHP. We can, and its recommended to, turn Magic Quoting off.

* PHP has released a version of its original documentation which incorporates the comments from the website. I find this very useful. However, it only works on windows.

* As for the structure of PHP… IMHO it makes it easy for people to get started, and then (if they wish, as I did) to move to more structured development techniques, then on to other lanugages. I've recently started to look at Python as my next development language, after PHP, JavaScript (Client-side), XSL, and XQuery. Without PHP's quick learning curve, I don't think I'd have ever gotted started.

* No, we don't avoid the global variables, we just avoid the depricated ones. $HTTP_SERVER_VARS and the like. Register globals is the method that allows any parameter passed to a script in GET or POST format to be instantly accessible within the script. This is a serious security threat, and therefore we access them now through the $_POST and $_GET arrays. Variables such as $_SERVER allow us access to information which is passed around via http headers from client to server. Very handy.

* With the advent of PHP5, working with HTML and XML has become very easy. We can now quickly populate objects with a DOM, and modify elements/nodes and attributes with ease. We can also perform XPath queries easily on them. XSLT has been around for a while too, so a lot on the time things can be collected and translated without PHP doing much work.


PHP has its place, and in the future I hope that it will grow to incorporate some of the benefits of other languages, such as persistance. But for the moment while developing for the web, I'll first look at whether PHP can provide a solution before considering other platforms.

2010年8月12日星期四

解决python打印中文的问题

#!/usr/bin/python
# -*- coding: utf-8 -*-  
# FileName: PrintChinese.py

s = "中文english"
print s

注意上面标红的那句声明哦!用这个就行了!

python写的一段程序,典型的用户登录,获取请求信息,做相应的导航,获取response。

import httplib
import urlparse
import urllib
import base64
 
class Connection:
def __init__(self, base_url, username, password):
self.base_url = base_url
self.username = username
self.password = password
self.url = urlparse.urlparse(base_url)
 
def request_get(self, resource, args = None):
self.request(resource, "get", args)
 
def request_post(self, resource, args = None):
self.request(resource, "post", args)
 
def request(self, resource, method = "get", args = None):
params = None
path = resource
headers = {}
 
if args:
path += "?" + urllib.urlencode(args)
 
if self.username and self.password:
encoded = base64.encodestring("%s:%s" % (self.username, self.password))[:-1]
headers["Authorization"] = "Basic %s" % encoded
 
if (self.url.port == 443):
conn = httplib.HTTPSConnection(self.url.netloc)
else:
conn = httplib.HTTPConnection(self.url.netloc)
 
req = conn.request(method.upper(), "/" + path, None, headers)
 
r = conn.getresponse()