Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hltbra
Last active January 4, 2019 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hltbra/aaf0d86d0c0938fa3494f13ed1f96f90 to your computer and use it in GitHub Desktop.
Save hltbra/aaf0d86d0c0938fa3494f13ed1f96f90 to your computer and use it in GitHub Desktop.
Basic implementation of a shell in Python. This is from a talk I gave at YipitData on August 29, 2018.
# REPL
# read, eval, print, loop program
import os
import subprocess
import shlex
import sys
last_returncode = 0
try:
while True:
# read
command = raw_input("> ")
command_args = []
for arg in shlex.split(command):
if arg.startswith('$'):
env_var = arg[1:]
if env_var in os.environ:
command_args.append(os.environ.get[env_var])
else:
command_args.append(arg)
if command == 'EXIT':
sys.exit(0)
elif command == 'EXITCODE':
print(last_returncode)
continue
elif command == 'PWD':
print(os.getcwd())
continue
elif command_args[0] == 'CD':
os.chdir(command_args[1])
continue
# eval
proc = subprocess.Popen(
command_args,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr)
# print
stdout, stderr = proc.communicate()
last_returncode = proc.returncode
# loop
except (KeyboardInterrupt, EOFError):
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment