#!/usr/bin/env python

import sys, optparse, json

def run_command():    
    if len(sys.argv) < 2:
        print 'Usage: ./run.py <command>'
        sys.exit()
    command = sys.argv[1]
    
    try:
        parent_mod = __import__('regscrape_lib.commands', fromlist=[command])
        mod = getattr(parent_mod, command)
    except ImportError:
        print 'No such command: %s' % command
        sys.exit()
    
    if getattr(mod, 'GEVENT', True):
        from gevent.monkey import patch_all
        patch_all()

    run = getattr(mod, 'run', False)
    if not run or not callable(run):
        print 'Command %s is not runnable' % command
        sys.exit()
    
    parser = getattr(mod, 'arg_parser', None)
    parser_defined = parser is not None
    
    if not parser:
        parser = optparse.OptionParser()
    parser.add_option('--parsable', dest='parsable', action='store_true', default=False, help='Output JSON instead of human-readable messages.')
    parse_results = parser.parse_args(sys.argv[2:])
    
    if parse_results[0].parsable:
        # disable standard output by monkey-patching sys.stdout
        dev_null = open('/dev/null', 'w')
        real_stdout = sys.stdout
        sys.stdout = dev_null
    
    from regscrape_lib.util import bootstrap_settings
    bootstrap_settings()
    
    out = run(*(parse_results if parser_defined else []))
    
    if parse_results[0].parsable:
        # turn stdout back on so we can print output
        sys.stdout = real_stdout
        # but disable stderr so we can avoid that stupid gevent thing
        sys.stderr = dev_null
        
        if out:
            print json.dumps(out)

@@ -193,13 +193,325 @@
     
-try:%0A
+if command.endswith('.py'):%0A        mod_name = command.split('/').pop().rsplit('.', 1)%5B0%5D%0A        import imp%0A        try:%0A            mod = imp.load_source(mod_name, command)%0A        except ImportError:%0A            print 'Could not load custom command: %25s' %25 command%0A            sys.exit()%0A    else:%0A        try:%0A    
     
@@ -588,24 +588,28 @@
 d%5D)%0A        
+    
 mod = getatt
@@ -631,24 +631,28 @@
 ommand)%0A    
+  
+  
 except Impor
@@ -651,32 +651,36 @@
 pt ImportError:%0A
+    
         print 'N
@@ -701,32 +701,36 @@
 : %25s' %25 command%0A
+    
         sys.exit
@@ -1339,24 +1339,62 @@
 v%5B2:%5D)%0A    %0A
+    dev_null = open('/dev/null', 'w')%0A
     if parse
@@ -1483,50 +1483,8 @@
 out%0A
-        dev_null = open('/dev/null', 'w')%0A
     
@@ -1826,28 +1826,105 @@
     
-# but disable stderr
+%0A        if out:%0A            print json.dumps(out)%0A    %0A    # no matter what, nuke stderr on exit
  so 
@@ -1961,20 +1961,16 @@
 t thing%0A
-    
     sys.
@@ -1991,63 +1991,4 @@
 ull%0A
-        %0A        if out:%0A            print json.dumps(out)%0A

Add support for running one-off scripts via the regscrape infrastructure.