import sys
import os
import re
import getpass
# os.name 操作系统平台 Windows:'nt'|Linux/Unix:'posix'。
# os.getenv()/os.putenv()读取和设置环境变量。
# os.system()函数用来运行shell命令。
# os.linesep 行终止符 Windows:'\r\n'|Linux:'\n'|Mac:'\r'
# os.path.split() 返回目录名和文件名的tuple
# sys.argv 命令行参数
# sys.platform 获得操作系统类型
# sys.exit(n) 终止程序
# sys.path 搜索模块的路径
# sys.modules 已载入模块
# sys.stdin,sys.stdout,sys.stderr 标准输入/输出/错误输出
# sys.version_info 得到python的版本信息
def os_sys_test():
print('os.name: ' + os.name)
print('$PATH: ' + os.getenv('PATH'))
print('os.linesep: ' + os.linesep)
print('filename: ' + sys.argv[0])
print('platform: ' + sys.platform)
print(sys.path)
#print(sys.modules)
print(sys.version_info)
def shell():
#os_sys_test()
heading = '''
#########################################
# welcome to hakase shell #
# ©copyright 2016 #
#########################################
'''
print(heading)
while True:
inputCmd = re.split('\s+', input(getpass.getuser() + '@' + os.getcwd() + '$ '))
cmd = inputCmd[0]
args = inputCmd[1:]
if cmd in cmdList:
cmdList[cmd](args)
def fun_rm(args):
for path in args:
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
lst = os.listdir(path)
os.chdir(path)
fun_rm(lst)
os.chdir('..')
os.removedirs(path)
def fun_echo(args):
for str in args:
print(str, end=' ')
print()
def fun_cat(args):
for file in args:
with open(file, 'r') as f:
for line in f:
print(line)
def fun_ls(args):
if len(args) == 0:
for file in os.listdir('.'):
print(file)
else:
for path in args:
for file in os.listdir(path):
print(file)
def fun_mkdir(args):
for dir in args:
if os.path.exists(dir):
print(dir + ' exist !')
else:
os.mkdir(dir)
def fun_cd(args):
for path in args:
os.chdir(path)
def fun_pwd(args):
print(os.getcwd())
def fun_exit(args):
exit(0)
def fun_touch(args):
for file in args:
if os.path.exists(file):
print(file + ' exist !')
pass
else:
with open(file, 'w') as f:
pass
def fun_clear(args):
os.system('clear')
cmdList = {
'echo' : fun_echo,
'exit' : fun_exit,
'cat' : fun_cat,
'ls' : fun_ls,
'cd' : fun_cd,
'pwd' : fun_pwd,
'touch': fun_touch,
'mkdir': fun_mkdir,
'rm' : fun_rm,
'clear': fun_clear
};
if __name__ == '__main__':
shell()
最简单的方法 只实现shell内部命令 外部命令直接使用外部shell来执行 在Window平台上当然运行不起来..
import os, getpass, re
def fun_cd(args):
for path in args:
os.chdir(path)
def fun_echo(args):
for str in args:
print(str, end=' ')
print()
def fun_exit(args):
exit(0)
cmdList = {
'echo' : fun_echo,
'exit' : fun_exit,
'cd' : fun_cd
};
while True:
cmdLine = input(getpass.getuser() + '@' + os.getcwd() + '$ ')
cmd = re.split('\s+', cmdLine)
if cmd[0] in cmdList:
cmdList[cmd[0]](cmd[1:])
else:
os.system(cmdLine)