Python programming FAQ
I often use Python programming, and record frequently encountered problems here to save the time for online searching. Therefore, this article will be updated continuously and you can mark what you need. Enter the subject:
1. Python common file header Declaration
#!/usr/bin/python#-*- coding: UTF-8 -*-## @filename: # @author: # @since: 2013-# @version: 0.0.1## Usage:###############################################################################import osimport sysimport shutilimport fileinput# utf8import codecs
2. parse Python command parameters (long parameters and short parameters)
################################################################ command line for this app:# $ python app.py -s 5555 -p 5556# or# $ python app.py --sink-port 5555 --publish-port 5556###############################################################import osimport optparsepid = os.getpid()# parse our options# see usage for optparse.OptionParser():# http://docs.python.org/2/library/optparse.html#parser = optparse.OptionParser()parser.add_option("-s", "--sink-port", action="store", dest="sink_port", help="Specifies sink port on that service is listening")parser.add_option("-p", "--publish-port", action="store", dest="publish_port", help="Specifies publish port service publish to")# parse args and get options(options, args) = parser.parse_args()sink_port = options.sink_portpub_port = options.publish_portprint ("[Process:%d] is listening on (tcp://*:%s) and publish to (tcp://*:%s) ..." % (pid, sink_port, pub_port))3. Python obtains the External Interrupt command (CTRL + C) to end the program.
import timeimport osimport signalis_exit = Falsepid = os.getpid()def sigint_handler(signum, frame): global is_exit is_exit = True print "[Process:%d] Receive a signal %d, is_exit = %d" % (pid, signum, is_exit)signal.signal(signal.SIGINT, sigint_handler)signal.signal(signal.SIGTERM, sigint_handler)while not is_exit:# sleep 1 secondtime.sleep(1)print "."print "[Process:%d] exit!" % (pid)
4. Python UTF-8 File Operations
A good habit is to always use UTF-8 encoding for everything, including the python file itself. The following uses UTF-8 encoding to open the file and write data:
#! /Usr/bin/Python #-*-coding: UTF-8 -*-#!!! Please make sure this python file is saved in UTF-8 !!! # Utf8import codecsdef openfileutf8 (fname): FD = codecs. open (fname, "W", encoding = "UTF-8") return fddef closefile (FD): FD. close () def writeutf8 (FD, STR): FD. write (Unicode (STR, "UTF-8") def writelnutf8 (FD, STR): FD. write (Unicode (STR, "UTF-8") + '\ r \ n') FW = openfileutf8 ("/path/to/yourfile.txt") writeutf8 (FW, "I love you, china ") closefile (FW)5. Python UTF-8 Chinese character string operations
The following shows how to obtain the utf8 String Length (number of valid texts) and truncation:
#! /Usr/bin/Python #-*-coding: UTF-8 -*-#!!! Please make sure this python file is saved in UTF-8 !!! # How do I get the length and truncate the characters of a Chinese UTF-8-encoded string? # Idea is: # first convert the UTF-8 string into a UTF-16 (UNICODE) string, # Then judge the length of the UTF-16, cut off the UTF-16 string, and then back to the UTF-8: Import codecsutf8str = "I love you love, china "print" utf8: ", utf8strutf16str = utf8str. decode ('utf-8') print "UTF16 Len (= 10):", Len (utf16str) # truncate the first 3 characters utf16str = utf16str [0: 7] # truncate the characters into the UTF-8utf8substr = utf16str. encode ('utf-8') print "utf8 substr:", utf8substrprint "the above process is written as a sentence: utf8substr = utf8str. decode ('utf-8') [0: 7]. encode ('utf-8') "utf8substr = utf8str. decode ('utf-8') [0: 7]. encode ('utf-8') print "utf8 substr:", utf8substr
Run:
6. mysql-Python
To operate MySQL using python on Ubuntu, first install:
$ wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz$ tar -zxvf MySQL-python-1.2.3.tar.gz$ cd MySQL-python-1.2.3$ sudo python setup.py install
Solution:
Error: traceback (most recent call last): file "setup. PY ", line 5, in from setuptools import setup, extensionimporterror: No module named setuptools solve: $ sudo apt-Get install Python-setuptools error: Sh: mysql_config: Not found... environmenterror: mysql_config not found solution: $ sudo apt-Get install libmysqlclient-dev error :... error: Command 'gcc 'failed with exit status 1 solution: $ sudo apt-Get install Python-Dev
7. Use mysql-Python
Http://www.cnblogs.com/ceniy/archive/2010/08/31/1814066.html
(To be continued ...)