共計(jì) 967 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
Python 進(jìn)程管理工具可以通過(guò)多種方式使用,以下是一些常見(jiàn)的用法示例:
- 使用
os
模塊創(chuàng)建新的進(jìn)程:
import os
pid = os.fork() # 創(chuàng)建一個(gè)子進(jìn)程
if pid == 0:
# 子進(jìn)程代碼
print("This is a child process")
else:
# 父進(jìn)程代碼
print("This is the parent process")
- 使用
subprocess
模塊執(zhí)行外部命令:
import subprocess
# 執(zhí)行命令并等待命令完成
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)
# 啟動(dòng)一個(gè)長(zhǎng)時(shí)間運(yùn)行的進(jìn)程并與其交互
process = subprocess.Popen(["python3", "my_script.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, error = process.communicate(input="input data")
print(output.decode())
- 使用
multiprocessing
模塊創(chuàng)建和管理多個(gè)進(jìn)程:
import multiprocessing
def worker(num):
print(f"Worker {num} started")
if __name__ == "__main__":
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
p.start()
processes.append(p)
for p in processes:
p.join() # 等待所有進(jìn)程完成
- 使用第三方庫(kù)
celery
進(jìn)行分布式任務(wù)管理:
from celery import Celery
app = Celery('myapp', broker='pyamqp://guest@localhost//')
@app.task
def add(x, y):
return x + y
result = add.delay(4, 6)
print(result.get())
這只是一些簡(jiǎn)單的示例,實(shí)際使用中可以根據(jù)具體需求選擇合適的工具和方法來(lái)管理和操作進(jìn)程。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完