Hiểu về Process (Tiến trình)
Khi bạn chạy chương trình trên Windows, macOS hoặc Linux, hệ điều hành tạo một tiến trình (process). Tiến trình sử dụng tài nguyên: CPU, RAM, ổ đĩa, cấu trúc dữ liệu trong kernel. Các tiến trình bị cô lập - không thấy hoặc can thiệp vào nhau.
Lưu ý: Code ví dụ chạy trên Linux/Unix. Trên Windows có thể ném ngoại lệ.
Mục tiêu của Hệ điều hành
Phân chia công việc công bằng và phản hồi nhanh cho người dùng. Được đạt bằng cách theo dõi tiến trình, cấp thời gian chạy nhỏ cho từng tiến trình rồi chuyển sang tiến trình khác. Có thể xem trạng thái bằng Task Manager (Windows), Activity Monitor (macOS), hoặc lệnh top (Linux).
Lập trình viên có thể truy cập dữ liệu tiến trình qua module os:
import os
print(f"Process ID: {os.getpid()}")
print(f"User ID: {os.getuid()}, Group ID: {os.getgid()}")
print(f"Current Working Directory: {os.getcwd()}")
Module subprocess
Python có module subprocess để tạo tiến trình mới, gửi/nhận thông tin, xử lý lỗi và mã trả về. Tài liệu chính thức khuyến nghị dùng subprocess thay cho os.system cũ.
Hàm subprocess.call() chờ lệnh kết thúc và đọc đầu ra. Ví dụ lấy thông tin dung lượng đĩa.
Ví dụ 1: Chạy df -h và đọc vào Pandas
from io import StringIO
import pandas as pd
import subprocess
diskspace = "df"
diskspace_arg = "-h"
sp = subprocess.Popen([diskspace, diskspace_arg], stdout=subprocess.PIPE)
b = StringIO(sp.communicate()[0].decode('utf-8'))
df = pd.read_csv(b, sep=",")
print(df)
Ví dụ 2: Chi tiết hơn với check_output
import subprocess
def uname_func():
uname = "uname"
uname_arg = "-a"
return subprocess.call([uname, uname_arg])
def disk_func():
diskspace = "pydf"
diskspace_arg = "-a"
stdout = subprocess.check_output([diskspace, diskspace_arg])
return stdout
def main():
userinfo = uname_func()
discinfo = disk_func()
print("Displaying values now...")
print(discinfo.decode('utf-8'))
content = discinfo.decode('utf-8').split("\n")
print(content)
main()
Kết quả mẫu: Hiển thị thông tin kernel, hệ thống file, dung lượng, % sử dụng, điểm mount...
Tóm tắt
subprocess.Popen: Kiểm soát chi tiết (stdin, stdout, stderr pipe).subprocess.call: Chạy lệnh, chờ xong, trả về mã thoát.subprocess.check_output: Chạy lệnh, trả về stdout dạng bytes, ném exception nếu mã thoát ≠ 0.subprocess.run(Python 3.5+): API cấp cao, khuyến nghị dùng cho hầu hết trường hợp.