欢迎来到 booking¶
项目简介¶
作者: peng shiyu
介绍: 一些平时学习的笔记
邮箱:pengshiyuyx@gmai.com
github地址: https://github.com/mouday/mybook
目录¶
Python Standard Library笔记¶
1. 内建函数和异常¶
__builtin__
包含Python 中使用的内建函数- exceptions 模块提供了标准异常的层次结构
Python 在启动时导入这两个模块, 使任何程序都能够使用它们
- type descriptor (类型描述符)
- 字典是无序的, 而列表和元组是有序的
- 所有的类都属于一个特殊的类类型(special class type)
- 所有的类实例属于一个特殊的实例类型(special instance type)
- 不能使用type 函数来测试一个实例是否属于一个给定的类, 所有的实例都是同样的类型
python中的异常体系
Exception
SystemExit(Exception)
StandardError(Exception)
KeyboardInterrupt(StandardError)
ImportError(StandardError)
NameError(StandardError)
UnboundLocalError(NameError)
AttributeError(StandardError)
SyntaxError(StandardError)
IndentationError(SyntaxError)
TabError(IndentationError)
TypeError(StandardError)
AssertionError(StandardError)
LookupError(StandardError)
IndexError(LookupError)
KeyError(LookupError)
ArithmeticError(StandardError)
OverflowError(ArithmeticError)
ZeroDivisionError(ArithmeticError)
FloatingPointError(ArithmeticError)
ValueError(StandardError)
UnicodeError(ValueError)
RuntimeError(StandardError)
NotImplementedError(RuntimeError)
SystemError(StandardError)
MemoryError(StandardError)
EnvironmentError
IOError(EnvironmentError)
OSError(EnvironmentError)
WindowsError(OSError)
2. 操作系统接口模块¶
- os 模块 提供文件和进程处理功能的
- os.path 模块 提供平台独立的文件名处理(分拆目录名, 文件名, 后缀等)
- time/datetime 模块 时间日期处理相关的
3. 类型支持模块¶
- string 模块 实现了常用的字符串处理
- math 模块 提供了数学计算操作和常量(pi, e都属于这类常量)
- cmath 模块 为复数提供了和math 一样的功能
4. 正则表达式¶
re 模块 正则表达式用于匹配字符串
5. 语言支持模块¶
- sys 模块可以让你访问解释器相关参数,比如模块搜索路径,解释器版本号等.
- operator 模块提供了和内建操作符作用相同的函数.
- copy 模块允许你复制对象,
- gc 模块提供了对垃圾收集的相关控制功能.
example¶
builtin-apply-example.py¶
# encoding=utf-8
# 使用apply 函数
def func(a, b):
print(a, b)
if __name__ == '__main__':
apply(func, ("name", "age"))
# py2: ('name', 'age')
# py3: NameError: name 'apply' is not defined
# 使用apply 函数传递关键字参数
apply(func, ("name",), {"b": "age"})
# ('name', 'age')
apply(func, (), {"a": "name", "b": "age"})
# ('name', 'age')
builtin-callable-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-callable-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# callable 函数, 检查一个对象是否可调用
# 对于函数, 方法, lambda 函式, 类, 实现了 __call__方法的类实例, 它都返回True.
def is_callable(function):
if callable(function):
print(function, "is callable")
else:
print(function, "is not callable")
class A(object):
def method(self, value):
return value
class B(A):
def __call__(self, value):
return value
a = A()
b = B()
is_callable(0)
is_callable("string")
is_callable(a)
is_callable(b)
is_callable(A)
is_callable(B)
is_callable(a.method)
"""
(0, 'is not callable')
('string', 'is not callable')
(<__main__.A object at 0x105e07190>, 'is not callable')
(<__main__.B object at 0x105e07390>, 'is callable')
(<class '__main__.A'>, 'is callable')
(<class '__main__.B'>, 'is callable')
(<bound method A.method of <__main__.A object at 0x105e07190>>, 'is callable')
"""
builtin-compile-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-compile-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# eval 函数只针对简单的表达式.
# 如果要处理大块的代码, 你应该使用compile和exec 函数
name = "script.py"
script = "name = 'Tom'; age = 23; print(name, age)"
# 编译脚本, 返回一个代码对象
code = compile(script, name, "exec")
# 执行脚本 py2
# exec code
# ('Tom', 23)
import string
class CodeGeneratorBackend(object):
"""
在程序执行时实时地生成代码.
write 方法用于添加代码,
indent 和dedent 方法用于控制缩进结构.
其他部分交给类来处理.
"""
def begin(self, tab="\t"):
self.code = []
self.tab = tab
self.level = 0
def end(self):
self.code.append("") # 确保最后一行是空行
return compile(string.join(self.code, "\n"), "<code>", "exec")
def write(self, code):
self.code.append(self.tab * self.level + code)
def indent(self):
self.level += 1
def dedent(self):
if self.level == 0:
raise SyntaxError("缩进小于0")
else:
self.level -= 1
c = CodeGeneratorBackend()
c.begin()
c.write("for i in range(3):")
c.indent()
c.write("print('i = ', i)")
c.dedent()
# exec c.end()
"""
('i = ', 0)
('i = ', 1)
('i = ', 2)
"""
# execfile 函数, 一个从文件加载代码, 编译代码, 执行代码的快捷方式
# execfile("hello.py")
# hello world!
builtin-dir-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-dir-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# dir返回成员列表
import sys
def dump(value):
print(value, "=>", dir(value))
dump(0)
dump(1.0)
dump(1.0j) # complex
dump({}) # dictionary
dump([]) # list
dump("string")
dump(len) # function
dump(sys) # module
"""
(0, '=>', ['__abs__', '__add__', '__and__', '__class__', '__cmp__',
'__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__',
'__float__', '__floordiv__', '__format__', '__getattribute__',
'__getnewargs__', '__hash__', '__hex__', '__index__', '__init__',
'__int__', '__invert__', '__long__', '__lshift__', '__mod__',
'__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__',
'__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__',
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__',
'__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__',
'__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'])
(1.0, '=>', ['__abs__', '__add__', '__class__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__eq__',
'__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__',
'__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__',
'__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__',
'__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__',
'__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__',
'__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio',
'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real'])
(1j, '=>', ['__abs__', '__add__', '__class__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__',
'__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__',
'__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__',
'__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__',
'__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__',
'__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__',
'__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__truediv__', 'conjugate', 'imag', 'real'])
({}, '=>', ['__class__', '__cmp__', '__contains__', '__delattr__',
'__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key',
'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem',
'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'])
([], '=>', ['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__delslice__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'])
('string', '=>', ['__add__', '__class__', '__contains__', '__delattr__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split',
'_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'])
(<built-in function len>, '=>', ['__call__', '__class__', '__cmp__',
'__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__'])
(<module 'sys' (built-in)>, '=>', ['__displayhook__', '__doc__',
'__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__',
'__stdout__', '_clear_type_cache', '_current_frames', '_getframe',
'_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode',
'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable',
'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval',
'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding',
'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof',
'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize',
'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cache', 'platform', 'prefix', 'py3kwarning',
'real_prefix', 'setcheckinterval', 'setdlopenflags', 'setprofile',
'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion',
'version', 'version_info', 'warnoptions'])
Process finished with exit code 0
"""
# 使用dir 函数查找类的所有成员
class A(object):
def a(self):
pass
def b(self):
pass
class B(A):
def c(self):
pass
def d(self):
pass
def get_members(klass, members=None):
if members is None:
members = []
# 基类中查找成员
for k in klass.__bases__:
get_members(k, members)
# 本类中查找成员
for m in dir(klass):
if m not in members:
members.append(m)
return members
print(get_members(B))
# 成员在列表中名称出现的越早, 它所处的类层次就越高
"""
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__dict__',
'__module__', '__weakref__', 'a', 'b', 'c', 'd']
"""
print(B.__bases__)
# (<class '__main__.A'>,)
builtin-eval-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-eval-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# eval 函数将一个字符串作为Python 表达式求值
print(eval("1+1")) # 2
print(eval("__import__('os').getcwd()"))
# /example
# Python 在求值前会检查这个字典, 如果没有发现名称为builtins 的变量(复数形式), 它就会添加一个
namespace = {}
print(eval("__import__('os').getcwd()", namespace))
print(namespace.keys()) # ['__builtins__']
# 如果这个变量存在, Python 就不会去添加默认的
namespace = {"__builtins__": {}}
print(eval("__import__('os').getcwd()", namespace))
# NameError: name '__import__' is not defined
builtin-import-example.py¶
# encoding=utf-8
# 加载模块
# os = __import__("os")
# 推荐使用
import importlib
os = importlib.import_module("os")
print(os.path.abspath(__file__))
# 获得特定函数
def get_func(module_name, function_name):
module = __import__(module_name)
return getattr(module, function_name)
# Python 的辨识符不允许有”-”
f = get_func("builtin-apply-example", "func")
f("aaa", "bbb")
# ('aaa', 'bbb')
# 函数实现延迟导入 lazy module loading
class LazyImport(object):
def __init__(self, module_name):
self.module_name = module_name
self.module = None
def __getattr__(self, name):
if self.module is None:
self.module = __import__(self.module_name)
return getattr(self.module, name)
# string 模块只在第一次使用的时候导入
string = LazyImport("string")
print(string.lowercase)
# abcdefghijklmnopqrstuvwxyz
builtin-isinstance-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-isinstance-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# 用isinstance 函数,检查一个对象是不是给定类(或其子类)的实例
class A(object):
pass
class B(A):
pass
a = A()
b = B()
# 判断类型
print(type(A))
print(type(B))
print(type(a))
print(type(b))
"""
<type 'type'>
<type 'type'>
<class '__main__.A'>
<class '__main__.A'>
"""
# 判断实例
print(isinstance(a, A))
print(isinstance(b, A))
print(isinstance(b, B))
print(isinstance(A, type))
"""
True
True
True
True
"""
# issubclass 函数 检查一个类对象是否与给定类相同,或者是给定类的子类
print(issubclass(A, A))
print(issubclass(A, B))
print(issubclass(B, A))
"""
True
False
True
"""
builtin-open-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-open-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# 从 builtin 模块重载函数
def open(filename):
return filename
filename = "source/file.txt"
f = open(filename)
print(type(f)) # <type 'str'>
f = __builtins__.open(filename, "r")
print(type(f)) # <type 'file'>
builtin-reload-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-reload-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# reload重新加载已加载模块
import __hello__
reload(__hello__)
reload(__hello__)
# Hello world...
# Hello world...
# Hello world...
builtin-type-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-type-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# type 函数检查一个变量的类型
import os
def func(value):
print(value, type(value))
func(1)
func(1.0)
func("name")
"""
(1, <type 'int'>)
(1.0, <type 'float'>)
('name', <type 'str'>)
"""
def load(file_):
if isinstance(file_, type("")):
file_ = open(file_, "r")
return file_.read()
filename = "example/source/file.txt"
print(load(filename)) # 传入文件路径
print(load(open(filename, "r"))) # 传入文件对象
builtin-vars-example.py¶
# -*- coding: utf-8 -*-
# @File : builtin-vars-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# vars 返回包含每个成员当前值的字典
from pprint import pprint
name = "哈利波特"
age = 24
pprint(vars())
"""
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '/example/builtin-vars-example.py',
'__name__': '__main__',
'__package__': None,
'age': 24,
'name': '\xe5\x93\x88\xe5\x88\xa9\xe6\xb3\xa2\xe7\x89\xb9',
'pprint': <function pprint at 0x104580aa0>}
"""
print("%(name)s yeas old is %(age)s" % vars())
# 哈利波特 yeas old is 24
# locals 返回当前局部名称空间的可见元素
pprint(locals())
"""
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '/example/builtin-vars-example.py',
'__name__': '__main__',
'__package__': None,
'age': 24,
'name': '\xe5\x93\x88\xe5\x88\xa9\xe6\xb3\xa2\xe7\x89\xb9',
'pprint': <function pprint at 0x10a84baa0>}
"""
"""
总结:
vars()
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
locals()
Update and return a dictionary containing the current scope's local variables.
"""
pprint(globals())
"""
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '/example/builtin-vars-example.py',
'__name__': '__main__',
'__package__': None,
'age': 24,
'name': '\xe5\x93\x88\xe5\x88\xa9\xe6\xb3\xa2\xe7\x89\xb9',
'pprint': <function pprint at 0x1065d5b18>}
"""
# 获取实例对象的属性
class A(object):
def __init__(self):
self.a = 1
self.b = 2
def keys(self):
for key in vars(self).keys():
yield key
def get_keys(self):
for key in self.__dict__:
yield key
a = A()
for key in a.keys():
print(key)
for key in a.get_keys():
print(key)
copy-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-11-01
# @Author : Peng Shiyu
import copy
# 浅拷贝shallow copy 复制对象本身,
# 容器container 对象的成员仍然指向原来成员对象
def shallow_copy():
lst = [[0], [1], [2]]
lst1 = copy.copy(lst)
lst2 = lst[:]
lst1[0].append(None)
print(lst)
print(lst1)
print(lst2)
"""
[[0, None], [1], [2]]
[[0, None], [1], [2]]
[[0, None], [1], [2]]
"""
# 深拷贝deep copy
# 容器container 对象的所有成员被递归复制
def deep_copy():
lst = [[0], [1], [2]]
lst1 = copy.deepcopy(lst)
lst1[0].append(None)
print(lst)
print(lst1)
"""
[[0], [1], [2]]
[[0, None], [1], [2]]
"""
exceptions-example.py¶
# -*- coding: utf-8 -*-
# @File : exceptions-example.py
# @Date : 2018-09-21
# @Author : Peng Shiyu
# 自定义异常
class MyException(Exception):
def __init__(self, url, errcode, errmsg):
self.url = url
self.errcode = errcode
self.errmsg = errmsg
def __str__(self):
return "<HTTPError for %s: %s %s>" % (
self.url, self.errcode, self.errmsg
)
if __name__ == '__main__':
try:
raise MyException("www.baidu.com", 404, "not found")
except MyException as e:
print(e.url)
print(e.errcode)
print(e.errmsg)
raise # 重新抛出异常
hello.py¶
print("hello world!")
math-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-11-01
# @Author : Peng Shiyu
# math 模块提供浮点数数学运算
import math
print(math.pi)
print(math.e)
"""
3.141592653589793
2.718281828459045
"""
# cmath 提供复数计算
import cmath
print(cmath.pi)
# 3.141592653589793
print(cmath.sqrt(-1))
# 1j
print(2 + 3j + 2 + 2j)
# (4+5j)
operator-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-11-01
# @Author : Peng Shiyu
# operator 提供标准操作符接口,替换lambda
import operator
from functools import reduce
lst = [1, 2, 3, 4, -5]
# 计算
print(reduce(operator.add, lst))
# 5
print(list(map(operator.abs, lst)))
# [1, 2, 3, 4, 5]
os-example.py¶
# -*- coding: utf-8 -*-
# @File : os-example.py
# @Date : 2018-09-21
# @Author : Peng Shiyu
import string
import os
import shutil
# 使用os 模块重命名和删除文件
def replace(filename, search_word, replace_word):
"""
对文件中的词进行替换
:param filename: {str} 文件路径
:param search_word: {str} 需要替换的词
:param replace_word: {str} 替换之后的词
:return: None
"""
temp_file = os.path.splitext(filename)[0] + ".tmp"
back_file = os.path.splitext(filename)[0] + ".bak"
# 移除temp文件
try:
os.remove(temp_file)
except os.error:
pass
# 逐行替换的新内容写入temp文件
f = open(filename, "r")
ft = open(temp_file, "w")
for line in f.readlines():
ft.write(string.replace(line, search_word, replace_word))
ft.close()
f.close()
# 移除bak文件
try:
os.remove(back_file)
except os.error:
pass
# 对源文件备份,temp文件改名
os.rename(filename, back_file)
os.rename(temp_file, filename)
# 使用os 列出目录下的文件
def print_files():
for f in os.listdir("."):
print(f)
# 使用os 模块改变当前工作目录
def change_dir():
print(os.getcwd()) # 获得当前工作目录
os.chdir("..") # 改变当前工作目录
print(os.getcwd())
# 使用os 模块创建/删除多个目录级
def make_dirs():
filename = "temp/upload"
os.makedirs(filename)
# OSError: [Errno 17] File exists: 'temp/upload'
with open(os.path.join(filename, "temp.txt"), "w") as f:
f.write("ooxx")
os.removedirs(filename)
# OSError: [Errno 66] Directory not empty: 'temp/upload'
# 使用os 模块创建/删除目录
def make_dir():
filename = "temp"
os.mkdir(filename)
os.rmdir(filename)
# shutil 模块中的rmtree 函数 删除非空目录
def remove_tree():
shutil.rmtree("source")
if __name__ == '__main__':
old = "十"
new = "10"
filename = "source/file.txt"
# replace(filename, old, new)
remove_tree()
os-exit-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-10-22
# @Author : Peng Shiyu
# 使用os 模块终止当前进程
import sys
print("开始。。。")
sys.exit()
print("结束。。。") # 这个语句不会被执行
os-file-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-09-30
# @Author : Peng Shiyu
# 使用os 模块获取文件属性
# stat 函数可以用来获取一个存在文件的信息
import os
# 获取一个文件的状态
print(os.stat("source/poem.txt"))
"""
os.stat_result(st_mode=33188, st_ino=34523939,
st_dev=16777220, st_nlink=1, st_uid=501, st_gid=80,
st_size=152, st_atime=1538296119, st_mtime=1538296028,
st_ctime=1538296028)
"""
# 获取一个打开文件的状态
f = open("source/poem.txt", "r")
print(os.fstat(f.fileno()))
"""
os.stat_result(st_mode=33188, st_ino=34523939,
st_dev=16777220, st_nlink=1, st_uid=501, st_gid=80,
st_size=152, st_atime=1538296119, st_mtime=1538296028,
st_ctime=1538296028)
"""
"""
st_mode (权限模式)
st_ino (inode number)
st_dev (device)
st_nlink (number of hard links)
st_uid (所有者用户ID)
st_gid (所有者所在组ID )
st_size (文件大小, 字节)
st_atime (最近一次访问时间)
st_mtime (最近修改时间)
st_ctime (平台相关,Unix 修改时间, Windows 创建时间)
"""
# 使用os 模块修改文件的权限和时间戳
import os
import stat
from datetime import datetime
def copy_file(source, target):
fs = open(source, "rb")
ft = open(target, "wb")
while True:
chunk = fs.read(512)
if not chunk:
break
ft.write(chunk)
ft.close()
fs.close()
def show_stat(filename):
st = os.stat(filename)
at = datetime.fromtimestamp(st.st_atime)
mt = datetime.fromtimestamp(st.st_mtime)
print("访问时间: %s 修改时间: %s" % (at, mt))
def copy_time(source, target):
stat_s = os.stat(source)
os.chmod(target, stat.S_IMODE(stat_s.st_mode))
os.utime(target, (stat_s[stat.ST_ATIME], stat_s[stat.ST_MTIME]))
if __name__ == '__main__':
source = "source/poem.txt"
target = "source/poem.bak"
copy_file(source, target)
print("文件创建")
show_stat(source)
show_stat(target)
copy_time(source, target)
print("时间复制")
show_stat(source)
show_stat(target)
os-path-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-10-22
# @Author : Peng Shiyu
# os.path 模块包含与平台无关的处理长文件名的函数.
# 也就是说, 你 不需要处理前后斜杠, 冒号等
# 使用os.path 模块处理文件名
import os
filename = "base/file/file.ext"
print(os.path.split(filename))
print(os.path.splitext(filename))
print(os.path.dirname(filename))
print(os.path.basename(filename))
print(os.path.join(os.path.dirname(filename), os.path.basename(filename)))
"""
('base/file', 'file.ext')
('base/file/file', '.ext')
base/file
file.ext
base/file/file.ext
"""
# 使用os.path 模块检查文件名的特征
print(os.path.exists(filename))
print(os.path.isdir(filename))
print(os.path.isfile(filename))
print(os.path.isabs(filename))
print(os.path.islink(filename))
print(os.path.ismount(filename)) # 挂载点
"""
False
False
False
False
False
False
"""
# 使用os.path 模块将用户名插入到文件名
print(os.path.expanduser("~/.pythonrc"))
# /Users/qmp/.pythonrc
# 使用os.path 替换文件名中的环境变量
os.environ["USER"] = "user"
print(os.path.expandvars("/$USER"))
os-path-walk-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-10-22
# @Author : Peng Shiyu
# 使用os.path 搜索文件系统
import os
def get_files(top="."):
"""
获取路径下所有文件
"""
for root, dirs, files in os.walk(top):
for filename in files:
yield os.path.join(root, filename)
def get_dirs(top="."):
"""
获取路径下所有文件夹
"""
for root, dirs, files in os.walk(top):
for directory in dirs:
yield os.path.join(root, directory)
# 使用os.listdir 搜索文件系统
def get_files_(directory="."):
stack = []
stack.append(directory)
while stack:
current = stack.pop()
for filename in os.listdir(current):
fullname = os.path.join(current, filename)
if os.path.isdir(fullname) and not os.path.islink(fullname):
stack.append(fullname)
else:
yield fullname
# 使用DirectoryWalker 搜索文件系统
class DirectoryWalker():
def __init__(self, directory):
self.stack = [directory]
self.index = 0
self.files = []
def __getitem__(self, index):
while True:
try:
filename = self.files[self.index]
self.index += 1
except IndexError:
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
fullname = os.path.join(self.directory, filename)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
return filename
if __name__ == '__main__':
for filename in DirectoryWalker("."):
print(filename)
os-shell-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-09-30
# @Author : Peng Shiyu
# 使用os 执行操作系统命令
# system 函数在当前进程下执行一个新命令, 并等待它完成
import os
if os.name == "nt":
command = "dir"
else:
command = "ls -l"
# os.system(command)
# 使用os 模块启动新进程
"""
execl
execle
execlp
execlpe
execvp
execvpe
l 接受多个独立的参数(参数列表,类命令行输入)
v 接受一个list或tuple的参数
p 使用PATH环境变量
e 指定的dict环境变量
"""
# os.execvp("python", ("hello.py",))
# 当前进程不会结束
# 使用os 模块调用其他程序(Unix)
# fork 函数复制当前进程, 子进程返回中返回0 在进程中返回子进程的PID
# wait 函数会等待一个子进程执行结束
pid = os.fork()
print(pid)
print("balabala...")
# Windows 上使用spawn函数
os-stat-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-10-22
# @Author : Peng Shiyu
# stat 模块包含了一些os.stat 函数中可用的常量和测试函数.
import os
import stat
from datetime import datetime
filename = "hello.py"
st = os.stat(filename)
print(st)
# 模式
print(oct(st.st_mode))
print(oct(stat.S_IMODE(st.st_mode)))
print(oct(stat.S_IMODE(st[stat.ST_MODE])))
print(stat.S_ISDIR(st.st_mode))
print(stat.S_ISLNK(st.st_mode))
# 大小
print(st.st_size)
# 时间
print(datetime.fromtimestamp(st.st_ctime))
print(datetime.fromtimestamp(st.st_atime))
print(datetime.fromtimestamp(st.st_mtime))
re-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-10-30
# @Author : Peng Shiyu
# re 模块正则表达式处理字符串
# re 默认会保存编译后的匹配模式
import re
# match 匹配
def match_func():
text = "2018/11/1"
ret = re.match("(\d{4})/(\d{1,2})/(\d{1,2})", text)
# group 抽取匹配的字符串
if ret is not None:
print(ret.group())
print(ret.group(0, 1, 2, 3))
print(ret.groups())
year, month, day = ret.groups()
print(year)
print(month)
print(day)
"""
2018/11/1
('2018/11/1', '2018', '11', '1')
('2018', '11', '1')
2018
11
1
"""
# search 搜索
def search_func():
text = "the day is 2018/11/1"
ret = re.search("(\d{4})/(\d{1,2})/(\d{1,2})", text)
if ret:
year, month, day = ret.groups()
print(year)
print(month)
print(day)
"""
2018
11
1
"""
# sub 替换
def sub_func():
text = "day day up"
print(text.replace("up", "good")) # 更快
ret = re.sub("[au]", "=", text)
print(ret)
# findall 查找所有
def findall_func():
text = "2018, 2009, 20, 2005"
ret = re.findall("\d{4}", text)
print(ret) # <class 'list'>
# ['2018', '2009', '2005']
string-example.py¶
# -*- coding: utf-8 -*-
# @Date : 2018-10-22
# @Author : Peng Shiyu
# string 模块提供了一些用于处理字符串类型的函数
# 字符串方法
import string
from functools import partial
text = "Monty Python’s Flying Circus"
print("upper", "=>", text.upper())
print("lower", "=>", text.lower())
print("split", "=>", text.split())
print("join", "=>","+".join(text.split()))
print("replace", "=>", text.replace("Python","Perl"))
print("find", "=>", text.find("Python"), text.find("Perl"))
print("count", "=>", text.count("n"))
"""
upper => MONTY PYTHON’S FLYING CIRCUS
lower => monty python’s flying circus
split => ['Monty', 'Python’s', 'Flying', 'Circus']
join => Monty+Python’s+Flying+Circus
replace => Monty Perl’s Flying Circus
find => 6 -1
count => 3
"""
# 字符串转为数字
print(int("12")) # 字符串转数字
print(int("0x12", base=16)) # 16进制转10进制
print(int("012", base=8)) # 8进制转10进制
print(int("110", base=2)) # 2进制转10进制
"""
12
18
10
6
"""
# 使用偏函数
bin_to_int = partial(int, base=2)
print(bin_to_int("110"))
print(bin(12)) # 10进制转2进制(str)
print(oct(12)) # 10进制转8进制(str)
print(hex(12)) # 10进制转16进制(str)
"""
0b1100
0o14
0xc
"""
python sheet¶
Python sys Variables¶
变量 | 说明 |
---|---|
argv | Command line args |
builtin_module_names | Linked C modules |
byteorder | Native byte order |
exec_prefix | Root directory |
executable | Name of executable |
modules | Loaded modules |
path | Search path |
platform | Current platform |
stdin, stdout, stderr | File objects for I/O |
version_info | Python version info |
version | Version number |
Python sys.argv¶
sys.argv for the command:
$ python foo.py bar -c qux –h
变量 | 说明 |
---|---|
sys.argv[0] | foo.py |
sys.argv[1] | bar |
sys.argv[2] | -c |
sys.argv[3] | qux |
sys.argv[4] | --h |
Python os Variables¶
方法 | 说明 |
---|---|
altsep | Alternative sep |
curdir | Current dir string |
defpath | Default search path |
devnull | Path of null device |
extsep | Extension separator |
linesep | Line separator |
name | Name of OS |
pardir | Parent dir string |
pathsep | Patch separator |
sep | Path separator |
Registered OS names: “posix”, “nt”, “mac”, “os2”, “ce”, “java”, “riscos”
Python Class Special Methods¶
方法 | 说明 |
---|---|
__new__(cls) | |
init(self, args) | |
__del__(self) | |
__str__(self) | |
repr(self) | |
lt(self, other) | |
le(self, other) | |
gt(self, other) | |
ge(self, other) | |
eq(self, other) | |
ne(self, other) | |
__cmp__(self, other) | |
index(self) | |
nonzero(self) | |
hash(self) | |
getattr(self, name) | |
__getattribute__(self, name) | |
setattr(self, name, attr) | |
delattr(self, name) | |
call(self, args, kwargs) |
Python List Methods¶
方法 | 说明 |
---|---|
append(item) | |
pop(position) | |
count(item) | |
remove(item) | |
extend(list) | |
reverse() | |
index(item) | |
sort() | |
insert(position, item) |
Python String Methods¶
方法 | 说明 |
---|---|
decode() | |
encode() | |
count(sub, start, end) | |
index(sub, start, end) | |
rindex(sub, start, end) | |
find(sub, start, end) | |
rfind(sub, start ,end) | |
startswith(sub) | |
endswith(sub) | |
center(width) | |
rjust(width) | |
ljust(width) | |
zfill(width) | |
expandtabs() | |
strip() | |
lstrip() | |
rstrip() | |
split(sep) | |
rsplit(sep) | |
splitlines() | |
partition(sep) | |
rpartition(sep) | |
join() | |
swapcase() * | |
capitalize() * | |
title() * | |
translate(table) | |
lower() * | |
upper() * | |
replace(old, new) | |
isdigit() * | |
isalnum() * | |
isspace() * | |
istitle() * | |
islower() * | |
isupper() * | |
isalpha() * |
Methods marked * are locale dependant for 8-bit strings.
Python File Methods¶
方法 | 说明 |
---|---|
close() | |
readlines(size) | |
flush() | |
seek(offset) | |
fileno() | |
tell() | |
isatty() | |
truncate(size) | |
next() | |
write(string) | |
read(size) | |
writelines(list) | |
readline(size) |
Python Indexes and Slices¶
Indexes and Slices of a=[0,1,2,3,4,5]
操作 | 结果 |
---|---|
len(a) | 6 |
a[0] | 0 |
a[5] | 5 |
a[-1] | 5 |
a[-2] | 4 |
a[1:] | [1,2,3,4,5] |
a[:5] | [0,1,2,3,4] |
a[:-2] | [0,1,2,3] |
a[1:3] | [1,2] |
a[1:-1] | [1,2,3,4] |
b=a[:] | Shallow copy of a |
Python Datetime Methods¶
操作 | 结果 |
---|---|
today() | |
fromordinal(ordinal) | |
now(timezoneinfo) | |
combine(date, time) | |
utcnow() | |
strptime(date, format) | |
fromtimestamp(timestamp) | |
utcfromtimestamp(timestamp) |
Python Time Methods¶
操作 | 结果 |
---|---|
replace() | |
utcoffset() | |
isoformat() | |
dst() | |
str() | |
tzname() | |
strftime(format) |
Python Date Formatting¶
字符 | 说明 |
---|---|
%a | Abbreviated weekday (Sun) |
%A | Weekday (Sunday) |
%b | Abbreviated month name (Jan) |
%B | Month name (January) |
%c | Date and time |
%d | Day (leading zeros) (01 to 31) |
%H | 24 hour (leading zeros) (00 to 23) |
%I | 12 hour (leading zeros) (01 to 12) |
%j | Day of year (001 to 366) |
%m | Month (01 to 12) |
%M | Minute (00 to 59) |
%p | AM or PM |
%S | Second (00 to 61⁴) |
%U | Week number¹ (00 to 53) |
%w | Weekday² (0 to 6) |
%W | Week number³ (00 to 53) |
%x | Date |
%X | Time |
%y | Year without century (00 to 99) |
%Y | Year (2008) |
%Z | Time zone (GMT) |
%% | A literal "%" character (%) |
¹ Sunday as start of week. All days in a new year preceding the first Sunday are considered to be in week 0. ² 0 is Sunday, 6 is Saturday. ³ Monday as start of week. All days in a new year preceding the first Monday are considered to be in week 0. ⁴ This is not a mistake. Range takes account of leap and double-leap seconds.
一些学习笔记¶
print("hello")
利用Python进行数据分析¶
重要的python库¶
- numpy (numerical python) 多维数组ndarray
- pandas (panel data 面板数据, python data analysis) DataFrame 二维表结构
- matplotlib 绘制图表数据
- Ipython 交互式shell
- Scipy 科学计算
机器学习的方法¶
监督学习 supervised learning;¶
有数据和标签
非监督学习 unsupervised learning;¶
只有数据,没有标签
半监督学习 semi-supervised learning;¶
大量数据,少量标签
强化学习 reinforcement learning;¶
经验中总结提升
遗传算法 genetic algorithm.¶
适者生存,不适者淘汰
卷积神经网络¶
CNN (Convolutional Neural Network)
mongodb的简单介绍¶
官网下载:https://www.mongodb.com/download-center?jmp=nav#community
参考文档:http://www.runoob.com/mongodb/mongodb-tutorial.html
安装¶
macos安装:
brew install mongodb
创建一个数据库存储目录
sudo mkdir -p /data/db
启动数据库
sudo mongod
进入数据库
mongo
函数语法类似javascriptBSON是一种类json的一种二进制形式的存储格式,简称Binary JSON
数据库操作¶
MongoDB 创建数据库
show dbs 查看所有数据库
db 查看当前数据库
use DATABASE_NAME 不存在则创建,否则切换
db.dropDatabase() 删除当前数据库
MongoDB 创建集合
show collections 查看集合
show tables 查看集合
db.createCollection(name, options) 创建集合,MongoDB 会自动创建集合
db.COLLECTION_NAME.drop() 删除集合
文档操作¶
db.collection.insert(document) 插入文档db.collection.insertOne() 插入一条文档数据db.collection.insertMany() 插入多条文档数据db.collection.save(document) 替换文档
db.collection.update(
如: db.collection.update({“name”: “tom”}, {$set:{“name”: “Tom”}})
db.collection.remove(
db.col.remove({}) 删除所有 类似 SQL 的 truncate 命令deleteOne() 和 deleteMany()
查询语句¶
db.collection.find() 查询文档db.collection.find().pretty() 格式化
Where 语句比较:等于(=) {
AND 条件db.col.find({key1:value1, key2:value2}).pretty()
OR 条件db.col.find({$or: [{key1: value1}, {key2:value2}]}).pretty()
Limit() 方法 指定数量的数据记录db.collection.find().limit(NUMBER)
Skip() 方法 跳过指定数量的数据db.collection.find().limit(NUMBER).skip(NUMBER)
sort()方法 排序1 升序排列,-1 降序排列db.collection.find().sort({KEY:1})
其他操作¶
创建索引 background:true 的选项,让创建工作在后台执行db.collection.ensureIndex({KEY:1})
聚合db.collection.aggregate(AGGREGATE_OPERATION)
$type 操作符
MongoDB复制将数据同步在多个服务器的过程mongodb各个节点常见的搭配方式为:一主一从、一主多从
分片集群
备份(mongodump)与恢复(mongorestore)
监控 mongostat mongotop
数据库引用{ $ref : , $id : , $db : }
Redis学习¶
NoSQL概述¶
NoSQL = not only sql非关系型数据库
优势:
高并发读写 high performance
海量数据的高效率存储和访问 huge storage
高可扩展性和高可用性 high scalability high availability
NoSQL四大分类
键值对(key-value) redis
列存储 hbase
文档数据库 mongodb
图形数据库
NoSQL特点
易扩展
灵活的数据模型
大数据量,高性能
高可用
Redis安装¶
环境搭建
虚拟机 VMware 10.0.2
Linux centOS-6.5
ssh客户端 secureCRT 7.3 secureFX 7.3
Linux 下安装
下载地址:http://redis.io/download
Linx在线安装gcc,>yum install gcc-c++
filezilla将 redis压缩包 上传至linux
tar -zxvf redis压缩包名称
make编译
拷贝 redis.conf
前端启动
后端启动 修改redis.conf -> deamonize yes
启动服务:/bin/redis-server ./redis.conf
查看启动情况:ps -ef | grep -i redis
停止:redis-cli shutdown
启动客户端:./bin/redis-cli
Window 下安装
下载地址:https://github.com/MSOpenTech/redis/releases
mac 下安装
1、执行 brew install redis
2、后台服务启动 brew services start redis
重启服务:brew services restart redis
或者直接启动:redis-server /usr/local/etc/redis.conf
打开客户端 redis-cli
链接测试:
启动客户端 $ redis-cli
远程服务器 $ redis-cli -h host -p port -a password
127.0.0.1:6379> ping
PONG
简单使用
127.0.0.1:6379> set name imool
OK
127.0.0.1:6379> get name
"imool"
127.0.0.1:6379> keys *
1) "name"
2) "a"
127.0.0.1:6379> del name
(integer) 1
127.0.0.1:6379> keys *
1) "a"
数据类型¶
string(字符串)set key value ; get key
hash(哈希)hmset key field value; hget key field; hgetall key
list(列表)lpush key value; lrange key start stop
set(集合)sadd key member; smembers key
zset(sorted set:有序集合)zadd key score member; zrangebyscore key min max
更多命令请参考:https://redis.io/commands
Redis keys 命令¶
KEYS pattern 查找 key
DEL key 删除 key
DUMP key 返回 key 序列化的值
EXISTS key 检查 key 是否存在
MOVE key db 移动 key
EXPIRE key seconds 为 key 设置过期时间
PERSIST key 移除 key 的过期时间
TTL key 返回 key 的剩余生存时间(秒s)(TTL, time to live)
RANDOMKEY 随机返回一个 key
RENAME key newkey 修改 key 的名称
RENAMENX key newkey 仅当 newkey 不存在时,将 key 改名为 newkey
TYPE key 返回 key 类型
flushdb //删除当前数据库中的所有Key
flushall //删除所有数据库中的key
Redis string字符串 命令¶
SET key value 设置值
GET key 获取值
GETSET key value 获取旧值,设置新值
SETRANGE key offset value 覆写字符串值
GETRANGE key start end 返回子字符串
MSET key value [key value ...] 同时设置多个值
MGET key1 [key2..] 获取多个值
SETEX key seconds value 设置值和过期时间(秒s)
SETNX key value 不存在时设置值
MSETNX key value [key value ...] 同时设置多个值,当且仅当所有key都不存在
INCR key 增一
DECR key 减一
INCRBY key increment 加值
DECRBY key decrement 减值
INCRBYFLOAT key increment 加浮点值
STRLEN key 返回长度
APPEND key value 末尾追加
Redis hash哈希 命令¶
HSET key field value 设置字段值
HGET key field 获取字段的值
HMSET key field1 value1 [field2 value2 ] 设置多个字段的值
HMGET key field1 [field2] 获取多个字段的值
HSETNX key field value 不存在时,设置字段的值
HGETALL key 获取所有字段和值
HKEYS key 获取所有字段
HVALS key 获取所有值
HLEN key 获取字段的数量
HDEL key field1 [field2] 删除多个字段
HEXISTS key field 查看字段是否存在
HINCRBY key field increment 字段加值
HINCRBYFLOAT key field increment 字段加浮点值
Redis list列表命令
LPUSH key value1 [value2] 头部插入
RPUSH key value1 [value2] 尾部插入
LPOP key 头部弹出
RPOP key 尾部弹出
LSET key index value 设置值
LINSERT key BEFORE|AFTER pivot value 插入元素
LINDEX key index 获取元素
LRANGE key start stop 获取多个元素
LREM key count value 移除元素
LLEN key 获取长度
LTRIM key start stop 修剪,保留区间
LPUSHX key value 插入到已存在的列表头部
RPUSHX key value 插入到已存在的列表尾部
BLPOP key1 [key2 ] timeout 头部弹出,没有会阻塞
BRPOP key1 [key2 ] timeout 尾部弹出,没有会阻塞
RPOPLPUSH source destination 弹出一个值,插入到另外一个列表中并返回
BRPOPLPUSH source destination timeout 弹出一个值,插入到另外一个列表中并返回,如果没有会阻塞
Redis set集合命令¶
SADD key member1 [member2] 添加成员
SREM key member1 [member2] 移除成员
SCARD key 获取成员数
SMEMBERS key 所有成员
SISMEMBER key member 成员检查
SRANDMEMBER key [count] 随机返回
SPOP key 随机弹出
SMOVE source destination member 移动
SDIFF key1 [key2] 差集
SINTER key1 [key2] 交集
SUNION key1 [key2] 并集
SDIFFSTORE destination key1 [key2] 差集并存储
SINTERSTORE destination key1 [key2] 交集并存储
SUNIONSTORE destination key1 [key2] 并集存储
Redis sorted set有序集合命令¶
ZADD key score1 member1 [score2 member2] 添加成员
ZCARD key 获取成员数
ZSCORE key member 成员分数值
ZRANK key member 成员索引
ZREVRANK key member 成员的排名,分数值递减(从大到小)排序
ZCOUNT key min max 分数区间的成员数
ZLEXCOUNT key min max 字典区间内成员数
ZINCRBY key increment member 增加分数值
ZREM key member [member ...] 移除成员
ZREMRANGEBYLEX key min max 移除字典区间成员
ZREMRANGEBYRANK key start stop 移除排名区间成员
ZREMRANGEBYSCORE key min max 移除分数区间成员
ZRANGE key start stop [WITHSCORES] 索引区间成员
ZRANGEBYLEX key min max [LIMIT offset count] 字典区间成员
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] 分数区间成员
ZREVRANGE key start stop [WITHSCORES] 索引区间成员,分数从高到底
ZREVRANGEBYSCORE key max min [WITHSCORES] 分数区间内成员,分数从高到低排序
ZINTERSTORE destination numkeys key1 [key2...] 交集并存储
ZUNIONSTORE destination numkeys key [key ...] 并集并存储
Redis HyperLogLog 命令¶
PFADD key element [element ...] 添加元素
PFCOUNT key [key ...] 返回基数估算值
PFMERGE destkey sourcekey [sourcekey ...] 合并
Redis 发布订阅命令¶
SUBSCRIBE channel [channel ...] 订阅频道
UNSUBSCRIBE [channel [channel ...]] 退订频道
PUBLISH channel message 发送信息
PUBSUB subcommand [argument] 查看订阅与发布系统状态 channels
PSUBSCRIBE pattern [pattern ...] 订阅模式频道
PUNSUBSCRIBE [pattern] 退订模式频道
Redis 事务命令¶
阶段: 开始事务 -> 命令入队 -> 执行事务
MULTI 标记一个事务块的开始
EXEC 执行所有事务块内的命令
DISCARD 取消事务
WATCH key [key ...] 监视key ,如果改动,那么事务将被打断
UNWATCH 取消 WATCH 命令对所有 key 的监视
Redis Lua脚本命令¶
EVAL script numkeys key [key ...] arg [arg ...] 执行脚本
EVALSHA sha1 numkeys key [key ...] arg [arg ...] 执行脚本
SCRIPT EXISTS script [script ...] 是否在缓存
SCRIPT FLUSH 移除所有脚本
SCRIPT KILL 杀死运行的脚本
SCRIPT LOAD script 将脚本添加到缓存中,但并不立即执行这个脚本
Redis 服务器命令¶
CLIENT SETNAME connection-name 设置当前连接的名称
CLIENT GETNAME 获取连接的名称
CLIENT LIST 获取连接到服务器的客户端连接列表
CLIENT KILL [ip:port] [ID client-id] 关闭客户端连接
CLIENT PAUSE timeout 在指定时间内终止运行来自客户端的命令
DBSIZE 返回当前数据库的 key 的数量
FLUSHDB 删除当前数据库的所有key
FLUSHALL 删除所有数据库的所有key
COMMAND 获取 Redis 命令详情数组
COMMAND COUNT 获取 Redis 命令总数
COMMAND GETKEYS 获取给定命令的所有键
TIME 返回当前服务器时间
COMMAND INFO command-name [command-name ...] 获取指定 Redis 命令描述的数组
CONFIG SET parameter value 修改 redis 配置参数,无需重启
CONFIG GET parameter 获取指定配置参数的值
CONFIG REWRITE 对启动 Redis 服务器时所指定的 redis.conf 配置文件进行改写
CONFIG RESETSTAT 重置 INFO 命令中的某些统计数据
DEBUG OBJECT key 获取 key 的调试信息
DEBUG SEGFAULT 让 Redis 服务崩溃
INFO [section] 获取 Redis 服务器的各种信息和统计数值
LASTSAVE 返回最近一次 Redis 成功将数据保存到磁盘上的时间,以 UNIX 时间戳格式表示
MONITOR 实时打印出 Redis 服务器接收到的命令,调试用
ROLE 返回主从实例所属的角色
SHUTDOWN [NOSAVE] [SAVE] 异步保存数据到硬盘,并关闭服务器
CLUSTER SLOTS 获取集群节点的映射数组
SLAVEOF host port 将当前服务器转变为指定服务器的从属服务器(slave server)
SLOWLOG subcommand [argument] 管理 redis 的慢日志
SYNC 用于复制功能(replication)的内部命令
SAVE 同步保存数据到硬盘
BGSAVE 在后台异步保存当前数据库的数据到磁盘
BGREWRITEAOF 异步执行一个 AOF(AppendOnly File) 文件重写操作
Redis 数据备份与恢复¶
数据备份
SAVE
BGSAVE
恢复数据
CONFIG GET dir 获取 redis 目录
将备份文件 (dump.rdb) 移动到 redis 安装目录并启动服务即可
如果不能恢复需要先将 dump.rdb 文件拷贝到其他地方,再拷贝回备份目录
Redis 安全¶
CONFIG get requirepass 查看是否设置密码
CONFIG set requirepass password 设置密码
AUTH password 验证
Redis 性能测试¶
redis-benchmark [option] [option value] 性能测试
Redis 客户端连接¶
config get maxclients 最大连接数