# -*- python -*- # hello world # print a simple string on stdout print "Hello World" # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) import sys; print sys.argv[1] # env # access environment variable import os; print os.environ["HOME"] # test file exists # return exit code error (non zero) if a file does not exist import os, sys sys.exit(not os.path.exists("/etc/mtab")) # test file readable # return exit code error (non zero) if a file is not readable import sys try: open("/etc/mtab") except: sys.exit(1) # formatting # print integers in a simple formatted string a=1; b=2; print a, '+', b ,'=', a + b # system # call an external program and check the return value import os, sys if os.system("false"): sys.stderr.write("false failed\n") os.system("echo done") # sed in place # remove #-comments from a file (modifying the file, i.e. in place) import fileinput, re for s in fileinput.input(inplace = 1): print re.sub("#.*", "", s), # compile what must be # find and compile .c files into .o when the .o is old or absent from os import * from fnmatch import * for dir, _, files in walk('.'): for f in filter(files, '*.c'): c = path.join(dir, f) o = c[0:-2] + '.o' if not path.exists(o) or stat(c)[9] > stat(o)[9]: print 'compiling', c, 'to', o system("gcc -c -o '%s' '%s'" % (o, c)) # grep # grep with -F -i -h handling, usage, grep'ing many files import getopt, sys, fileinput, re opts, args = getopt.getopt(sys.argv[1:], 'hiF') opts = [ x[0] for x in opts ] if not args or '-h' in opts: print >> sys.stderr, "usage: grep [-F] [-i] regexp [files...]" sys.exit(1) r, files = args[0], args[1:] if '-F' in opts: r = re.sub("\W", lambda i: "\\" + i.group(0), r) if '-i' in opts: re = re.compile(r, re.I) else: re = re.compile(r) for s in fileinput.input(files): prefix = "" if len(files) > 1: prefix = fileinput.filename() + ":" if re.search(s): print prefix + s,