From: Colin Patrick Mccabe Date: Sat, 5 May 2012 04:25:37 +0000 (-0700) Subject: pickrand.py: allow selecting from a set of files X-Git-Url: http://club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=98340bd6de4e28d1d75a25ecb6f9a72b2bb2082a;p=cmccabe-bin pickrand.py: allow selecting from a set of files Allow selecting from a set of files specified on the command line, rather than just all files in the current directory tree. Signed-off-by: Colin McCabe --- diff --git a/pickrand.py b/pickrand.py index 6340971..688460a 100755 --- a/pickrand.py +++ b/pickrand.py @@ -3,26 +3,29 @@ import os import random import sys +import time print_to_stderr = False +random.seed(os.getpid() + int(time.time())) + +file_name = None if (len(sys.argv) == 1): - pass + allfiles = [] + for root, dirs, files in os.walk("."): + for f in files: + allfiles.append(os.path.join(root, f)) + if (len(allfiles) == 0): + sys.exit(1) + r = random.randint(0,len(allfiles) - 1) + file_name = allfiles[r] elif (len(sys.argv) == 2) and (sys.argv[1] == "-S"): print_to_stderr = True else: - print >>sys.stderr, "invalid command-line arguments" - sys.exit(1) - -allfiles = [] + allfiles = sys.argv[1:] + r = random.randint(0,len(allfiles) - 1) + file_name = allfiles[r] -for root, dirs, files in os.walk("."): - for f in files: - allfiles.append(os.path.join(root, f)) -if (len(allfiles) == 0): - sys.exit(1) -random.seed(os.getpid()) -r = random.randint(0,len(allfiles) - 1) -print(allfiles[r]) +print(file_name) if (print_to_stderr): - print >>sys.stderr, (allfiles[r]) + print >>sys.stderr, file_name sys.exit(0)