廖雪峰Python

廖雪峰Python

字符串

1
2
'xx'.lower() .upper()

面试题

https://zhuanlan.zhihu.com/p/270331009

Python库

time

1
2
3
4
5
6
7
8
9
10
import time

# 打印时间戳
print(time.time()) # 自1970年1月1日午夜(历元)以来的秒数

# 打印本地时间
print(time.localtime(time.time())) # 本地时间

# 打印格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) # 格式化时间
1
2
3
4
5
6
7
8
9
import datetime

# 打印当前时间
time1 = datetime.datetime.now()
print(time1)

# 打印按指定格式排版的时间
time2 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(time2)

sys

functools

random

1
time.sleep(random.random())

高级功能

切片

1
2
切片 list,tuple,字符串都支持
l[a:b:2] a+1个开始取,到b个,间隔为2

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
迭代
for i in dict:

for v in dict.values():

for k,v in dict.items():

>>> from collections.abc import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True

>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C

列表生成式

1
2
3
4
5
6
7
列表生成式
[x * x for x in range(1, 11)]
[x * x for x in range(1, 11) if x % 2 == 0]

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

生成器

1
2
3
4
5
6
7
8
9
g = (x * x for x in range(10))

def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'

迭代器

模块

1
2
sys.argv
sys.path

错误、调试和测试

常见错误

1
2
3
4
5
6
StopIteration 
AttributeError
ZeroDivisionError
KeyError
ValueError
AttributeError

错误、调试和测试

1
try except else finally
1
2
assert
logging
1
2
3
4
5
6
7
单元测试
import unittest

文档测试
if __name__ == '__main__':
import doctest
doctest.testmod()

IO编程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
文件读写
with open('/path/to/file', 'r') as f:
print(f.read())

readlines()
readline()
read(size)

rb
>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
>>> f.read()
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')

with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')
1
2
3
4
5
6
7
8
9
10
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

语法
strip()方法语法:

str.strip([chars]);
参数
chars -- 移除字符串头尾指定的字符序列。
1
StringIO和BytesIO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
操作文件和目录
os.environ
os.environ.get('PATH')
os.path.abspath('.')
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')

os.path.split()
os.path.splitext()可以直接让你得到文件扩展名

[x for x in os.listdir('.') if os.path.isdir(x)]
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
序列化 反序列化
import pickle

import pickle
>>> d = dict(name='Bob', age=20, score=88)
>>> pickle.dumps(d)
b'\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x14X\x05\x00\x00\x00s

f = open('dump.txt', 'wb')
>>> pickle.dump(d, f)
>>> f.close()

>>> f = open('dump.txt', 'rb')
>>> d = pickle.load(f)
>>> f.close()
>>> d
{'age': 20, 'score': 88, 'name': 'Bob'}

JSON

多进程和多线程python

csdn操作系统

csdn操作系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fork()

os.getpid()
os.getppid()


from multiprocessing import Process
p = Process(target=run_proc, args=('test',))
p.start()
p.join()

from multiprocessing import Pool
p = Pool(4)
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close()
p.join()

进程间通信 Queue、Pipes
1
2
os.getpid()
os.getppid()

进程间通信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
print('Process to write: %s' % os.getpid())
for value in ['A', 'B', 'C']:
print('Put %s to queue...' % value)
q.put(value)
time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
print('Process to read: %s' % os.getpid())
while True:
value = q.get(True)
print('Get %s from queue.' % value)

if __name__=='__main__':
# 父进程创建Queue,并传给各个子进程:
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()
运行结果如下:

Process to write: 50563
Put A to queue...
Process to read: 50564
Get A from queue.
Put B to queue...
Get B from queue.
Put C to queue...
Get C from queue.

线程

1
2
3
4
5
import time, threading

t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
1
进程复制变量,线程共享变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# multithread
import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n

def run_thread(n):
for i in range(10000000):
change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
1
threading.current_thread().name

Lock()

1
2
3
4
5
6
7
8
9
10
11
12
13
balance = 0
lock = threading.Lock()

def run_thread(n):
for i in range(100000):
# 先要获取锁:
lock.acquire()
try:
# 放心地改吧:
change_it(n)
finally:
# 改完了一定要释放锁:
lock.release()

ThreadLocal

1
解决局部变量在函数调用的时候,传递起来麻烦的问题
1
2
3
4
import threading

# 创建全局ThreadLocal对象:
local_school = threading.local()

异步IO

1
2
3
4
5
6
7
8
9
import asyncio

EventLoop

async await

asyncio.run(hello())

asyncio.gather()

协程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'

def produce(c):
c.send(None)
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()

c = consumer()
produce(c)

aiohttp

分布式进程

1
from multiprocessing.managers import BaseManager

多进程和多线程java

创建新线程

1
2
3
4
5
6
7
8
9
10
Thread t = new MyThread();
t.start(); // 启动新线程

Thread t = new Thread(new MyRunnable());
t.start(); // 启动新线程

Thread t = new Thread(() -> {
System.out.println("start new thread!");
});
t.start(); // 启动新线程

线程的状态

1
2
t.start(); // 启动t线程
t.join(); // 此处main线程会等待t结束

中断线程

1
2
3
4
5
t.interrupt(); isInterrupted()

InterruptedException

running 标志位
1
关键字volatile

守护线程

1
所有非守护线程都执行完毕后,无论有没有守护线程,虚拟机都会自动退出

线程同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 多线程
public class Main {
public static void main(String[] args) throws Exception {
var add = new AddThread();
var dec = new DecThread();
add.start();
dec.start();
add.join();
dec.join();
System.out.println(Counter.count);
}
}

class Counter {
public static final Object lock = new Object();
public static int count = 0;
}

class AddThread extends Thread {
public void run() {
for (int i=0; i<10000; i++) {
synchronized(Counter.lock) {
Counter.count += 1;
}
}
}
}

class DecThread extends Thread {
public void run() {
for (int i=0; i<10000; i++) {
synchronized(Counter.lock) {
Counter.count -= 1;
}
}
}
}

同步方法

1
解决多线程处理全局变量问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Counter {
private int count = 0;

public void add(int n) {
synchronized(this) {
count += n;
}
}

public void dec(int n) {
synchronized(this) {
count -= n;
}
}

public int get() {
return count;
}
}

var c1 = Counter();
var c2 = Counter();

// 对c1进行操作的线程:
new Thread(() -> {
c1.add();
}).start();
new Thread(() -> {
c1.dec();
}).start();

// 对c2进行操作的线程:
new Thread(() -> {
c2.add();
}).start();
new Thread(() -> {
c2.dec();
}).start();
1
2
3
public synchronized void add(int n) { // 锁住this
count += n;
} // 解锁
1
线程安全”的

死锁

可重入锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
可重入锁

public class Counter {
private int count = 0;

public synchronized void add(int n) {
if (n < 0) {
dec(-n);
} else {
count += n;
}
}

public synchronized void dec(int n) {
count += n;
}
}
死锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
死锁

public void add(int m) {
synchronized(lockA) { // 获得lockA的锁
this.value += m;
synchronized(lockB) { // 获得lockB的锁
this.another += m;
} // 释放lockB的锁
} // 释放lockA的锁
}

public void dec(int m) {
synchronized(lockB) { // 获得lockB的锁
this.another -= m;
synchronized(lockA) { // 获得lockA的锁
this.value -= m;
} // 释放lockA的锁
} // 释放lockB的锁
}