python subprocess錯(cuò)誤怎么處理

小樊
81
2024-11-16 16:04:44
欄目: 編程語言

在Python中,subprocess模塊用于執(zhí)行外部命令

  1. 使用subprocess.run()執(zhí)行外部命令并獲取結(jié)果:
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
  1. 檢查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)
  1. 使用subprocess.Popen()進(jìn)行更復(fù)雜的操作:
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)
  1. 使用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}")
  1. 使用subprocess.check_output()執(zhí)行外部命令并檢查輸出:
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模塊中的錯(cuò)誤。根據(jù)你的需求,你可以選擇合適的方法來處理錯(cuò)誤。

0