读书笔记 python

create new object or modify the object

  • create new object > slice operator([:]); + operator;

dir 和 help 函数

  1. var = ''; dir(var) 可以输出var那个object中的所有方法。
  2. var = ''; ty = type(var); help(ty.method) 可以输出var的类型中method的相关信息。

c/c++ 调用python函数

流程如下: 1. 我们先定义一个python函数

1
2
def great_function(a)
.........
2. 我们使用上面的python函数定义一个c/c++函数 > 假设上面的great_function在一个module中, 比如说, 这个module名字叫great_module.py

那么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元素,module、function、tuple、string等等, 实际上都是PyObject。c/c++中操纵它们,一律使用PyObject指针。

  • 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)

  1. 最后可以在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

  1. \s --- matches a whitespace character.
  2. '' --- matches a non-whitespace character.
    • --- apply to the immediately preceding character and indicates to match zero or more of the preceding characters.
  3. *? --- like above, but in "non-greedy mode".
  4. () --- added to a regular expression, they are ignored and allow you to extract a particular subset of the matched string.
  5. -- matches the empty string, but only at the start or end of a word.
  6. --- like above, but not in the start or end of the word.
  7. -- matches any decimal digit, equivalent to the set[0-9].
  8. --- 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
2
cmd = 'ls -l'
fp = os.popen(cmd)

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',)

动态导入模块

  1. use importlib module (also has a imp module which deprecated in 3.4)
1
2
3
import importlib

mymodule = importlib.import_module('modulename')
  1. use __import__ built_in function mymodule = __import__('modulename')

  2. examples in <>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    >>> modulenames = ['sys', 'os', 're']
    >>> 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
2
3
4
5
6
7
8
#!/usr/bin/env python

def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.

Returns string."""

return ";".join(["%s = %s" % (k, v) for k, v in params.items()])

可以以一下方式输出其doc string:

1
2
3
>>> import test
>>> print test.buildConnectionString.doc

python — doctest

  • in some class
1
2
3
4
5
6
7
8
9
10
11
def get(self, key, value=None):
"""Returns the value associated with key or value if key isn't
in the dictionary

>>> d = OrderedDict(dict(s=1, a=2, n=3, i=4, t=5, y=6))
>>> d.get("X", 21)
21
>>> d.get("i")
4
"""
return self.__dict.get(key, value)
  • add following three line to the module
1
2
3
if __name__ == "__main__":
import doctest
doctest.testmod()

有用的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

  1. 首先在sys.modules中找
  2. 若找不到, 则开始在sys.meta_path中查找(它包含一个finder objects的列表)-- 通过find_spec()函数进行查找
  3. 若找到,则会返回一个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

-------------本文结束感谢您的阅读-------------