Intro
各平台依照指示下載安裝即可。Windows環境下指令為py
。
Ecosystem - 生態系
語言特性
python / py
依照環境及版本,直接於指令列執行Python程式碼檔案:
$ echo "print('Hello World')" > hello-world.py
$ python hello-world.py
$ python3 hello-world.py
$ py hello-world.py
pip
PyPI · The Python Package Index
Pip為Python套件管理器,可以直接官網下載執行get-pip.py自動安裝,或者套件安裝如APT:
$ apt install python-pip
$ apt install python3-pip
Namespace 規則:{Package name}
(與Github無關連)
Pip使用範例:
$ sudo pip install requests
The Packaging Flow - To get an overview of the flow used to publish your code
專案移植
將專案依賴的套件利用freeze指令輸出到指定檔案:
pip freeze > requirements.txt
在新平台執行此專案前,即可依照檔案安裝:
pip install -r requirments.txt
Run Module
pip
從10版之後改為Module依環境形式啟動,這好處是可以指定由Python版本-m
使用相依的pip
模組啟動:
$ python -m pip install {package}
指定python3-pip
:
$ python3 -m pip install {package}
Windows使用pip
Windows環境要使用pip
指令得Add PATH (pip.exe位於Python安裝目錄./Script下),可以參考Is Python in your PATH
Windows若不想額外安裝設定pip
,可以直接使用上述pip module方式啟動:
python3.4 -m pip install {package}
References
Packaging Python Projects - PyPA
正式環境
uWSGI
透過Nginx > uWSGI > Python
架構方式搭建:Quickstart for Python/WSGI applications
Setting up Django and your web server with uWSGI and nginx
Concurrency (並發/並行)
Multi-threading
Python 採用全域直譯器鎖(Global Interpreter Lock,縮寫GIL),所以若應用場景是要最大發揮並行 CPU 運算則建議使用 Multi-processing。
Python - threading — Thread-based parallelism
Python - queue — A synchronized queue class
Reference: Python 多執行緒 threading 模組平行化程式設計教學
Multiprocessing Vs. Threading In Python: What You Need To Know.
Multi-processing
multiprocessing — Process-based parallelism
Reference: 進程間的通信(Queue,Pipe)與數據共享(Manager)
編譯 Compile
透過 PyInstaller 套件可以針對當下 OS 環境 build 可執行檔
Command Line
ArgumentParser
Python 內建 argparse lib 可以方便處理 CMD arguments
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))