my python FAQ

my python FAQ

  1. Python coding standards
  3. Determine whether the object contains an attribute if hasattr(object,'attribute')
  4. Reflect to obtain 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 expression 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. The pylint code scanning specification tool installs pylint under Windows for automatic code analysis. After configuration, eclipse sets build Automatically. After each save, a report is generated to indicate whether your code conforms to the programming specification and give you a score (my copy can run through The code is -13/10, minus 13, shame...) Refer to 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 then copy all the files there to the Python Scripts directory (such as: D:\Python26\Scripts) in the command line Try to execute pylint. If you output help, it means that pylint has been installed successfully. The default specification of pylint does not conform to the camel case variable and method naming method. If necessary, create a common conf file to determine the regular expression configuration draft of variables and methods: pylint.conf It can be added to the eclipse=>Window=>preferences=>Pydev=>Pylint use Pylint tick, and the location of pylint fills in the local path of the download package pylint D:\develop\pylint\pylint-0.22.0\ arguments box Fill in: --rcfile=C:\Python26\Scripts\pylint.conf
  10. Check if the 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 
  1. Cherrypy access to static resources html css js images and other resources: cherryd -i cpapp -c prod.conf cherrypy.quickstart(Root(),'/', config=conf) For details, please refer to: http://www.cherrypy. org/wiki/StaticContent
  2. python binding cpp boost method: Create new cpp for hello.cpp binding hello_wrap.cpp #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 in the current directory Generate file python command line: >>>import hello >>> print hello.greet(1) Boost.Python >>> python ctypes method: html
char const* greet(unsigned x)
static char const* const msgs[] = {"hello", "Boost.Python", "world!" };
if (x> 2)
return "nothing";
return msgs[x];
  1. True in Python Before version 2.2.1, Python did not have a separate Boolean data type. In order to make up for this defect, Python accepts almost everything in a Boolean environment (such as if statements), following the following rules: • 0 is false; all other values ​​are true. • The empty string ("") is false; all other strings are true. • An empty list ([]) is false; all other lists are true. • Empty tuple (()) is false; all other tuples are true. • Empty dictionary ({}) is false; all other dictionaries are true. These rules still apply to Python 2.2.1 and later versions, but now you can also use a real boolean value, whose value is either True or False. Please note that the first letter is uppercase; these values ​​are case sensitive like everything else in Python.
  2. The python process terminates abnormally. Possible reasons: cmd call error, memory block read error, program error encountered in the project is a program error and no except is obtained. For example, i = 1 while True: i = i+1 if i==100: i/0 The process terminates if a division by 0 error occurs def test(): i = 1 while True: i = i+1 print [ for c in messages.columns] if i==100: i/0 try: test() except Exception: print Exception is not captured inside the function and captured by the periphery will also cause the process to terminate
  3. Assume that the current project has several folders (core, domain, util) classes that need to be installed in python to establish 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@', url='', license='(c) 2010 NetQin', include_package_data=True, zip_safe=False,) Under normal circumstances, packages should write the project name or only install a few modules of the project Then packages = ['scservice.core','scservice.domain','scservice.util'], sudo python develop can create a link file, if svn is updated, it can be updated without running the installation again and you can use sudo python install installs several folders directly under/python/lib/site-packages to test: Enter the python command line: from core.rule import Rule If no error is reported, the installation is successful
  4. Why can str be traversed by for? (From python mail list) str does not provide the __iter__() method like list, and cannot generate iteration objects, but it can be traversed by for. 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 the sequence, as long as it is the sequence, it can handle it. The sequence protocol is defined here: the __getitem__() method with integer arguments starting at 0 In other words, as long as there is a __getitem__ method, it is considered a sequence. for can handle it. Verify it: class A(object): def __getitem__(self, item): print'getitem:', item if item == 5: raise IndexError() return item for i in A(): print i
  5. dict list conversion to construct a dict with empty values ​​dict.fromkeys([1,2,3]) => {1:None,2:None,3:None} to construct a dict dict([(1,2),(2,3 )]) => {1:2, 2:3} Construct a list list from the dict key( {1:2, 2:3}) => [1,2] or {1:2, 2:3}. keys() Construct a list from the value of dict [j for i,j in {1:2, 2:3}.iteritems()]
  6. Install python wget 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 install $ cd Python-2.6.5 $ ./configure $ make $ make install l If the default version has not been replaced, you need to create a software 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
  7. Check if the variable is defined a = 1 if a in dir()
  8. Pycurl binds to a specific IP address
def iptest(ip):
    c = pycurl.Curl()
    c.setopt(c.URL, "")
# Bind to a specific IP address
    c.fp = StringIO.StringIO()
    print c.fp.getvalue()
  1. Using random random numbers in python multi-process Linux's fork is copy-write, that is, only the modified part of the fork process will open up additional memory; and the random number is a pseudo-random number derived from the seed value, and the fork is the process The seeds are the same, so the values ​​are the same. Therefore, every time after finishing random, random.seed() is needed to generate a new random number uuid method: >>> import uuid # make a random UUID >>> uuid.uuid4() UUID('16fd2706-8baf- 433b-82eb-8c7fada847da')
def executeChangeable():
    pid = os.getpid()
    randpart = random.randint(10000000, 99999999)
    return pid, randpart
  1. python crawling 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=''+str(pagenum + 1)+'.html'


        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


                    num += 1;

        pagenum += 1;


    print "Total number of agents processed: "+ str(num)

Reference: my python FAQ-Cloud+Community-Tencent Cloud