实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接传递,所以需要将其转换成字符串形式.转换的过程也是一种序列化过程.
用json.dumps序列化为json字符串格式
>>> import json
//dict
>>> sdict = {'a': ['11'], 'b': ['22'], 'c': 'great'}
//序列化
>>> jdict = json.dumps(sdict)
>>> print jdict
'{"a": ["11"], "c": "great", "b": ["22"]}'//字符串类型
//格式化打印
>>> print json.dumps(sdict,sort_keys=True,indent=3)
{
"a": [
"11"
],
"b": [
"22"
],
"c": "great"
}
//用json.dump序列化到文件对象中
>>> json.dump({'4': 5, '6': 7}, open('savejson.txt', 'w'))
>>> print open('savejson.txt').readlines()
['{"4": 5, "6": 7}']
//反序列化成python对象
json.loads(jdict)
{u'a': [u'11'], u'c': u'great', u'b': [u'22']} // dict
>>> fobj = json.load(open('savejson.txt'))
>>> print fobj
{u'4': 5, u'6': 7}
2.cmd
3.导入module
4.命令行自动提示
vim ~/.pythonstartup
import readline,rlcompleter
### Indenting
class TabCompleter(rlcompleter.Completer):
"""Completer that supports indenting"""
def complete(self, text, state):
if not text:
return (' ', None)[state]
else:
return rlcompleter.Completer.complete(self, text, state)
readline.set_completer(TabCompleter().complete)
### Add autocompletion
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind -e")
readline.parse_and_bind("bind '\t' rl_complete")
else:
readline.parse_and_bind("tab: complete")
### Add history
import os
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
del histfile
export PYTHONSTARTUP=”/home/xxx/.pythonstartup”
注意:histfile是.pyhist
5.命令行
查看模块信息
import os
help(os)
Help on module os:
NAME
os - OS routines for NT or Posix depending on what system we're on.
FILE /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py
MODULE DOCS
http://docs.python.org/library/os
DESCRIPTION
CLASSES
//也可以查看更详细信息
dir(os)
help(os.path)
6.类
•无绑定类方法对象:无self
•绑定实例方法对象:有self
>>> class MyClass:
... def foo(self,text):
... print text
...
>>> a = MyClass() #创建类实例
#调用实例方法, foo默认和a绑定,再调用时,默认会传self
>>> a.foo('qiwsir.github.io')
>>> a.foo
0xb74495ac>>
#未绑定实例
>>> a = MyClass()
>>> y = MyClass.foo #这里没有用类调用
>>> y
>>> y(a,"qiwsir.github.io")
qiwsir.github.io
7.命令行参数
getopt.getopt(args, options[, long_options])
getopt函数的第三个参数[, long_options]为可选的长选项参数,上面例子中的都为短选项(如-i -o)
长选项格式举例:
- -version
- -file=error.txt
让一个脚本同时支持短选项和长选项
a,b = getopt.getopt(sys.argv[1:],'a:b:',["ver","hel="])
print a,b
python 1.py -a 1 -b 2 --ver --hel=3333 a b c
[('-a', '1'), ('-b', '2'), ('--ver', ''), ('--hel', '3333')] ['a', 'b', 'c']
8.异常
try:
raise Exception("a", "b")
except Exception,e:
print e
9.dict
dict和json的区别?谁可以没有引号?
10.python 有switch么?
python没有switch,可以通过dict转移实现.
#coding: utf-8
from __future__ import division
def jia(x,y):
print x+y
def jian(x,y):
print x-y
operator = {'+':jia,'-':jian}
def f(x,o,y):
operator.get(o)(x,y)
f(3,'+',2)
11.ConfigParser
Python的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser SafeConfigParser。
RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。
# -* - coding: UTF-8 -* -
import ConfigParser
#生成config对象
conf = ConfigParser.ConfigParser()
#用config对象读取配置文件
**返回的是成功读取的文件**
conf.read("test.cfg")
#以列表形式返回所有的section
sections = conf.sections()
print 'sections:', sections #sections: ['sec_b', 'sec_a']
#得到指定section的所有option
options = conf.options("sec_a")
print 'options:', options #options: ['a_key1', 'a_key2']
#得到指定section的所有键值对
kvs = conf.items("sec_a")
print 'sec_a:', kvs #sec_a: [('a_key1', '20'), ('a_key2', '10')]
#指定section,option读取值
str_val = conf.get("sec_a", "a_key1")
int_val = conf.getint("sec_a", "a_key2")
print "value for sec_a's a_key1:", str_val #value for sec_a's a_key1: 20
print "value for sec_a's a_key2:", int_val #value for sec_a's a_key2: 10
#写配置文件
#更新指定section,option的值
conf.set("sec_b", "b_key3", "new-$r")
#写入指定section增加新option和值
conf.set("sec_b", "b_newkey", "new-value")
#增加新的section
conf.add_section('a_new_section')
conf.set('a_new_section', 'new_key', 'new_value')
#写回配置文件
conf.write(open("test.cfg", "w"))
#变量替换
[portal]
url = http://%(host)s:%(port)s/Portal
host = localhost
port = 8080
12.常用函数:
dict
判断是否存在 dict.has_key()
返回keys:dict.keys(),dict.values(),dict.items()
13.thread
target=worker work不要有引号
#!/usr/bin/python
#current's number of threads
import threading
import time
def worker():
print "test"
time.sleep(1)
for i in xrange(5):
t = threading.Thread(target=worker)
t.start()
print "current has %d threads" % (threading.activeCount() - 1)
14.os.walk
(root,dir,files) = os.walk(path)
获取文件全路径 os.join(root/files)
>>> for i in os.walk("/tmp"):
... print i
...
('/tmp', ['com.apple.launchd.5SdprsnZAe', 'com.apple.launchd.PgImBhdXtD', 'cvcd', 'KSOutOfProcessFetcher.0.HVXI9pQwBk_bgiVJaTNhiQNhqxc='], ['.keystone_install_lock', 'ct.shutdown', 'safeq-zhangshunwen', 'scep.gui.501.fifo', 'scep.sock', 'scepx.sock'])
('/tmp/com.apple.launchd.5SdprsnZAe', [], ['Listeners'])
('/tmp/com.apple.launchd.PgImBhdXtD', [], ['Render'])
>>> for i in os.walk("/tmp/com.apple.launchd.5SdprsnZAe"):
a=”a/b/c/d/e” -> ‘c/d/e’
a[a.find(‘c’):]
with tarfile.open(tpath,'w:bz2') as tar:
for troot,tdir,tfiles in os.walk(fpath):
for tfile in tfiles:
tfullpath = os.path.join(troot,tfile)
tarpath = tfullpath.replace(fpath, '')
print tfullpath," ",tarpath
tar.add(tfullpath,arcname=tarpath)
with tarfile.open(tpath,'r:bz2') as tar:
for name in tar.getnames():
print name
easy_install redis
import redis
r = redis.Redis(host="localhost",port=6379,db=0)
r.get('a')
help("modules")
help ("modules http") //查看 http 相关的 module
19.http请求
urllib2
//最简单的页面访问
res=urllib2.urlopen(url)
print res.read()
//加上要get或post的数据
data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))
//加上http头
header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)
requests:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
Python的函数定义中有两种特殊的情况,即出现,*的形式。
如:
def myfun1(username, *keys)
def myfun2(username, **keys)等。
解释:
* 用来传递任意个无名字参数,这些参数会一个Tuple的形式访问。
** 用来处理传递任意个有名字的参数,这些参数用dict来访问。