Python 进程与并发编程实战
1. 替代复杂的 Subprocess 操作
在进行复杂的 shell 管道操作时,有时可以使用内置模块替代 Subprocess。例如,在获取用户信息时,使用pwd模块比 Subprocess 更方便。
import pwd # 获取 root 用户信息 root_info = pwd.getpwnam('root') print(root_info) # 获取 root 用户的 shell shell = root_info[-1] print(shell)Subprocess 还能同时处理输入、输出和标准错误。以下是一个示例:
import subprocess p = subprocess.Popen("tr a-z A-Z", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) output, error = p.communicate("translatetoupper") print(output)2. 使用 Supervisor 管理进程
作为系统管理员,经常需要管理和处理进程。Supervisor 可以帮助管理长时间运行的进程,确保系统重启后进程能自动恢复。
2.1 安装 Supervisor
可以使用easy_install安装