在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
模塊中的錯誤。根據你的需求,你可以選擇合適的方法來處理錯誤。