Last active
January 4, 2019 05:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
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