Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

POSIX System Calls ใน Python (โมดูล posix)

โมดูล posix ให้ Low-level POSIX System Calls บน UNIX ควรใช้ผ่าน os Module (Superset ของ posix) แทนการ Import โดยตรง

import posix (หรือ import os)


posix.environ

Dictionary ของ Environment Variables (Bytes Keys/Values บน UNIX)

print(posix.environ[b'HOME'])  # b'/home/user'
> **หมายเหตุ:** แก้ posix.environ ไม่ส่งผลต่อ Subprocess ต้องใช้ os.putenv() หรือส่ง env ให้ subprocess.Popen

File Descriptor Operations

posix.open(file, flags[, mode])

เปิดไฟล์ คืน File Descriptor (Integer)

  • Flags: O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC, O_APPEND
  • Mode: Permission (0o644 etc.) เมื่อใช้ O_CREAT

posix.read(fd, n)

อ่านสูงสุด n Bytes จาก FD

posix.write(fd, data)

เขียน Bytes ลง FD

posix.close(fd)

ปิด FD


โค้ดตัวอย่าง

import posix

# เปิดไฟล์อ่าน
fd = posix.open("fruits.txt", posix.O_RDONLY)
print("File Descriptor:", fd)

# อ่านข้อมูล
data = posix.read(fd, 512)
print(data)  # b'Mango\nOrange\nBanana\n...'

posix.close(fd)

# Environment
print("HOME:", posix.environ[b'HOME'])

ผลลัพธ์

File Descriptor: 3
b'Mango\nOrange\nBanana\nApple\nGuava\nGrape\nRaspberry\nBlueberry\nPineapple\nWatermelon\n'
HOME: b'/home/unix_user'

System Calls สำคัญอื่นๆ

Functionคำอธิบาย
fork()สร้าง Child Process
exec*()แทนที่ Process Image (execve, execl, execvp...)
waitpid()รอ Child Process จบ
kill(pid, sig)ส่ง Signal
pipe()สร้าง Pipe (รองรับ Pipe2)
dup/dup2()Duplicate FD
stat/fstat/lstat()File Status
chmod/chown()Permission/Owner
unlink/rmdir/mkdir()File/Directory Ops
access()Check Permission

ควรใช้ os Module แทน

import os

# แทน posix.open
fd = os.open("file.txt", os.O_RDONLY)
data = os.read(fd, 1024)
os.close(fd)

# แทน posix.environ
print(os.environ['HOME'])

# High-level API ที่ดีกว่า
with open("file.txt") as f:
    data = f.read()

สรุป

  • posix = Low-level POSIX API
  • os = Portable Wrapper (Windows + UNIX) + High-level Helpers
  • เขียนโค้ดใหม่: ใช้ os หรือ pathlib / subprocess
  • Porting Legacy Code: อาจเจอ posix โดยตรง