温馨提示×

python3 linux如何进行进程管理

小樊
81
2024-11-28 00:33:25
栏目: 编程语言

在Python 3中,可以使用subprocess模块来在Linux环境下进行进程管理

  1. 启动一个子进程:
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')}")
  1. 等待子进程完成:
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")
  1. 检查子进程是否仍在运行:
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")
  1. 向子进程发送信号:
import subprocess
import signal

# 启动一个命令行程序(如ls)
process = subprocess.Popen(["ls"])

# 向子进程发送SIGINT信号(如Ctrl+C)
process.send_signal(signal.SIGINT)

# 等待子进程终止
process.wait()

这些示例展示了如何使用Python 3的subprocess模块在Linux环境下进行基本的进程管理。你可以根据需要调整这些示例以满足你的具体需求。

0