I wrote a short python script to read a GPIO pin and watch for a state change (from a momentary contact switch) in order to execute a safe, clean, & orderly shutdown of the raspberry pi computer, since no on-board provision exists out of the box. It is necessary to ensure a clean shutdown in order to avoid the chance that you might corrupt your SD card:
import os
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.IN)prev_input = 0
while True:
input = GPIO.input(4)
if ((not prev_input) and input):
os.system("/sbin/poweroff")
prev_input = input
#slight pause to debounce
time.sleep(0.05)