my python FAQ

my python FAQ

  1. Python coding standards
  2. http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
  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 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 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\lint.py 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 
print response.read()
conn.close()
  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 hello.so in the current directory Generate hello.so file python command line: >>>import hello >>> print hello.greet(1) Boost.Python >>> python ctypes method: http://blogold.chinaunix.net/u/21908/showart_2225882. 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 [c.name 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 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 only install a few modules of the project Then packages = ['scservice.core','scservice.domain','scservice.util'], sudo python setup.py 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 setup.py 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: http://docs.python.org/library/functions.html#iter 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 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 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, "http://www.ip138.com/ip2city.asp")
# Bind to a specific IP address
    c.setopt(pycurl.INTERFACE,ip)
    c.perform()
    c.fp = StringIO.StringIO()
    print c.fp.getvalue()
    c.close()
  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()
    random.seed()
    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='http://www.cnproxy.com/proxy'+str(pagenum + 1)+'.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 agents processed: "+ str(num)

 
Reference: https://cloud.tencent.com/developer/article/1067245 my python FAQ-Cloud+Community-Tencent Cloud