py实现一个shell

@

ref

我们要实现的一个 shell 类似物

参考了:

https://linux.cn/article-7624-1.html

https://zcfy.cc/article/create-your-own-shell-in-python-part-ii

git hub code :

https://github.com/supasate/yosh/blob/master/yosh/shell.py

notes

在这里插入图片描述

code

在这里插入图片描述

shell.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import shlex
import os

from buildins import *

build_in_cmds = {}

def register_command(name, func):
    build_in_cmds[name] = func

def init():
    register_command("cd", cd)
    register_command("exit", exit)



def shell_loop():
    # start the loop here
    status = SHELL_STATUS_RUN

    while status == SHELL_STATUS_RUN:
        ## show the prompt
        sys.stdout.write('F9500(PE)>')
        sys.stdout.flush()

        # 读取命令输入
        cmd = sys.stdin.readline()
        # 切分 命令
        cmd_tokens = tokenize(cmd)

        # 执行这个切分好的命令
        status = execute(cmd_tokens)

# 魔法切割一行命令
def tokenize(string):
    return shlex.split(string)

# 执行 execute
def execute(cmd_tokens):
    if cmd_tokens:
        cmd_name = cmd_tokens[0]
        cmd_args = cmd_tokens[1:]

        if cmd_name in build_in_cmds:
            return build_in_cmds[cmd_name](cmd_args)

    if cmd_tokens[0] == 'createinterface':
        print "F9500 create a new interface for you"
        
    return SHELL_STATUS_RUN

def main():
    init()
    shell_loop()


if __name__ == '__main__':
    main()

buildin

在这里插入图片描述

在这里插入图片描述
文本,从左到右:代码如下:

from cd import *
from exit import *


---

import os

SHELL_STATUS_STOP = 0
SHELL_STATUS_RUN = 1
HISTORY_PATH = os.path.expanduser('~') + os.sep + '.yosh_history'

---


from constants import *

def exit(args):
    return SHELL_STATUS_STOP


----

import os
from constants import *


def cd(args):
    if len(args) > 0:
        os.chdir(args[0])
    else:
        os.chdir(os.getenv('HOME'))
    return SHELL_STATUS_RUN

猜你喜欢

转载自www.cnblogs.com/paulkg12/p/12450406.html
今日推荐