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

Python Interface to Shell Pipelines (โมดูล pipes)

โมดูล pipes ให้ Python สร้าง Shell Pipeline ได้แบบ Object-Oriented ใช้ /bin/sh ภายใน

import pipes


คลาส Template

แทน Pipeline หนึ่ง Pipeline มีเมธอดหลัก:

เมธอดคำอธิบาย
reset()รีเซ็ต Template กลับสถานะเริ่มต้น
clone()คัดลอก Template ใหม่เหมือนเดิม
debug(flag)True = แสดงคำสั่งระหว่างรัน
append(cmd, kind)เพิ่มคำสั่งท้าย Pipeline
prepend(cmd, kind)เพิ่มคำสั่งหน้า Pipeline
open(file, mode)เปิดไฟล์ผ่าน Pipeline (read/write)
copy(infile, outfile)คัดลอกไฟล์ผ่าน Pipeline

Kind Parameter (2 ตัวอักษร)

รูปแบบ: '--', 'f-', '.-' ฯลฯ

ตัวแรก (Input)ความหมาย
-อ่านจาก Standard Input
fอ่านจากไฟล์ (ระบุใน Command Line)
.ไม่อ่าน Input (อยู่หน้าสุด)
ตัวที่สอง (Output)ความหมาย
-เขียนไป Standard Output
fเขียนไปไฟล์ (ระบุใน Command Line)
.ไม่เขียน Output (อยู่ท้ายสุด)

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

import pipes

t = pipes.Template()
t.append('tr a-z A-Z', '--')        # stdin -> stdout
t.prepend('echo Python Programming', '--')  # ไม่มี input -> stdout
t.append('rev', '--')               # stdin -> stdout
t.debug(True)

f = t.open('test_file', 'w')
f.close()

with open('test_file') as f:
    print(f.read())

ผลลัพธ์ (Debug Output)

$ python3 example.py
echo Python Programming | tr a-z A-Z | rev >test_file
+ rev
+ tr a-z A-Z
+ echo Python Programming
GNIMMARGORP NOHTYP

กรณีใช้งาน

  • สร้าง Pipeline ซับซ้อนแบบ Dynamic
  • ประมวลผลไฟล์ผ่าน Chain ของ Commands
  • Debug Pipeline ได้ง่ายด้วย debug(True)

หมายเหตุ

  • โมดูล pipes ถูก Deprecated ใน Python 3.11+ ควรใช้ subprocess แทน
  • subprocess.Popen ให้ความควบคุมมากกว่าและปลอดภัยกว่า