My python FAQ

Source: Internet
Author: User
Tags python static method
  1. Python coding specifications
  2. Http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
  3. Determines whether an object contains an attribute.
    If hasattr (object, 'attribute ')
  4. Reflection acquisition class instance
    Globals () ['classname'] ()
  5. Python date conversion
    String to date:
    Import time
    TimeInDate = time. strptime (timeInStr, "% Y-% m-% d % H: % M: % S ")
    Date to string:
    TimeInStr = time. strftime ("% Y/% m/% d % H: % M: % S", time. localtime ())
    TimeInStr = time. strftime ("% Y/% m/% d % H: % M: % S", timeInDate)
  6. Find the specified value in the list
    Guids = []
    Guids. append (1)
    Guids. append (3)
    GuidTofind = 4
    Guidin = filter (lambda g: g = guidTofind, guids)
    # Not in the list
    If len (guidin) = 0:
  7. Python ternary expressions
    S = ('negitive ', 'positive') [n> = 0]
  8. Python static method
    Annotation:
    @ Staticmethod
    Def bar ():
    Print Foo. str
    Other:
    Def bar ():
    Print Foo. str
    Bar = staticmethod (bar)
  9. Install pylint code scanning standard tool in Windows
    Pylint is used for automatic code analysis. After configuration, eclipse sets build Automatically and generates a report after each save, indicating whether your Code complies with programming specifications, and give you a score (one of my code that can pass through is-13/10, negative 13, shame ...)
    Reference http://www.logilab.org/card/pylint_manual
    But the result still prompts: can't open file 'd: \ Python26 \ Scripts \ pylint ': [Errno 2] No such file or directory
    You need to open the D: \ pylint-0.22.0 \ bin directory and copy all the files there to the Python
    Under the Scripts directory (for example, D: \ Python26 \ Scripts)
    Execute pylint in the command line. If the help is output, the installation is successful.
    Pylint default specification variables and methods that do not comply with the camper mode naming method visual needs to create a public conf file to determine the Regular Expression of variables and Methods
    Configuration draft: pylint. conf
    You can add it to eclipse> Window => preferences => Pydev => Pylint
    Use Pylint hook, location of pylint fill in the download package pylint local path D: \ develop \ pylint \ pylint-0.22.0 \ lint. py
    In the arguments box, enter -- rcfile = C: \ Python26 \ Scripts \ pylint. conf.
  10. Check whether a file exists
    Import OS. path
    OS. path. isfile (fname)
  11. Post xml by http request
    import httplib, urllib
    params = urllib.urlencode( \
    {'parameter': pValue, "p":valuep})
    headers = { "Content-type": "text/xml,charset=utf-8"}
    conn = httplib.HTTPConnection(self.webHost+":"+self.webPort)
    conn.request("POST", "/"+self.webPath+"/?"+params, content , headers)
    response = conn.getresponse()
    print response.status, response.reason
    print response.read()
    conn.close()
  12. Cherrypy accesses static Resources
    How to access html css js images and other resources:
    Cherryd-I cpapp-c prod. conf
    Cherrypy. quickstart (Root (), '/', config = conf)
    See: http://www.cherrypy.org/wiki/StaticContent
  13. Python binding cpp
    Boost mode:
    Create hello. cpp
    char const* greet(unsigned x)
    {
    static char const* const msgs[] = { "hello", "Boost.Python", "world!" };
    if (x > 2)
    return "nothing";
    return msgs[x];
    }

    Cpp hello_wrap.cpp for binding

    #include 
    #include
    using namespace boost::python;
    char const* greet(unsigned x);
    BOOST_PYTHON_MODULE(hello)
    {
    def("greet", greet, "return one of 3 parts of a greeting");
    }

    Compile:
    Sudo g ++-lpython2.5-lboost_python-I/usr/include/python2.5 hello. cpp hello_wrap.cpp-shared-o hello. so

    Generate the python command line for the hello. so file in the current directory:
    >>> Import hello
    >>> Print hello. greet (1)
    Boost. Python
    >>>

    Python ctypes: http://blogold.chinaunix.net/u/21908/showart_2225882.html

  14. True in Python
    Before version 2.2.1, Python does not have a separate boolean data type. To make up for this defect, Python accepts almost everything in a Boolean environment (such as an if statement) and follows the following rules:
    • 0 is false; all other values are true.
    • Null String ("") is false; all other strings are true.
    • Empty list ([]) is false; all other lists are true.
    • Null tuple () is false; all other tuple is true.
    • The value of null dictionary ({}) is false, and the value of all other dictionary statements is true.
    These rules are still applicable to Python 2.2.1 and later versions, but now you can use real boolean values, which are True or False. Note that the first letter is in uppercase; these values are case sensitive just as they are in Python.
  15. Python Process Termination exception
    Possible cause: cmd call error memory block read error program error
    The project encounters a program error and does not obtain the token. For example
    I = 1
    While True:
    I = I + 1
    If I = 100:
    I/0

    The process stops when the error code is displayed
    Def test ():
    I = 1
    While True:
    I = I + 1
    Print [c. name for c in messages. columns]
    If I = 100:
    I/0
    Try:
    Test ()
    Failed t Exception:
    Print Exception
    If a function is not captured inside the function, the process is terminated if it is captured outside the function.

  16. Assume that the current project has several folders (core, domain, util) and classes that need to be installed in python.
    Create setup. py
    From setuptools import setup
    Setup (name = 'scservice ',
    Version = '0. 1.0 ',
    Description = "Easy python framework for SC service ",
    Packages = ['core', 'domain ', 'util'],
    Platforms = 'any ',
    Keywords = 'Framework for SC service ',
    Author = 'shen guanpu ',
    Author_email = 'shenguanpu @ netqin.com ',
    Url = 'www .netqin.com ',
    License = '(c) 2010 netqin ',
    Include_package_data = True,
    Zip_safe = False,
    )
    Under normal circumstances, packages should write the project name or install only a few modules of the project. Then packages = ['scservice. core', 'scservice. domain ', 'scservice. util'],

    Sudo python setup. py develop can be used to create a link file. If svn is updated, it can be updated without running the installation.
    Sudo python setup. py install directly installs several folders under/python/lib/site-packages
    Test: Go to the python command line:
    From core. rule import Rule
    If no error is reported, the installation is successful.

  17. Why can I use str for traversal? (From python mail list)
    Str does not provide the _ iter _ () method like list. It cannot generate iteration objects, but can be traversed using.
    The reason is:
    Python's for statement iterates over the items of any sequence (a list
    Or a string), in the order that they appear in the sequence.

    For is for sequence, which can be processed as long as it is sequence.

    Sequence protocol is defined here:
    Http://docs.python.org/library/functions.html#iter

    The _ getitem _ () method with integer arguments starting at 0

    That is to say, as long as there are _ getitem _ methods, they are all sequence and for can be processed.
    Verify:
    Class A (object ):
    Def _ getitem _ (self, item ):
    Print 'getitem: ', item
    If item = 5:
    Raise IndexError ()
    Return item

    For I in ():
    Print I

  18. Dict list Conversion
    Create a null dict. fromkeys ([, 3]) =>{ 1: None, 2: None, 3: None}
    Build dict ([(1, 2), (2, 3)]) =>}
    Build a list ({,}) from the key of dict => [1, 2] or {,}. keys ()
    Build list [j for I, j in {,}. iteritems ()] from the value of dict
  19. Install python
    Wget http://www.python.org/ftp/python/2.6.5/Python-2.6.5.tar.bz2
    Unzip: $ bzip2-d Python-2.5.2.tar.bz2
    $ Tar-xvf Python-2.5.2.tar
    Transfer Location:
    $ Mv Python-2.6.5/usr/local/
    L Installation
    $ Cd Python-2.6.5
    $./Configure
    $ Make
    $ Make install
    L if the default version is not replaced, you need to create a soft link.
    $ Cd/usr/bin
    $ Ll | grep python // view python in this directory
    $ Rm-rf python
    $ Ln-s/usr/local/Python-2.6.5/python./python // soft link
  20. Check whether the variable is defined
    A = 1
    If a in dir ()
  21. Bind Pycurl to a specific IP Address

    Def iptest (ip ):
    C = pycurl. Curl ()
    C. setopt (c. URL, "http://www.ip138.com/ip2city.asp ")
    # Binding to a specific IP Address
    C. setopt (pycurl. INTERFACE, ip)
    C. perform ()
    C. fp = StringIO. StringIO ()
    Print c. fp. getvalue ()
    C. close ()
  22. Use random number in python multi-process

    In Linux, fork writes and copies, that is, the fork process only opens up memory for the modified part. The random number is based on
    The pseudo-random number obtained by the seed value. The seed of the fork process is the same, so the value is the same. Therefore, after random is completed,
    Random. seed () is required to generate a new random number.

    def executeChangeable():
    pid = os.getpid()
    random.seed()
    randpart = random.randint(10000000, 99999999)
    return pid, randpart

    Uuid mode:

    >>> import uuid

    # make a random UUID
    >>> uuid.uuid4()
    UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

     

  23. Python captures http Proxy
    Def getproxycn ():

    PortDict = {"R": "8", "D": "0", "C": "1", "M": "4", "Z ": "3", "K": "2", "I": "7", "L": "9", "B": "5", "W ": "6 "};

    Pagenum = 0

    Num = 0;

    Proxyfile = "proxys.txt"

    File = open (proxyfile, "w + ");

    While pagenum <= 9:

    Url = 'HTTP: // www.cnproxy.com/proxy'{str (pagenum + 1100000000'.html'

    Html = urllib2.urlopen (url)

    For line in html:

    If "HTTP" in line:

    Arra = line. upper (). split ("<TR> <TD> ")

    Arrb = arra [1]. split ("<script type = TEXT/JAVASCRIPT> ")

    Ip = arrb [0]

    Port = arrb [1]. split (") </SCRIPT>") [0]. split ("DOCUMENT. WRITE (\": \ "") [1]

    Port = port. replace ("+ ","");

    P = "";

    For I in range (len (port )):

    Alph = port [I: I + 1]

    P + = portDict [alph];

    Print ip + ":" + p

    File. write (ip + ":" + p + "\ n ")

    Num + = 1;

    Pagenum + = 1;

    File. close ();

    Print "Total number of processed proxies:" + str (num)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.