Last active
July 28, 2019 05:40
-
-
Save youknowcast/f16d9402916eaa616dc7f17287280856 to your computer and use it in GitHub Desktop.
challenge3-3
This file contains 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
import sys | |
import os | |
import subprocess | |
current = os.path.dirname(os.path.abspath(__file__)) | |
def builtin_method(opt, piped_ret): | |
global current | |
opt_arr = opt.split() | |
first = opt.split()[0] | |
if first == 'cd': | |
if len(opt_arr) == 1: | |
target_path = '~' | |
else: | |
target_path = opt_arr[1] | |
if os.path.exists(target_path) is False: | |
print('invalid path: {}'.format(target_path)) | |
return True, None | |
if os.path.isfile(target_path): | |
print('file path is specified: {}'.format(target_path)) | |
return True, None | |
current = os.path.abspath(target_path) | |
os.chdir(target_path) | |
return True, None | |
elif first == 'echo': | |
txt = opt[5:] | |
return True, txt | |
elif first == 'pwd': | |
return True, current | |
elif first == 'exit': | |
exit(-1) | |
else: | |
return False, None | |
while True: | |
cmd = input('mysh> ') | |
if cmd == '': | |
continue | |
pipe_arr = cmd.split('|') | |
last = "" | |
pipe_idx = 0 | |
for c in pipe_arr: | |
prev_ret = last | |
if type(last) is bytes: | |
prev_ret = last.decode('utf8') | |
builtin, ret = builtin_method(pipe_arr[pipe_idx], prev_ret) | |
if builtin is True: | |
last = ret | |
else: | |
proc = subprocess.Popen(pipe_arr[pipe_idx], | |
shell=True, | |
stdin=subprocess.PIPE, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE) | |
proc_std, proc_err = proc.communicate(last) | |
last = proc_std | |
pipe_idx += 1 | |
if type(last) is bytes: | |
ret = last.decode('utf8').strip() | |
if ret is not None: | |
print(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment