[翻譯] 使用 Python 建立你自己的 Shell:Part II

來源:互聯網
上載者:User

標籤:內建函數   gis   hash   映射   調用   避免   著作權   html   imp   

使用 Python 建立你自己的 Shell:Part II

[TOC]

原文連結與說明
  1. https://hackercollider.com/articles/2016/07/06/create-your-own-shell-in-python-part-2/
  2. 本翻譯文檔原文選題自 Linux中國 ,翻譯文檔著作權歸屬 Linux中國 所有

在 part 1 中,我們已經建立了一個主要的 shell 迴圈、切分了的命令輸入,以及通過 forkexec 執行命令。在這部分,我們將會解決剩下的問題。首先,cd test_dir2 命令無法修改我們的目前的目錄。其次,我們仍無法優雅地從 shell 中退出。

步驟 4:內建命令

“cd test_dir2 無法修改我們的目前的目錄” 這句話是對的,但在某種意義上也是錯的。在執行完該命令之後,我們仍然處在同一目錄,從這個意義上講,它是對的。然而,目錄實際上已經被修改,只不過它是在子進程中被修改。

還記得我們 fork 了一個子進程,然後執行命令,執行命令的過程沒有發生在父進程上。結果是我們只是改變了子進程的目前的目錄,而不是父進程的目錄。

然後子進程退出,而父進程在原封不動的目錄下繼續運行。

因此,這類與 shell 自己相關的命令必須是內建命令。它必須在 shell 進程中執行而沒有分叉(forking)。

cd

讓我們從 cd 命令開始。

我們首先建立一個 builtins 目錄。每一個內建命令都會被放進這個目錄中。

yosh_project|-- yosh   |-- builtins   |   |-- __init__.py   |   |-- cd.py   |-- __init__.py   |-- shell.py

cd.py 中,我們通過使用系統調用 os.chdir 實現自己的 cd 命令。

import osfrom yosh.constants import *def cd(args):    os.chdir(args[0])    return SHELL_STATUS_RUN

注意,我們會從內建函數返回 shell 的運行狀態。所以,為了能夠在項目中繼續使用常量,我們將它們移至 yosh/constants.py

yosh_project|-- yosh   |-- builtins   |   |-- __init__.py   |   |-- cd.py   |-- __init__.py   |-- constants.py   |-- shell.py

constants.py 中,我們將狀態常量都放在這裡。

SHELL_STATUS_STOP = 0SHELL_STATUS_RUN = 1

現在,我們的內建 cd 已經準備好了。讓我們修改 shell.py 來處理這些內建函數。

...# Import constantsfrom yosh.constants import *# Hash map to store built-in function name and reference as key and valuebuilt_in_cmds = {}def tokenize(string):    return shlex.split(string)def execute(cmd_tokens):    # Extract command name and arguments from tokens    cmd_name = cmd_tokens[0]    cmd_args = cmd_tokens[1:]    # If the command is a built-in command, invoke its function with arguments    if cmd_name in built_in_cmds:        return built_in_cmds[cmd_name](cmd_args)    ...

我們使用一個 python 字典變數 built_in_cmds 作為雜湊映射(hash map),以儲存我們的內建函數。我們在 execute 函數中提取命令的名字和參數。如果該命令在我們的雜湊映射中,則調用對應的內建函數。

(提示:built_in_cmds[cmd_name] 返回能直接使用參數調用的函數引用的。)

我們差不多準備好使用內建的 cd 函數了。最後一步是將 cd 函數添加到 built_in_cmds 映射中。

...# Import all built-in function referencesfrom yosh.builtins import *...# Register a built-in function to built-in command hash mapdef register_command(name, func):    built_in_cmds[name] = func# Register all built-in commands heredef init():    register_command("cd", cd)def main():    # Init shell before starting the main loop    init()    shell_loop()

我們定義了 register_command 函數,以添加一個內建函數到我們內建的命令雜湊映射。接著,我們定義 init 函數並且在這裡註冊內建的 cd 函數。

注意這行 register_command("cd", cd) 。第一個參數為命令的名字。第二個參數為一個函數引用。為了能夠讓第二個參數 cd 引用到 yosh/builtins/cd.py 中的 cd 函數引用,我們必須將以下這行代碼放在 yosh/builtins/__init__.py 檔案中。

from yosh.builtins.cd import *

因此,在 yosh/shell.py 中,當我們從 yosh.builtins 匯入 * 時,我們可以得到已經通過 yosh.builtins 匯入的 cd 函數引用。

我們已經準備好了代碼。讓我們嘗試在 yosh 同級目錄下以模組形式運行我們的 shell,python -m yosh.shell

現在,cd 命令可以正確修改我們的 shell 目錄了,同時非內建命令仍然可以工作。非常好!

exit

最後一塊終於來了:優雅地退出。

我們需要一個可以修改 shell 狀態為 SHELL_STATUS_STOP 的函數。這樣,shell 迴圈可以自然地結束,shell 將到達終點而退出。

cd 一樣,如果我們在子進程中 fork 和執行 exit 函數,其對父進程是不起作用的。因此,exit 函數需要成為一個 shell 內建函數。

讓我們從這開始:在 builtins 目錄下建立一個名為 exit.py 的新檔案。

yosh_project|-- yosh   |-- builtins   |   |-- __init__.py   |   |-- cd.py   |   |-- exit.py   |-- __init__.py   |-- constants.py   |-- shell.py

exit.py 定義了一個 exit 函數,該函數僅僅返回一個可以退出主迴圈的狀態。

from yosh.constants import *def exit(args):    return SHELL_STATUS_STOP

然後,我們匯入位於 yosh/builtins/__init__.py 檔案的 exit 函數引用。

from yosh.builtins.cd import *from yosh.builtins.exit import *

最後,我們在 shell.py 中的 init() 函數註冊 exit 命令。

...# Register all built-in commands heredef init():    register_command("cd", cd)    register_command("exit", exit)...

到此為止!

嘗試執行 python -m yosh.shell。現在你可以輸入 exit 優雅地退出程式了。

最後的想法

我希望你能像我一樣享受建立 yoshyour own shell)的過程。但我的 yosh 版本仍處於早期階段。我沒有處理一些會使 shell 崩潰的極端狀況。還有很多我沒有覆蓋的內建命令。為了提高效能,一些非內建命令也可以實現為內建命令(避免新進程建立時間)。同時,大量的功能還沒有實現(請看 公用特性 和 不同特性)

我已經在 github.com/supasate/yosh 中提供了原始碼。請隨意 fork 和嘗試。

現在該是建立你真正自己擁有的 Shell 的時候了。

Happy Coding!

via: https://hackercollider.com/articles/2016/07/06/create-your-own-shell-in-python-part-2/

[翻譯] 使用 Python 建立你自己的 Shell:Part II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.