您的位置:首页 > 运维架构 > Shell

Python利用OS模块模拟一个shell

2016-09-30 08:50 441 查看
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)<
4000
/span>:
'''
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))


运行效果



当然,真的很简陋啦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: