在Python中,subprocess
模块用于执行外部命令
- 使用
subprocess.run()
执行外部命令并获取结果:
import subprocess result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(result.stdout)
- 检查
subprocess.run()
的返回码:
import subprocess result = subprocess.run(['ls', '-l'], capture_output=True, text=True) if result.returncode != 0: print(f"Error occurred: {result.stderr}") else: print(result.stdout)
- 使用
subprocess.Popen()
进行更复杂的操作:
import subprocess process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) stdout, stderr = process.communicate() if process.returncode != 0: print(f"Error occurred: {stderr}") else: print(stdout)
- 使用
try-except
捕获异常:
import subprocess try: result = subprocess.run(['ls', '-l'], capture_output=True, text=True, check=True) print(result.stdout) except subprocess.CalledProcessError as e: print(f"Error occurred: {e.stderr}")
- 使用
subprocess.check_output()
执行外部命令并检查输出:
import subprocess try: output = subprocess.check_output(['ls', '-l'], stderr=subprocess.STDOUT, text=True) print(output) except subprocess.CalledProcessError as e: print(f"Error occurred: {e.output}")
这些示例展示了如何处理subprocess
模块中的错误。根据你的需求,你可以选择合适的方法来处理错误。