Python利用OS模块模拟一个shell

os模块是Python标准库中很有用的一个模块,因为它和操作系统打交道,封装了很多操作系统提供的功能。闲来无事,就利用os模块写了个tiny shell,就当做模块的练习。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import getpass
import re
copyright="""
        ####################################################
        #          This shell is created by ji!            #                             
        #              ©copyright  2016-                   # 
        #          do whatever u want to do!               #                          
        ####################################################
        """


def rm_file(filename):
    '''
    args: rm file1 file2
    '''
    if os.path.isfile(filename):
        try:
            os.remove(filename)
        except:
            args_error(command[0],"cannt remove "+ filename +" :Permission denied")       


def rm_dir(dirname):
    '''
    args: rm dir if dir is empty or not ,will warn.
    '''
    if os.path.isdir(dirname):
        try:
            os.removedirs(dirname)
        except:
            answer = input(dirname+ " is not an empty dirname.Are u sure?(y/n)")
            if answer == 'n':
                return
            else:
                file_list = os.listdir(dirname)
                os.chdir(dirname)
                for subfile in file_list:

                    if os.path.isfile(subfile):
                        rm_file(subfile)
                    else:
                        rm_dir(subfile)
                os.chdir("..")
            rm_dir(dirname)                 

def args_error(command, msg):
    '''
    if args is not correct ,shell will go here
    '''
    print(command+":"+msg)


def command_error( cmd):
    '''
    if cmd  is not supported in jish, shell will go here
    '''
    print(cmd+":command not found")


class mkdir_class:
    '''
    args:mkdir a dir
    '''
    def __call__(self,commands):
        if len(commands) !=2 :
            args_error(commands[0]," usage:mkdir dir!")
        if os.path.isdir(commands[1]):
            args_error(commands[0]," dir  exists'")
        else:
            os.mkdir(commands[1])        

class cd_class:
    '''
    args:change u env
    '''
    def __call__(self,commands):
        if len(commands) !=2 :
            args_error(commands[0]," usage:cd dir!")
        if os.path.isdir(commands[1]):
            os.chdir(commands[1])
        else:
            args_error(commands[0]," dir does't exist'")        

class cat_class:
    def __call__(self, commands):
        if len(commands) < 2:
            args_error(commands[0]," usage:cat file!")
            return
        if os.path.isfile(commands[1]):
            with open(commands[1],"r") as f:
                for line in f:
                    print(line,end="")


class echo_class:
    def __call__(self,commands):
        for line in commands[1:]:
            print(line)


class ls_class:
    """
    args:commands must be a list like this  ['ls','-x','-x','path']
    function: show the file  in the path
    """
    def __call__(self, commands):
        path = os.getcwd() if len(commands) < 2 else commands[-1]

        if os.path.exists(path) :
            for file in os.listdir(path):
                print(file,end=" ")
            print()
        else : 
            args_error(commands[0],path+" doesnt exists")

class pwd_class:
    """
    args: commands = pwd
    function: show the dir u are in
    """
    def __call__(self, commands):
        print( os.getcwd() )


class touch_class:
    """
    args: commands = touch file1 file2
    function: it will create the files ,if file exists ,it will ignore and show show warings; 
    """
    def __call__(self,commands):
        if len(commands) < 2:
            args_error(command[0] +"usage: touch  file1 file2 ...")
        else:
            for file in commands[1:len(commands)]:
                if os.path.isfile(file):
                    print("file "+file+ " is exists")
                else:
                    with open(file,'w+') as _:
                        pass           


class rm_class:
    def __call__(self,commands):
        """
        args: rm  file1 file2 file3 or rm  dir1 dir2 dir3
        function: if dir is not empty,it will warning 
        """
        if len(commands) < 2:
            args_error(commands[0] +"usage: rm  file1 file2 |dir1 dir2 ...")
        else:
            for file in commands[1:len(commands)]:
                if os.path.isdir(file):
                    rm_dir(file)
                else:
                    rm_file(file)


command_line=""      #  for storing the command from UserWarning
command_function={ 'ls': ls_class,
                    'pwd':pwd_class,
                    'touch':touch_class,
                    'rm':rm_class,
                    'echo':echo_class,
                    'cat':cat_class,
                     'cd':cd_class,
                     'mkdir':mkdir_class}


def main():
    print(copyright)
    while True:
        command_line = input(getpass.getuser()+'$')
        commands = re.split(r'\s+',command_line)    #strip the "" and TabError 

        if commands[0]  in command_function:        #call the  function of the commands
            command_function[commands[0]]()( commands)
        else:
            command_error(commands[0])      



if __name__ == '__main__':
    import sys
    sys.exit(int(main() or 0))

运行效果
这里写图片描述

当然,真的很简陋啦。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值