Python 编程常见问题

来源:互联网 发布:外网端口查询 编辑:程序博客网 时间:2024/05/22 01:37

Python 编程常见问题

经常使用Python编程,把经常遇到问题在这里记录一下,省得到网上查找,因此这篇文章会持续更新,需要的可以Mark一下。进入正题:

1.Python常用的文件头声明

#!/usr/bin/python#-*- coding: UTF-8 -*-## @filename: # @author: # @since: 2013-# @version: 0.0.1## Usage:###############################################################################import osimport sysimport shutilimport fileinput# utf8import codecs

2.Python命令参数解析(长参数和短参数)

################################################################ 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获取外部中断命令(Ctrl+C)结束本程序

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文件操作

一个好的习惯就是永远使用UTF-8编码作一切事情,包括Python文件本身。下面使用UTF-8编码打开文件并写入数据
#!/usr/bin/python#-*- coding: UTF-8 -*-# !!!请确保本Python文件以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, "我爱你,中国")closeFile(fw)

5.Python UTF-8中文字符串操作

下面演示如何获取UTF8字符串长度(有效文字个数)和截断:
#!/usr/bin/python#-*- coding: UTF-8 -*-# !!!请确保本Python文件以UTF-8保存!!!# 对于中文UTF-8编码的字符串,如何得到长度并截断其中的字符呢?# 思路就是:#   首先把UTF-8字符串转成UTF-16(Unicode)字符串,#   然后判断UTF-16长度,截断UTF-16字符串,再转回UTF-8:import codecsutf8str = "我爱你love,中国"print "utf8:", utf8strutf16str = utf8str.decode('utf-8')print "utf16 len (==10):", len(utf16str)# 截取前3个字符utf16str = utf16str[0:7]# 截取到的字符转回UTF-8utf8substr = utf16str.encode('utf-8')print "utf8 substr:", utf8substrprint "上面全部过程写成一句话: utf8substr = utf8str.decode('utf-8')[0:7].encode('utf-8') "utf8substr = utf8str.decode('utf-8')[0:7].encode('utf-8')print "utf8 substr:", utf8substr
运行截图:


6. MySQL - Python

1) 在Ubuntu上使用Python操作MySQL, 首先是安装:

$ 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

错误解决办法:
错误:Traceback (most recent call last):  File "setup.py", line 5, in    from setuptools import setup, ExtensionImportError: No module named setuptools解决:$ sudo apt-get install python-setuptools错误:sh: mysql_config: not found...EnvironmentError: mysql_config not found解决:$ sudo apt-get install libmysqlclient-dev错误:...error: command 'gcc' failed with exit status 1解决:$ sudo apt-get install python-dev

2) 在RHEL6.x上使用Python操作MySQL:

# cd MySQL-python-1.2.3# python ez_setup.py -U setuptools# yum install -y python-devel# python setup.py build# python setup.py install# python>>> import MySQLdb

8. UTF-8 文件操作

UTF-8的网站出现了中文乱码的问题,怀疑是缺少UTF-8 BOM头导致的。所以给所有HTML和JS文件添加了BOM头,问题解决。

def removeBomHeader(file):    BOM = b'\xef\xbb\xbf'    f = open(file, 'rb')    if f.read(3) == BOM:        fbody = f.read()        f.close()        with open(file, 'wb') as f:            f.write(fbody)    f.close()def addBOMHeader(file):    BOM = b'\xef\xbb\xbf'    f = open(file, 'rb')    if f.read(3) != BOM:        f.close()        f = open(file, 'rb')        fbody = f.read()        f.close()        with open(file, 'wb') as f:            f.write(BOM)            f.write(fbody)    f.close()

打开终端,设置为utf-8显示模式:

python

import codec

>>> s= u'\u7f8e\u9cf3'
>>> s= u'\u7f8e\u9cf3'
>>> s
u'\u7f8e\u9cf3'
>>> print s
美鳳
>>> u16 = u'\u7f8e\u9cf3'
>>> print u16
美鳳
>>> u8=u16.encode('utf-8')
>>> print u8
美鳳
>>> u8
'\xe7\xbe\x8e\xe9\xb3\xb3'
>>> type(u16)
<type 'unicode'>
>>> type(u8)
<type 'str'>
>>>


(未完待续...)







原创粉丝点击