wiki:PythonSandbox

This page is mainly for internal use.

System Calls

New method of making system calls using the subprocess module (ORIGINAL POST WAS INCORRECT FOR CATCHING STDOUT/STDERR):

import subprocess

proc = subprocess.Popen("PROGRAM " + args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # notice the space after the program
output = proc.communicate() # catch output
out =  output[0] # isolate stdout
err =  output[1] # isolate stderr

Traps for Cleanup Code

#import signal, traceback

# Called when sent SIGTERM, calls cleanup and exits
def kill_cleanup(a,b):
	cleanup()
	sys.exit()

# Term signal catching
signal.signal(signal.SIGTERM, kill_cleanup)
signal.signal(signal.SIGINT, kill_cleanup)

try:
	main()
except:
	traceback.print_exception(*sys.exc_info())
	cleanup()
	sys.exit()

Delete a directory recursively in python (helpful for cleanup)

# Delete a directory, recursively
def delete_dir(dir):
	items = os.listdir(dir)
	for item in items:
		if item == '.' or item == '..': continue
		file = dir + os.sep + item
		if os.path.isdir(file):
			# if this file is actually a dir, delete the dir
			delete_dir(file)
		else: # it's just a file
			print "Deleting " + file  
			os.remove(file)
	os.rmdir(dir)
Last modified 10 years ago Last modified on 08/19/08 14:29:08