Notes & software courses · Free to learn
Aph's Blog
On this page

วันที่ 20 — ตัวจัดการแพ็กเกจ (Package Manager)

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

เรียนรู้การใช้ PIP จัดการ packages ใน Python การดึงข้อมูลจาก URL ด้วย requests และการสร้าง Package เป็นของตัวเอง

Python Package Manager

Package คือโมดูลหรือกลุ่มโมดูลที่ถูกรวมกัน ใน Python เราใช้ pip (Pip Installs Packages) ในการจัดการ packages

PIP คืออะไร

PIP ย่อมาจาก Preferred Installer Program หรือ Pip Installs Packages เป็น package manager สำหรับ Python ใช้ install และจัดการ packages ที่ไม่ได้มาพร้อมกับ Python

การติดตั้ง PIP

ถ้าใช้ Python 3.4 ขึ้นไป pip ถูกติดตั้งมาพร้อมกันแล้ว ตรวจสอบได้ด้วย:

shell
pip --version

ถ้ายังไม่มี ติดตั้งได้โดย:

shell
asabeneh@Asabeneh:~$ pip install pip

การ Install Packages

ลองติดตั้ง numpy ซึ่งเป็น package สำหรับงาน data science:

shell
pip install numpy

เริ่มใช้ numpy:

python
import numpy
print(numpy.version.version)
print(numpy.pi)

ติดตั้ง pandas:

shell
pip install pandas
python
import pandas
print(pandas.__version__)

webbrowser Module

ลองนำเข้า web browser module ซึ่งช่วยให้เราเปิดเว็บไซต์ได้ เราไม่จำเป็นต้อง install module นี้ เพราะมันถูกติดตั้งมาพร้อมกับ Python 3 แล้ว ตัวอย่างเช่น ถ้าต้องการเปิดเว็บไซต์จำนวนมากในเวลาเดียวกัน หรือต้องการ schedule บางอย่าง สามารถใช้ webbrowser module นี้ได้

python
import webbrowser # web browser module to open websites

# list of urls: python
url_lists = [
    'http://www.python.org',
    'https://www.linkedin.com/in/asabeneh/',
    'https://github.com/Asabeneh',
    'https://twitter.com/Asabeneh',
]

# opens the above list of websites in a different tab
for url in url_lists:
    webbrowser.open_new_tab(url)

การ Uninstall Packages

shell
pip uninstall packagename

การดู List Packages

shell
pip list

pip show

shell
pip show packagename
# pip show numpy
# Name: numpy
# Version: 1.13.1
# Summary: NumPy: array processing for numbers, strings, records, and objects.
# Home-page: http://www.numpy.org
# Author: NumPy Developers
# Author-email: numpy-discussion@python.org
# License: BSD
# Location: /usr/local/lib/python3.6/dist-packages
# Requires:
# Required-by: matplotlib, pandas, scikit-learn, scipy

pip freeze

ใช้สร้าง requirements.txt ที่บันทึก packages และ versions ทั้งหมดในโปรเจกต์:

shell
pip freeze
# asn1crypto==1.4.0
# beautifulsoup4==4.9.3
# ...

# เซฟลงไฟล์
pip freeze > requirements.txt

# ติดตั้งจาก requirements.txt
pip install -r requirements.txt

การอ่านข้อมูลจาก URL

Python มี packages ต่าง ๆ สำหรับอ่านข้อมูลจาก URL ที่นิยมคือ requests:

shell
pip install requests
python
import requests # importing requests module

url = 'https://restcountries.com/v3.1/all'  # countries api
response = requests.get(url)  # opening a url
print(response.status_code)  # status code, success: 200
countries = response.json()
print(type(countries))
print(countries[:1])  # first country

ตัวอย่างการใช้ response object:

python
import requests
url = 'https://api.github.com/users/asabeneh'  # github api
response = requests.get(url)
print(response.status_code)  # status code
print(response.headers)      # headers
print(response.text)         # response text (string)
print(response.json())       # response as dict

การสร้าง Package

Package คือโฟลเดอร์ที่มีไฟล์ __init__.py รวมกับ modules ต่าง ๆ ตัวอย่างการสร้าง package ชื่อ mypackage:

─ mypackage
    ├── __init__.py
    ├── arithmetic.py
    └── greet.py
python
# arithmetic.py
def add_numbers(num1, num2):
    return num1 + num2


def subtract_numbers(num1, num2):
    return num1 - num2


def multiply_numbers(num1, num2):
    return num1 * num2


def division(num1, num2):
    return num1 / num2
python
# greet.py
def greet_person(firstname, lastname):
    return f'{firstname} {lastname}, welcome to 30DaysOfPython Challenge!'
python
# __init__.py
from mypackage.arithmetic import add_numbers, subtract_numbers, multiply_numbers, division
from mypackage.greet import greet_person

การใช้ package:

python
from mypackage import add_numbers, subtract_numbers, multiply_numbers, division, greet_person
print(add_numbers(1, 2))        # 3
print(subtract_numbers(2, 1))   # 1
print(multiply_numbers(9, 9))   # 81
print(division(1, 2))           # 0.5
print(greet_person('Asabeneh', 'Yetayeh'))

ข้อมูลเพิ่มเติมเกี่ยวกับ Packages

Packages ที่น่าสนใจแยกตามหมวด:

  • Database: psycopg2, SQLAlchemy
  • Web: flask, django, fastapi
  • HTML Parser: beautifulsoup4, html5lib
  • XML: lxml
  • GUI: tkinter, PyQt5, kivy
  • Data Science: numpy, pandas, scipy, matplotlib, seaborn
  • Network: requests, httpx
  • Time: arrow
  • Cryptography: pyca/cryptography, PyNaCl
  • Testing: pytest, doctest
  • Serialization: protobuf, msgpack

💻 แบบฝึกหัด — วันที่ 20

  1. อ่านข้อมูลจาก URL นี้แล้วหา 10 คำที่พบบ่อยที่สุด: romeo_and_juliet = 'http://www.gutenberg.org/files/1112/1112.txt'
  2. อ่านข้อมูลจาก cats API (cats_api = 'https://api.thecatapi.com/v1/breeds') แล้วหา: (1) ค่า min, max, mean, median, standard deviation ของน้ำหนักแมวในหน่วยเมตริก (2) ค่า min, max, mean, median, standard deviation ของอายุขัยแมวในปี (3) สร้าง frequency table ของประเทศและสายพันธุ์แมว
  3. อ่านข้อมูลจาก countries API แล้วหา: (1) 10 ประเทศที่มีพื้นที่ใหญ่ที่สุด (2) 10 ภาษาที่มีคนพูดมากที่สุด (3) จำนวนภาษาทั้งหมดใน countries API
  4. UCI เป็นแหล่งข้อมูล dataset สำหรับ data science และ machine learning อ่านเนื้อหาจาก UCL (https://archive.ics.uci.edu/ml/datasets.php) การทำโดยไม่ใช้ library เพิ่มเติมอาจยาก ดังนั้นลองใช้ BeautifulSoup4