脚本格式
#!/usr/bin/python3
#encoding=utf-8
命令行接收参数
import sys
print(sys.argv[0]) /* 第0个参数,表示脚本名称 */
print(sys.argv[1]) /* 第1个参数 */
自定义模块
- 新建一个文件夹mymod作为包名称(package),并在包里创建__init__.py初始化脚本。脚本内容为空。
- 在mymod文件夹里创建一个user.py,并定义一个方法 getName(name)
- 应用方式一:import mymod.user,使用方式:mymod.user.getName("hongbo")
- 应用方式二:from mymod import user,使用方式:user.getName("hongbo")
面向对象范例
实例1:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def printScore(self):
print('%s: %s' % (self.name, self.score))
if __name__ == '__main__':
lisa = Student("Lisa Simpson", 87)
lisa.printScore()
实例2:
class Hotnet(object):
#类变量
config = '1.02'
instance = None
#(魔术)构造
def __init__(self, config):
self.config = config
#(魔术)析构
def __del__(self):
print("Class destruct")
#(魔术)检测长度
def __len__(self):
return 10
#类方法
@classmethod
def getVersion(cls):
print("version:"+config.version)
#实例方法(普通方法)
def run(self):
pring("The hotnet is running!")
#静态方法
@staticmethod
def getInstance(config):
if Hotnet.instance == None:
Hotnet.instance = Hotnet(config)
return Hotnet.instance
参数类型检测
通过一个求绝对值函数来示例:
def myAbs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad opreand type')
if x >= 0:
return x
else:
return -x
列表生成表达式范例
实例1:
[x * x for in range(1, 11)]
#生成结果:[1,4,9,16,...,81,100]
实例2:
[x * x for in range(1, 11) if x % 2 == 0]
#生成结果:[4,16,36,64,100]
实例3:
[a + b for a in 'ABC' for b in '123']
#生成结果:['A1','A2','A3','B1','B2','B3','C1','C2','C3']
函数可以当参数传递仅函数中使用
def add(x, y, f):
return f(x) + f(y)
print(add(-5, 6, abs))
#返回结果:11
文件读写
首先来读一个文件
try:
f = open('/var/www/haha.txt', 'r')
print f.read()
except IOError, e:
print 'ioerror:', e
finally:
if f:
f.close()
读取的时候,read(1024)可以指定读取长度,如果入参为空,则全部读取。readlines()可以一行一行读取,如果嫌麻烦还可以这样写:
with open('/var/www/haha.txt', 'r') as f:
print f.read()
如上的写法,不需要再显式调用f.close(),文件会自动关闭。
再来一个写文件的示例:
with open('/var/www/haha.txt', 'w') as f:
f.write('hello,world!')
时间日期
用到时间相关函数,需要先包含时间模块:
import time
time.localtime()和time.gmtime()是分别获取本地和零时区时间对象。
time.mktime(time.localtime()) 可以获取本地时间戳。
time.strftime(format, time)可以用来格式化时间,例如:
time.strftime('%Y-%m-%d', time.localtime())
#输出结果:2016-03-03
除了格式化,反格式化也很常用,就是把字符串时间转成时间对象:
time.strptime('2016-03-03 10:06:23', '%Y-%m-%d %H:%M:%S')
输出结果为时间对象:time.struct_time(tm_year=2016, tm_mon=3, tm_mday=3, tm_hour=10, tm_min=6, tm_sec=23, tm_wday=3, tm_yday=63, tm_isdst=-1)
读写CSV文件
先来写个csv文件:
import csv
with open('data.csv', 'wb') as f:
w = csv.writer(f, dialect='excel')
w.writerow(['a', 1, 2, 3, 4])
w.writerow(['b', '1', '2', '3', '4'])
我们以写入二进制文件('wb')的方式打开data.csv文件,并写入了两行数据。有趣的是数字和字符数字都会被csv模块理解为数字型。当然,我们也可以一次性写入多行数据的:
data = [['a', 'a', 'a'],['b', 'b', 'b']]
w.writerows(data)
再来读试试:
import csv
with open('data.csv', 'rb') as f:
r = csv.reader(f)
for row in r:
print(row)
使用默认浏览器打开一个网址
import webbrowser
webbrowser.open('http://time99.net')
获取本机MAC地址
import uuid
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
print(":".join([mac[e:e+2] for e in range(0,11,2)]))
使用数据库
python3常用pymysql模块来连接mysql系数据库,通过pip install pymysql很方便地安装。
import pymysql
#连接数据库
db = pymysql.connect('127.0.0.1', 'root', '****', 'demo')
#获取游标
cursor = db.cursor(pymysql.cursors.pymysql.cursors.DictCursor)
#执行sql语句
cursor.execute("select version()")
#获取操作结果
result = cursor.fetchone()
#关闭数据库连接
db.close()
print("数据库版本:%s" % result)
处理JSON
import json
#字符串转json对象(array, dict)
objStr = '{"name":"test", "age":18}'
obj = json.loads(objStr)
#josn对象(array, dict)转字符串
dicts = {"name":"test", "age":18}
strs = json.dumps(dicts)