Python subprocess.capture_output 参考
Python subprocess.capture_output 参考,整理标准库调用语法、参数、示例、返回值和常见错误。
语法
import subprocess
result = subprocess.run(command, capture_output=True, text=True)
参数
args:命令和参数数组,优先使用数组而不是拼接字符串。timeout / cwd / env:控制超时、工作目录和环境变量。
返回值
返回 CompletedProcess、输出文本或子进程对象;命令失败时可抛出 CalledProcessError。
示例
import subprocess
result = subprocess.run(["python", "--version"], capture_output=True, text=True)
print(result.stdout)
常见错误
- 把用户输入拼进 shell 命令有注入风险。
- 没有设置 timeout 或检查返回码,失败命令可能被当成成功。
相关内容
相关内容
- Python collections.ChainMap 参考 Python collections.ChainMap 参考,整理标准库调用语法、参数、示例、返回值和常见错误。
- Python collections.Counter 参考 Python collections.Counter 参考,整理标准库调用语法、参数、示例、返回值和常见错误。
- Python collections.defaultdict 参考 Python collections.defaultdict 参考,整理标准库调用语法、参数、示例、返回值和常见错误。
- Python collections.deque 参考 Python collections.deque 参考,整理标准库调用语法、参数、示例、返回值和常见错误。
- Python collections.most_common 参考 Python collections.most_common 参考,整理标准库调用语法、参数、示例、返回值和常见错误。
- Python collections.namedtuple 参考 Python collections.namedtuple 参考,整理标准库调用语法、参数、示例、返回值和常见错误。