import os
import sys
import platform
import signal
import readline
BUILTINS = { }
def cd(a):
home = os.getenv("HOME")
try:
if a: os.chdir(a[0].replace('~', home))
else: os.chdir(home)
return True
except Exception, e:
print(e.args[1])
return False
BUILTINS['cd'] = cd
def exit(a):
sys.exit()
BUILTINS['exit'] = exit
def alias(a):
if len(a) == 0: print(ALIASES)
elif len(a) >= 2: add_alias(a[0], " ".join(a[1:]))
else: print("Wrong number of arguments for `alias`")
BUILTINS['alias'] = alias
def source(a):
with open(a[0], 'r') as f:
for x in f:
execute(x.rstrip())
BUILTINS['source'] = source
ALIASES = { }
def add_alias( name, command ):
ALIASES[name] = command
def is_interactive():
return len(sys.argv) == 1
def prompt():
pwd = os.getcwd().split('/').pop()
return pwd + " $ "
def get_command( script ):
if script:
command = script.readline()
if command == "": sys.exit() return command
else: return raw_input(prompt())
def execute( command ):
argv = command.split(" ")
if argv[0] in ALIASES:
argv = ALIASES[argv[0]].split(" ") + argv[1:]
if argv[0] in BUILTINS:
return BUILTINS[argv.pop(0)](argv)
else:
return os.system(" ".join(argv)) == 0
def sigint_handler( signal, frame ):
print '\nExit this shell with `exit`'
sys.stdout.write(prompt())
if is_interactive(): signal.signal(signal.SIGINT, sigint_handler)
script = False if is_interactive() else open(sys.argv[1], 'r')
def completer( text, state ):
incomplete = text.split('/').pop()
path = text.strip(incomplete)
r_path = '.' if path == "" else path
r_path = r_path.replace("~", os.getenv("HOME"))
matches = [f for f in os.listdir(r_path) if f.startswith(incomplete)]
if state < len(matches): return path + matches[state]
else: return None
readline.set_completer(completer)
readline.set_completer_delims(' ')
if platform.system() == "Darwin":
readline.parse_and_bind("bind ^I rl_complete")
elif platform.system() == "Linux":
readline.parse_and_bind("tab: complete")
try: source(["./profile.myshell"])
except IOError: print 'No profile.myshell file found in current directory'
while True: execute(get_command(script))