在Python 3中,可以使用subprocess
模塊來在Linux環境下進行進程管理
import subprocess
# 啟動一個命令行程序(如ls)
process = subprocess.Popen(["ls"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 獲取子進程的輸出
output, error = process.communicate()
if process.returncode != 0:
print(f"Error occurred: {error.decode('utf-8')}")
else:
print(f"Output: {output.decode('utf-8')}")
import subprocess
import time
# 啟動一個命令行程序(如ls)
process = subprocess.Popen(["ls"])
# 等待子進程完成,并獲取返回碼
return_code = process.wait()
if return_code != 0:
print(f"Error occurred with return code {return_code}")
else:
print("Subprocess completed successfully")
import subprocess
import os
# 啟動一個命令行程序(如ls)
process = subprocess.Popen(["ls"])
# 獲取子進程的進程ID
pid = process.pid
# 檢查子進程是否仍在運行
if os.path.exists(f"/proc/{pid}"):
print(f"Subprocess with PID {pid} is still running")
else:
print(f"Subprocess with PID {pid} has terminated")
import subprocess
import signal
# 啟動一個命令行程序(如ls)
process = subprocess.Popen(["ls"])
# 向子進程發送SIGINT信號(如Ctrl+C)
process.send_signal(signal.SIGINT)
# 等待子進程終止
process.wait()
這些示例展示了如何使用Python 3的subprocess
模塊在Linux環境下進行基本的進程管理。你可以根據需要調整這些示例以滿足你的具體需求。