Skip to content

Instantly share code, notes, and snippets.

@sevagh
Created November 30, 2019 05:41
Show Gist options
  • Save sevagh/a63ad5ecd9a40805ab23bc7f4bc8e23a to your computer and use it in GitHub Desktop.
Save sevagh/a63ad5ecd9a40805ab23bc7f4bc8e23a to your computer and use it in GitHub Desktop.
Golfed shell in Python 3.6
#!/usr/bin/env python3.6
import sys, os, signal, readline
signal.signal(signal.SIGINT, signal.default_int_handler)
P = {'pid': ['state', 'ppid', 'name'], os.getpid(): ['0', os.getppid(), sys.argv[0]]}
W = {'worm-ps': lambda _: [print(f"{k}\t{v[1]}\t{v[0]}\t{' '.join(v[2:])}") for k, v in P.items()],
'worm-kill': lambda a: os.kill(int(a[1]), int(a[2])) if len(a) == 3 else print('usage: worm-kill pid sig', file=sys.stderr),
'worm-history': lambda _: print('\n'.join([(readline.get_history_item(i)) for i in range(readline.get_current_history_length()) if readline.get_history_item(i)])),
'worm-help': lambda _: print('available commands:\n' + '\n'.join(W.keys()))}
def completer(t, s):
try: return [x for x in W.keys() if x.startswith(t)][s]
except IndexError: return None
readline.set_completer(completer); readline.set_completer_delims(''); readline.parse_and_bind('tab: complete')
def _fork_exec_wait(exec_f, args, bg=False):
pid = os.fork()
if pid == 0: exec_f(args[0], args)
P[pid] = [os.waitpid(pid, (os.P_NOWAIT if bg==True else 0))[1], os.getpid()] + args
if __name__ == '__main__':
while True:
try:
args = input('_/\__/\__0> ').split(); bg = False
if not args: continue
if args[-1][-1] == '&': bg = True; args[-1] = args[-1][:-1]
if args[0] in W.keys(): W[args[0]](args)
elif args[0].split('/')[1:]: _fork_exec_wait(os.execv, args, bg)
else: _fork_exec_wait(os.execvp, args, bg) if any(args[0] in fs for p in os.environ['PATH'].split(':') for _, _, fs in os.walk(p)) else print(f"{args[0]} not found", file=sys.stderr)
except KeyboardInterrupt: print(); continue
except EOFError: print(); sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment