董偉明技術博客
安裝 python 3.8 環境 , 在此刻 似乎 anaconda 都還不支持 3.8 ,所以直接下載源碼進行編譯安裝
環境: centos7.5
版本:python3.8
1、依賴包安裝
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel
2、下載包:
https://www.python.org/ftp/python/3.8.0/
wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0a1.tgz
3、解壓:
tar -zxvf Python-3.8.0.tgz
4、安裝:
cd Python-3.8.0
./configure --prefix=/usr/local/python3
make && make install
5、建立軟連接
ln -s /usr/local/python3/bin/python3.8 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.8 /usr/bin/pip3
6、測試一下python3是否可以用
python3
pip3
賦值表達式
# 一個用法在 列表推導式
f = lambda x:x*2
[y for i in range(10) if(y:=f(i))]
# 另一個在 循環中間變量賦值
>>> with open('py38_test.txt','r') as fr:
... while (line:=fr.readline()) != 'efg':
... print(line)
...
abc

位置參數
f-string 用來 字符串調試輸出
>>> x=2
>>> print(f'{x**3}')

審計鈎子
PEP 578: Python Runtime Audit Hooks
現在可以給 Python 運行時添加審計鈎子:
In : import sys
...: import urllib.request
...:
...:
...: def audit_hook(event, args):
...: if event in ['urllib.Request']:
...: print(f'Network {event=} {args=}')
...:
...: sys.addaudithook(audit_hook)
In : urllib.request.urlopen('https://httpbin.org/get?a=1')
Network event='urllib.Request' args=('https://httpbin.org/get?a=1', None, {}, 'GET')
Out: <http.client.HTTPResponse at 0x10e394310>
目前支持審計的事件名字和 API 可以看 PEP 文檔 (延伸閱讀鏈接 2), urllib.Request 是其中之一。另外還可以自定義事件:
In : def audit_hook(event, args):
...: if event in ['make_request']:
...: print(f'Network {event=} {args=}')
...:
In : sys.addaudithook(audit_hook)
In : sys.audit('make_request', 'https://baidu.com')
Network event='make_request' args=('https://baidu.com',)
In : sys.audit('make_request', 'https://douban.com')
Network event='make_request' args=('https://douban.com',)
Multiprocessing shared memory
進程間共享內存
在Python 3.8中,multiprocessing模塊提供了SharedMemory類,可以在不同的Python進城之間創建共享的內存區域。
typing 增強
Python是動態類型語言,但可以通過typing模塊添加類型提示,以便第三方 工具 驗證Python代碼。Python 3.8給typing添加了一些新元素,因此它能夠支持更健壯的檢查:
改寫的 fib 數列
# 原始的 fib 數列
(lambda f: f(f, int(input('Input: ')), 1, 0, 1))(lambda f, t, i, a, b: print(f'fib({i}) = {b}') or t == i or f(f, t, i + 1, b, a + b))
continue 可以出現在 finally 里了
while randint(0,1):
try:
1/0
except:
print('divided...error')
finally:
print('finally...')
continue
