面试题答案
一键面试import subprocess
def run_complex_command():
command = ['your_command', 'param1', 'param2', 'param3']
try:
result = subprocess.run(command, capture_output=True, text=True, check=True)
print("命令输出:", result.stdout)
except FileNotFoundError:
print("命令不存在")
except subprocess.CalledProcessError as e:
print(f"命令执行出错,错误码: {e.returncode}")
print("标准输出:", e.stdout)
print("标准错误:", e.stderr)
except TypeError as te:
print(f"参数类型错误: {te}")
if __name__ == "__main__":
run_complex_command()
上述代码做了如下操作:
- 使用
subprocess.run
来执行外部命令,并通过check=True
确保如果命令以非零状态码退出,会引发subprocess.CalledProcessError
异常。 - 使用
capture_output=True
来捕获命令的标准输出和标准错误输出,text=True
使得输出以文本形式返回。 - 使用
try - except
块处理可能出现的错误:FileNotFoundError
处理命令不存在的情况。subprocess.CalledProcessError
处理命令执行出错的情况,其中包括返回的错误码以及输出信息。TypeError
处理参数类型错误的情况。在实际使用中,要将['your_command', 'param1', 'param2', 'param3']
替换为真实的命令和参数。