读书笔记 python
create new object or modify the object
- create new object > slice operator([:]); + operator;
dir 和 help 函数
var = ''; dir(var)
可以输出var那个object中的所有方法。var = ''; ty = type(var); help(ty.method)
可以输出var的类型中method的相关信息。
c/c++ 调用python函数
流程如下: 1. 我们先定义一个python函数 1
2def great_function(a)
.........
那么c/c++中函数可以使用下面方法进行定义: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#include <Python.h>
int great_function_from_python(int a)
{
int res;
PyObject *pModule, *pFunc;
PyObject *pArgs, *pValue;
/* import the module*/
pModule = PyImport_Import(PyString_FromString("great_module"));
/* great_function in great_module */
pFunc = PyObject_GetAttrString(pModule, "great_function");
/* build args */
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0, PyInt_FromLong(a));
/* call */
pValue = PyObject_CallObject(pFunc, pArgs);
res = PyInt_AsLong(pValue);
return res;
}
Python的类型可以与c/c++语言可以相互转换。 Python类型xxx转换为c/c++语言类型yyy要使用Pyxxx_Asyyy函数;c/c++中类型yyy转换为Python类型xxx使用Pyxxx_Fromyyy函数。
- 可以创建Python类型的变量, 使用Pyxxx_New可以创建类型为xxx的变量。
若var是Tuple, 则var[i] = b对应于PyTuple_SetItem(var, i, b)
- 最后可以在c/c++中测试
1
2
3
4
5
6
7
8
9
10#include <Python.h>
int great_function_from_python(int a);
int main(int argc, char *argv[])
{
Py_Initialize();
printf("%d",great_function_from_python(2));
Py_Finalize();
}
string中的函数和list中的函数区别
string 中的函数一般都是创建一个新的string,而原来的string保留; list 中的函数一般修改参数,返回None。
regular expression
\s
--- matches a whitespace character.- '' --- matches a non-whitespace character.
- --- apply to the immediately preceding character and indicates to match zero or more of the preceding characters.
- *? --- like above, but in "non-greedy mode".
- () --- added to a regular expression, they are ignored and allow you to extract a particular subset of the matched string.
- -- matches the empty string, but only at the start or end of a word.
- --- like above, but not in the start or end of the word.
- -- matches any decimal digit, equivalent to the set[0-9].
- --- matches any non-digit character, equivalent to [^0-9].
调用shell中的命令
Any program that you can launch from the shell can also be launched from Python using a pipe.
1 | cmd = 'ls -l' |
print函数
输出格式, 类似c中的printf, 也可以控制宽度和精度 > %d --- 整形 %x --- 16进制 %o --- 8进制 bin() 函数 --- 2进制 %f --- 浮点数 %s --- string 字符串 %r --- 类似%s, 当时字符串会带上‘’; 也可能会带上待打印对象的一些信息
print 会自动在末尾加上换行符, 如何要让它不加上‘’,只需在最后的参数加上','
print var1, var2,
删除list中的某项
pop > lst.pop(index), and return the value that will be deleted
del > del lst[index], and return None > del lst[:], and return None
remove > lst.remove(thevalue), and return None
tuple in python
a tuple is a comma-separated list of values: t = 'a', 'b', 'c' although it is not necessary, it is common in python to enclose a tuple in parentheses to help us quickly identify tuples when we look in python code. t = ('a', 'b', 'c')
and to create a tuple with a single element, you have to include the final comma: t_single = ('a',)
动态导入模块
- use
importlib
module (also has aimp
module which deprecated in 3.4)
1 | import importlib |
use
__import__
built_in functionmymodule = __import__('modulename')
examples in <
> 1
2
3
4
5
6
7
8
9
10'sys', 'os', 're'] modulenames = [
modulenames
output> ['sys', 'os', 're']
modules = map(__import__, modulenames)
modules
output> [<module 'sys' (built_in)>,
<module 'os' from 'thepath'>,
<module 're' from 'thepath'>]
modules[0].version
doc string in function
将以下代码保存为test.py, 在函数中以””"......"”””的包起字符串就是一个doc string:
1 | #!/usr/bin/env python |
可以以一下方式输出其doc string:
1 | import test |
python — doctest
- in some class
1 | def get(self, key, value=None): |
- add following three line to the module
1 | if __name__ == "__main__": |
有用的package
- collections: ChainMap, Counter, defaultdict, deque, namedtuple, OrderedDict
- functools: lru_cache, partial, singleddispatch, warps
- itertools: count, islice, cycle, repeat, compress, dropwhile, filterfalse
python中的threading module 和 multiprocessing module
-- python 中的thread 对于io操作是效率最高的, 而且内部实现多线程也是在一个主的线程里,类似协程
python import module
- 首先在
sys.modules
中找 - 若找不到, 则开始在
sys.meta_path
中查找(它包含一个finder objects的列表)-- 通过find_spec()
函数进行查找 - 若找到,则会返回一个
module spec
的对象, 其内包含loader,用于导入时使用
python socket
- if socket.recv() return 0, means the other side is closed(or is in the process of closing) if you get returned value 0, it means the socket is broken
pyinstaller 打包python
C:\Python27\Scripts\pyinstaller.exe -F -w /path/to/the/python/scripts
*args and **kwargs 非keyword的variable arguments 和 keyword的variable argument
int & bytes
from_bytes & to_bytes builtin method