subprocess.Popen取代舊式 os.popen/commands,提供完整的進程控制與管道管理。
cat -n 加行號
from subprocess import Popen, PIPE
p = Popen(["cat", "-n"], stdin=PIPE, stdout=PIPE, bufsize=1, universal_newlines=True)
fin, fout = p.stdin, p.stdout
for i in range(10):
fin.write(f"line{i}\n")
fin.flush()
print(fout.readline().rstrip())
fin.close()
fout.close()
p.wait()
| 參數 | 說明 |
|---|---|
args | 指令與參數列表(建議用 list 避免 shell 注入) |
stdin/stdout/stderr | PIPE 建立管道,None 繼承,檔案物件重導向 |
bufsize | 0 無緩衝,1 行緩衝,>1 塊緩衝,-1 系統預設 |
universal_newlines | True 以文字模式處理(Python 3.7+ 用 text=True) |
shell | True 經由 shell 執行(有注入風險) |
cwd/env | 工作目錄、環境變數 |
subprocess.run (Python 3.5+)
result = subprocess.run(
["grep", "pattern", "file.txt"],
capture_output=True, text=True, timeout=5
)
print(result.stdout)
print(result.returncode)
asyncio.subprocessbufsize、或寫入暫存檔encoding='utf-8', errors='replace'wait() 或 communicate() 回收
import asyncio
async def run_cat():
proc = await asyncio.create_subprocess_exec(
'cat', '-n',
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE
)
for i in range(5):
proc.stdin.write(f"line{i}\n".encode())
await proc.stdin.drain()
line = await proc.stdout.readline()
print(line.decode().rstrip())
proc.stdin.close()
await proc.wait()