/silverlining/mgr-scripts/run-command.py
Python | 88 lines | 73 code | 9 blank | 6 comment | 24 complexity | 0b37dc1b977b6c89cbf3a53f37248c1e MD5 | raw file
1#!/usr/bin/env python 2import sys 3sys.path.insert(0, '/usr/local/share/silverlining/lib') 4import os 5from silversupport import appdata 6from silversupport.appconfig import AppConfig 7 8 9def main(): 10 args = sys.argv[1:] 11 hostname, path = appdata.normalize_location(args[0]) 12 tmp_dir = args[1] 13 command = args[2] 14 rest = args[3:] 15 instance_name = appdata.instance_for_location(hostname, path) 16 if not instance_name: 17 print 'No instance found attached to %s%s' % (hostname, path) 18 return 1 19 app_config = AppConfig.from_instance_name(instance_name) 20 21 if tmp_dir and tmp_dir != 'NONE': 22 rest = [ 23 r.replace('$TMP', tmp_dir) 24 for r in rest] 25 path = find_command_path(app_config.app_dir, command) 26 check_command_python(path) 27 os.environ['SILVER_VERSION'] = 'silverlining/0.0' 28 app_config.activate_services() 29 app_config.activate_path() 30 # Buffering can happen because this isn't obviously hooked up to a 31 # terminal (even though it is indirectly): 32 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 33 sys.argv = [path] + rest 34 os.chdir(app_config.app_dir) 35 ns = {'__file__': path, '__name__': '__main__'} 36 if os.path.basename(path) == 'ipython': 37 ## ipython-specific hack 38 if not os.access(os.environ['HOME'], os.W_OK): 39 os.environ['HOME'] = '/tmp' 40 os.chdir(app_config.app_dir) 41 if os.path.basename(path) in ('python', 'python2.6'): 42 from code import InteractiveConsole 43 console = InteractiveConsole() 44 console.interact() 45 else: 46 execfile(path, ns) 47 48 49def find_command_path(app_dir, command_name): 50 if command_name.startswith(os.path.sep): 51 # Absolute path 52 return command_name 53 places = [os.path.join(app_dir, 'bin'), 54 app_dir, 55 '/bin', 56 '/usr/bin'] 57 for place in places: 58 place = os.path.join(place, command_name) 59 if os.path.exists(place): 60 return place 61 print >> sys.stderr, ( 62 "%s not found (looked in %s)" 63 % (command_name, ', '.join(places))) 64 sys.exit(1000) 65 66 67def check_command_python(path): 68 if path.endswith('.py'): 69 # Good enough 70 return 71 if path.endswith('python') or path.endswith('python2.6'): 72 return 73 fp = open(path) 74 first = fp.readline() 75 fp.close() 76 if not first.startswith('#!'): 77 print >> sys.stderr, ( 78 "Not a #! script: %s" % path) 79 sys.exit(1001) 80 if not 'python' in first: 81 print >> sys.stderr, ( 82 "#! line in script is not for Python (%s): %s" 83 % (first.strip(), path)) 84 sys.exit(1001) 85 86 87if __name__ == '__main__': 88 sys.exit(main())