Python 编程常见问题
经常使用Python编程,把经常遇到问题在这里记录一下,省得到网上查找,因此这篇文章会持续更新,需要的可以Mark一下。进入正题:
1.Python常用的文件头声明
#!/usr/bin/python
#-*- coding: UTF-8 -*-
#
# @filename:
# @author:
# @since: 2013-
# @version: 0.0.1
#
# Usage:
###############################################################################
import os
import sys
import shutil
import fileinput
# utf8
import 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 os
import optparse
pid = 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_port
pub_port = options.publish_port
print ("[Process:%d] is listening on (tcp://*:%s) and publish to (tcp://*:%s) ..." %
(pid, sink_port, pub_port))
3.Python获取外部中断命令(Ctrl+C)结束本程序
import time
import os
import signal
is_exit = False
pid = 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 second
time.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保存!!!
# utf8
import codecs
def openFileUtf8(fname):
fd = codecs.open(fname, "w", encoding = "UTF-8")
return fd
def 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 codecs
utf8str = "我爱你love,中国"
print "utf8:", utf8str
utf16str = utf8str.decode('utf-8')
print "utf16 len (==10):", len(utf16str)
# 截取前3个字符
utf16str = utf16str[0:7]
# 截取到的字符转回UTF-8
utf8substr = utf16str.encode('utf-8')
print "utf8 substr:", utf8substr
print "上面全部过程写成一句话: 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
在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, Extension
ImportError: 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
7. 使用 MySQL - Python
http://www.cnblogs.com/ceniy/archive/2010/08/31/1814066.html8. 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()
(未完待续...)