执行外部命令并获取它的输出-python cookbook(第3版)高清中文完整版

时间:2024-06-29 23:06:46
【文件属性】:

文件名称:执行外部命令并获取它的输出-python cookbook(第3版)高清中文完整版

文件大小:4.84MB

文件格式:PDF

更新时间:2024-06-29 23:06:46

python cookbook 第3版 高清 中文完整版

13.6 执行外部命令并获取它的输出 问题 You want to execute an external command and collect its output as a Python string. 解决方案 Use the subprocess.check_output() function. For example: import subprocess out_bytes = subprocess.check_output([‘netstat’,’-a’]) This runs the specified command and returns its output as a byte string. If you need to interpret the resulting bytes as text, add a further decoding step. For example: out_text = out_bytes.decode(‘utf-8’) If the executed command returns a nonzero exit code, an exception is raised. Here is an example of catching errors and getting the output created along with the exit code: try: out_bytes = subprocess.check_output([‘cmd’,’arg1’,’arg2’]) except subprocess.CalledProcessError as e: out_bytes = e.output # Output generated before error code = e.returncode # Return code By default, check_output() only returns output written to standard output. If you want both standard output and error collected, use the stderr argument: out_bytes = subprocess.check_output([‘cmd’,’arg1’,’arg2’], stderr=subprocess.STDOUT) If you need to execute a command with a timeout, use the timeout argument: try: out_bytes = subprocess.check_output([‘cmd’,’arg1’,’arg2’], timeout=5) except subprocess.TimeoutExpired as e: ... Normally, commands are executed without the assistance of an underlying shell (e.g., sh, bash, etc.). Instead, the list of strings supplied are given to a low-level system com‐ mand, such as os.execve(). If you want the command to be interpreted by a shell, supply it using a


网友评论