Skip to content

Instantly share code, notes, and snippets.

@wong2 wong2/gist:1318308
Created Oct 26, 2011

Embed
What would you like to do?
#-*-coding:utf-8-*-
from cmd import Cmd
import os
import atexit
from user import User
import getpwd
import sys
# ls
import stat
import time
import ctypes ### is_hidden函数里使用
# cp、mv
import shutil
# alais
import cPickle as pickle
# color
import colorama
class Pash(Cmd):
def __init__(self, user_name):
Cmd.__init__(self)
self.app_path = os.getcwd()
self.aliasDataPath = self.app_path + "/" + "aliasData"
self.intro = "Welcome to pash"
self.output = {"type":"", "value":[], "redirect":""}
self.changeUser(user_name)
colorama.init()
# 路径改变后,需要更新提示符
def updatePrompt(self):
self.current_path = os.getcwd()
self.current_path = self.current_path.replace("C:\\", "/")
self.prompt = "%s@SeedCup %s $ " % (self.user_name, self.current_path)
def changeUser(self, name):
self.user_name = name
self.do_cd("C:/") # 默认“C盘”为“/”
self.updatePrompt()
## Begin ##
### alias 从文件里读取 pickle 后 load
### 存储形式 {"wong2":{"ll":"ls -l", "catn":"cat -n"}, "HQM":{}}
f = open(self.aliasDataPath, "r")
self.aliasDataAll = pickle.load(f)
f.close()
self.aliasData = self.aliasDataAll[uname]
## End ##
# 用于高亮显示字(蓝色)
def printBlue(self, string):
print colorama.Fore.BLUE + string + colorama.Fore.RESET,
def printWhite(self, string):
print colorama.Fore.WHITE + string + colorama.Fore.RESET,
def printMagenta(self, string):
print colorama.Fore.MAGENTA + string + colorama.Fore.RESET,
# 如果输入的命令为空,则神马都不做
def emptyline(self):
pass
# 如果是未定义的命令, 提示之
def default(self, line):
print "unknown command: ", line, len(line)
### 用来判断文件(目录)是否为隐藏
# From : http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection
### Just 处理了一下 中文 问题
def is_hidden(self, filepath):
name = os.path.basename(os.path.abspath(filepath))
return name.startswith('.') or self.has_hidden_attribute(filepath)
def has_hidden_attribute(self, filepath):
try:
try:
ufilepath = unicode(filepath)
except UnicodeDecodeError:
ufilepath = unicode(filepath, "gb2312")
attrs = ctypes.windll.kernel32.GetFileAttributesW(ufilepath)
assert attrs != -1
result = bool(attrs & 2)
except (AttributeError, AssertionError):
result = False
return result
### 4.3.1 ls [path] (4’)
# 系统命令--ls
### 判断文件是否是隐藏文件夹还没搞定...
### 目录项以蓝色显示没搞定...
def do_ls(self, opt):
if opt =="":
opt = os.getcwd()
elif opt[0] == "/":
opt = "C:"+opt
else:
pass
isfile = os.path.exists(opt) # check opt is exist&file or not
if isfile:
lsValue = []
for filename in os.listdir(opt or "."):
if os.path.isdir(opt+"/"+filename):
lsValue.append("Y"+filename)
else:
lsValue.append("N"+filename)
self.output.update({
"type": "ls",
"value": lsValue
})
else:
if opt[:3] == "-l " or opt[:2] == "-l": # ls -l path # 一开始写成了 opt[:3] == "-l "
opt = opt[3:]
if opt == "":
opt = os.getcwd()
elif opt[1] == "/":
opt = "C:"+opt
else:
pass
isfile = os.path.exists(opt)
if isfile:
llValue = []
llValue.append("NName".ljust(18)+"Size(KB)".ljust(18)+"Last modified".ljust(18)+"Type".ljust(18))
for file in os.listdir((opt or ".")):
path = opt + "/" + file # path of files
if self.is_hidden(path):
pass
else:
if os.path.isdir(path):
llValue.append("Y"+file.ljust(18)+str(os.stat(path).st_size).ljust(18)+(str(time.localtime(os.stat(path).st_ctime).tm_year)+"/"+str(time.localtime(os.stat(path).st_ctime).tm_mon)+"/"+str(time.localtime(os.stat(path).st_ctime).tm_mday)).ljust(18)+("<DIR>".ljust(18) if os.path.isdir(file) else " "*18))
else:
llValue.append("N"+file.ljust(18)+str(os.stat(path).st_size).ljust(18)+(str(time.localtime(os.stat(path).st_ctime).tm_year)+"/"+str(time.localtime(os.stat(path).st_ctime).tm_mon)+"/"+str(time.localtime(os.stat(path).st_ctime).tm_mday)).ljust(18)+("<DIR>".ljust(18) if os.path.isdir(file) else " "*18))
self.output.update({
"type": "ls -l",
"value": llValue,
})
else:
print "The path input isn't exist!!!"
else:
print "The path input isn't exist!!!"
def complete_ls(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### cp+mv 的功能实现
# 提供给cp、mv调用
def cpmv(self, opt, flag):
canCP = True
argList = opt.split()
argNum = len(argList)
##判断源文件(目录)是否存在##
##目标文件(目录)可以不存在##
if argNum == 3 and argList[0] == "-r":
if os.path.exists(argList[1]):
sour = argList[1]
if argList[2][0] == "/":
dest = "C:"+argList[2]
else:
dest = argList[2]
elif argList[0][0] == "/" and os.path.exists("C:"+argList[1]):
sour = "C:"+argList[1]
if argList[2][0] == "/":
dest = "C:"+argList[2]
else:
dest = argList[2]
else:
canCP = False
print "Sour file or dir is not exist!!!" ### 源文件或目录不存在
return False
elif argNum == 2:
if os.path.exists(argList[0]):
if os.path.isdir(argList[0]): ### 没有 -r 命令, 则不能 cp 目录
canCP = False
if flag == "1":
print "No power to copy dir!!!"
else:
print "No power to move dir!!!"
return False
else:
sour = argList[0]
if argList[1][0] == "/":
dest = "C:"+argList[1]
else:
dest = argList[1]
elif argList[0][0] == "/" and os.path.exists("C:"+argList[0]):
if os.path.isdir("C:"+argList[0]): ### 没有 -r 命令, 则不能 cp 目录
canCP = False
if flag == "1":
print "No power to copy dir!!!"
else:
print "No power to move dir!!!"
return False
else:
sour = "C:"+argList[0]
if argList[1][0] == "/":
dest = "C:"+argList[1]
else:
dest = argList[1]
else:
canCP = False
print "Sour file or dir is not exist!!!" ### 源文件或目录不存在
return False
else:
print "Parameter is not correct!!!" ### 可以分的更细,没参数,目标问及那(目录)为空...etc
return False
if canCP:
##判断 源文件(目录) 目标文件/目录 的类型##
x, y = os.path.isfile(sour), os.path.isdir(dest) ### or os.path.exists(dest) ### 目录不存在也当成目录
##分别处理##
##
if (x, y) == (True, False): # sour为文件,dest为文件
if os.path.exists(dest):
if flag == "1":
choice = raw_input("already exist:1、替换 2、取消复制 3、复制但不替换")
else:
choice = raw_input("already exist:1、替换 2、取消移动 3、移动但不替换")
if choice == "1":
try:
if flag == "1":
shutil.copy(sour, dest)
else:
shutil.move(sour, dest)
except IOException:
print "没有权限"
elif choice == "2":
pass
elif choice == "3":
partList = dest.split(".") ###
destHead = ".".join(partList[:-1])
destTail = partList[-1]
i = 2
while destHead + "("+str(i)+")" + "." + destTail in fileList:
i += 1
try:
if flag == "1":
shutil.copy(sour, destHead + "("+str(i)+")" + "." + destTail)
else:
shutil.move(sour, destHead + "("+str(i)+")" + "." + destTail)
except IOException:
print "没有权限"
else:
try:
if flag == "1":
shutil.copy(sour, dest)
else:
shutil.move(sour, dest)
except IOException:
print "没有权限"
##
elif (x, y) == (True, True): # sour为文件,dest为目录
fileList = os.listdir(dest)
if sour in fileList:
if flag == "1":
choice = raw_input("already exist:1、替换 2、取消复制 3、复制但不替换")
else:
choice = raw_input("already exist:1、替换 2、取消移动 3、移动但不替换")
if choice == "1":
try:
if flag == "1":
shutil.copy(sour, dest+"/"+sour)
else:
shutil.move(sour, dest+"/"+sour)
except IOException:
print "没有权限"
elif choice == "2":
pass
elif choice == "3":
partList = sour.split(".") ###
sourHead = ".".join(partList[:-1])
sourTail = partList[-1]
i = 2
while sourHead + "("+str(i)+")" + "." +sourTail in fileList:
i += 1
try:
if flag == "1":
shutil.copy(sour, dest + "/" + sourHead + "("+str(i)+")" + "." +sourTail)
else:
shutil.move(sour, dest + "/" + sourHead + "("+str(i)+")" + "." +sourTail)
except IOException:
print "没有权限"
else:
pass
else: # 妹的,冒号搞成另一种了...
try:
if flag == "1":
shutil.copy(sour, dest)
else:
shutil.move(sour, dest)
except IOException:
print "没有权限"
##
elif (x, y) == (False, True): # sour为目录,dest为目录
dirName = (sour.split("/"))[-1]
if os.path.isdir(dest+"/"+dirName) == True: ### 如果源目录在目标目录中已经存在
if flag == "1":
choice = raw_input("already exist:1、合并目录 2、取消复制")
else:
choice = raw_input("already exist:1、合并目录 2、取消移动")
if choice == "1":
for roots, dirs, files in os.walk(sour):
for dirsName in dirs:
dirsPath = dest+"/"+dirName+"/"+roots[len(sour):]+"/"+dirsName
if os.path.exists(dirsPath):
pass
else:
if flag == "1":
shutil.copytree(sour+"/"+dirsName, dest+"/"+dirName+"/"+roots[len(sour):]+"/"+dirsName,False)
else:
shutil.move(sour+"/"+dirsName, dest+"/"+dirName+"/"+roots[len(sour):]+"/"+dirsName)
for filesName in files:
filesPath = dest+"/"+dirName+"/"+roots[len(sour):]+"/"+filesName
if os.path.exists(filesPath):
pass
else:
if flag == "1":
shutil.copy(sour+"/"+filesName, dest+"/"+dirName+"/"+roots[len(sour):]+"/"+filesName)
else:
shutil.move(sour+"/"+filesName, dest+"/"+dirName+"/"+roots[len(sour):]+"/"+filesName)
elif choice == "2":
pass
else:
pass
else:
try:
if flag == "1":
shutil.copytree(sour, dest+"/"+dirName,False)
else:
shutil.move(sour, dest+"/"+dirName)
except IOException:
print "没有权限"
else:
pass
### 4.3.2 cp [args] [sour] [desti] (3’)
# 系统命令--cp
### 用shutil模块中的copy、copytree
def do_cp(self, opt):
self.cpmv(opt, "1")
def complete_cp(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 4.3.3 mv [args] [sour] [desti] (3’)
# 系统命令--mv
### 首先cp,然后如果cp成功,则删掉sour
### 用shutil模块中的move、rmtree
def do_mv(self, opt):
optTemp = opt
argList = optTemp.split()
argNum = len(argList)
if argNum == 3 and argList[0] == "-r"\
and ((os.path.isdir(argList[1]) and not os.path.isdir(argList[2])) or (os.path.isdir("C:"+argList[1]) and not os.path.isdir("C:"+argList[2])))\
and "/".join(argList[2].split("/")[:-1])=="/".join(argList[1].split("/")[:-1]):
if argList[1][0] == "/":
shutil.move("C:"+argList[1], "C:"+argList[2])
else:
shutil.move(argList[1], argList[2])
else:
self.cpmv(opt, "2")
def complete_mv(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 4.3.4 mkdir [args] [dirpath] (3’)
# 系统命令--mkdir
def do_mkdir(self, opt):
if opt == "": ### 未输入参数(目录)
print "No Parameter or Dir!!!"
return False
## 不能在目录名称中出现的字符 ##
noList = ["\\", "/", ":", "*", "?", '', "<", ">", "|", "'", ";"]
## 有参数 -p ##
if opt[:3] == "-p ": ### 与 ls 中的 -l 的判断有不同之处
opt = opt[3:] ### 取出要创建的目录名称
#相对路径
flag = True
# 判断路径是否符合规则
if opt[0] == "/": ### 绝对路径
flag = False
argList = opt.split("/")
argList = argList[1:] # 可有可无
opt = "C:"+opt
else: ###相对路径
argList = opt.split("/")
argNum = len(argList)
for i in range(argNum): ### 对每一级目录进行判断
for j in range(len(noList)):
if noList[j] in argList[i]:
print "Dir Name is illegal!!!" ### 目录名称非法
return False
else:
pass
## 每一级目录名称都符合命名规范 ##
if flag == True:
tempPath = ""
else:
tempPath = "C:/"
for i in range(argNum): ### 对每一级目录进行mkdir
tempPath += argList[i]
if os.path.exists(tempPath) == False: ### 如果路径不存在,则新建,如果存在,在下一级
os.mkdir(tempPath)
tempPath += "/"
else:
tempPath += "/"
## 无参数 -p ##
else:
# 判断路径是否符合规则
if opt[0] == "/": ### 绝对路径
argList = opt.split("/")
argList = argList[1:] # 可有可无
opt = "C:"+opt
argNum = len(argList)
tempPath = "C:"
for i in range(argNum-1):
tempPath += "/"+argList[i]
if os.path.exists(tempPath) == False:
print "Path is not exist!!!"
return False
else: ###相对路径
argList = opt.split("/")
argNum = len(argList)
for i in range(argNum-1):
if os.path.exists(argList[i]) == False:
print "Path is not exist!!!"
return False
## 路径存在,判断目录名是否符合要求 ##
for i in range(len(noList)):
if noList[i] in argList[argNum-1]:
print "Dir Name is illegal!!!" ### 目录名称非法
return False
else:
pass
if os.path.exists(opt):
print "Dir is already exist!!!" ### 目录已经存在
return False
os.mkdir(opt)
def complete_mkdir(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 4.3.5 cd [dirpath] (3’)
# 切换目录
### 如果cd的是当前目录的话...
def do_cd(self, opt):
opt = opt or "/"
try:
os.chdir(opt)
except OSError as inst:
print inst[1], ": ", opt
self.updatePrompt()
def complete_cd(self, text, line, begidx, endidx):
text = line.split(None, 1)[1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 4.3.6 rm [args] [path] (3’)
# 系统命令--rm
### 要不要支持 rm -r filename ... 即带 -r 的可以删除文件不...
### 暂时没支持上面的,讨论一下决定...
def do_rm(self, opt):
if opt == "": ### 未输入参数(目录文件)
print "No Parameter or Dir!!!"
return False
## 有参数 -r ##
if opt[:3] == "-r ": ###
opt = opt[3:] ### 取出要删除的目录(文件)名称
if opt[0] == "/":
opt = "C:"+opt
else:
pass
if os.path.isdir(opt) == True:
## 递归删除 ##
if opt in os.getcwd():
print "上层目录,不给删的亲!!!"
return False
else:
shutil.rmtree(opt)
else:
# 等讨论之后决定怎么写, 是文件,还是不存在,是分开写,还是一起处理掉...
if os.path.exists(opt) == False:
print "不存在的..."
else:
pass
## 无参数 -r ##
else:
if opt[0] == "/":
opt = "C:"+opt
else:
pass
if os.path.isdir(opt) == False:
if os.path.exists(opt) == True:
os.remove(opt)
else:
print "File not exist!!!"
return False
else:
print "No power to del dir!!!"
return False
def complete_rm(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 4.3.7 cat [file] (4’)
# 系统命令--cat
def do_cat(self, opt):
if opt == "": ### 未输入参数(文件)
print "No Parameter!!!"
return False
## 有参数 -n ##
if opt[:3] == "-n ": ###
opt = opt[3:] ### 取出要删除的目录(文件)名称
if opt[0] == "/":
opt = "C:"+opt
else:
pass
if os.path.isfile(opt):
fstream = open(opt)
catValue = []
j = 1
for i in fstream:
catValue.append("0"*(4-len(str(j))) + str(j) + ":" + " "*2 + i)
j += 1
fstream.close()
self.output.update({
"type": "cat",
"value": catValue,
})
else:
print "No file!!!"
return False
## 无参数 -n ##
else:
if opt[0] == "/":
opt = "C:"+opt
else:
pass
if os.path.isfile(opt):
fstream = open(opt)
catValue = []
for i in fstream:
catValue.append(i)
fstream.close()
self.output.update({
"type": "cat",
"value": catValue,
})
else:
print "No file!!!"
return False
def complete_cat(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 4.3.8 alias [cmd1]=’[cmd2]’ (4’)
# 系统命令--alias
def do_alias(self, opt):
if opt == "":
print "No Parameter!!!"
return False
elif "=" not in opt:
print "Error Parameter!!!"
return False
else:
cmdList = opt.split("=")
for key in self.aliasDataAll[uname]:
if key == cmdList[0]:
print "The alias of %s already exsits, Cover it??? <Y/N>"
if raw_input() == "Y":
self.aliasDataAll[uname][cmdList[0]] = cmdList[1]
else:
pass
return
self.aliasDataAll[uname][cmdList[0]] = cmdList[1]
f = open(self.aliasDataPath, "w") ### 在这里打开为啥没print aliasData成功啊
pickle.dump(self.aliasDataAll, f)
f.close()
### 4.3.9 find [path] [args] (4’)
# 系统命令--find
def do_find(self, opt):
if opt == "" or opt == ".": ### "find" or "find ."
opt = os.getcwd()
length = len(opt)
findValue = []
for roots, dirs, files in os.walk(opt):
findValue.append("."+(roots[length:]).replace("\\", "/"))
for filespath in files:
findValue.append("."+((os.path.join(roots, filespath))[length:]).replace("\\", "/"))
self.output.update({
"type": "find",
"value": findValue,
})
## 有参数 ##
else:
argList = opt.split()
argNum = len(argList)
if argNum == 1:
if argList[0] == "/": ### "find /(filename)" or "find filename"
opt = "C:" + opt
else:
pass
if os.path.isdir(opt):
findValue = []
for roots, dirs, files in os.walk(opt):
findValue.append(roots.replace("\\", "/"))
for filespath in files:
findValue.append((os.path.join(roots, filespath)).replace("\\", "/"))
self.output.update({
"type": "find -name",
"value": findValue,
})
else:
flag = 0
if argNum == 2 and argList[0] == "-name": ### "find -name filename"
flag = 1
opt = os.getcwd()
aim = argList[1]
elif argNum == 3 and argList[1] == "-name":
if argList[0] == ".": ### "find . -name filename"
flag = 1
opt = os.getcwd()
aim = argList[2]
elif os.path.isdir(argList[0]) == True: ### "find sourfile -name filename"
flag = 2
opt = argList[0]
aim = argList[2]
elif (argList[0][0] == "/") and os.path.isdir("C:"+argList[0]): ### "find /(sourfile) -name filename"
opt = "C:"+argList[0]
aim = argList[2]
else:
print "Root dir is not exist!!!"
return False
else:
print "Command error!!!" ###参数个数不对 or 参数错误 -name
return False
length = len(opt)
findValue = []
for roots, dirs, files in os.walk(opt):
if aim in files:
if flag == 1:
#print (roots[length:]).replace("\\", "/")+"/"+aim
findValue.append((roots[length:]).replace("\\", "/")+"/"+aim)
elif flag == 2:
#print roots.replace("\\", "/")+"/"+aim
findValue.append(roots.replace("\\", "/")+"/"+aim)
else:
#print argList[0]+"/"+aim
findValue.append(argList[0]+"/"+aim)
else:
pass
self.output.update({
"type": "find -name",
"value": findValue,
})
def complete_find(self, text, line, begidx, endidx):
text = line.rsplit()[-1]
text = text if "/" in text else "./" + text
path, prefix = text.rsplit("/", 1)
return [name for name in os.listdir(path+"/")
if name.startswith(prefix)]
### 连续命令
def do_multi(self, cmds):
for cmd in cmds:
self.onecmd(cmd)
# 登出,返回登录界面
def do_logout(self, opt):
return True
# 退出程序, 关闭数据库连接
def do_exit(self, opt):
User.closeDB()
sys.exit()
def do_EOF(self, opt):
print
self.do_exit(opt)
def do_useradd(self, name):
if not name:
print "Usage: useradd [username]"
return
if not User.isValidUname(name):
print "user name should be 1-10 long, ",
print "contains only letters and numbers"
elif User.hasUser(name):
print "user name %s is already taken" % name
else:
pwd1 = getpwd.getpwd("password: ")
if User.isValidPwd(pwd1):
pwd2 = getpwd.getpwd("password again: ")
if pwd2 == pwd1:
User.addUser(name, pwd2)
print "%s has been created successfully!" % name
else:
print "password doesn't match"
else:
print "password should be 6-20 long, ",
print "contains only letters and numbers"
def do_passwd(self, name):
if not name:
print "Usage: passwd [username]"
return
if not User.hasUser(name):
print "no user %s" % name
else:
old_pwd = getpwd.getpwd("old password: ")
if User.isValidUser(name, old_pwd):
new_pwd1 = getpwd.getpwd("new password : ")
if User.isValidPwd(new_pwd1):
new_pwd2 = getpwd.getpwd("new password again: ")
if new_pwd2 == new_pwd1:
User.setPwd(name, new_pwd2)
print "password of %s changed successfully!" % name
else:
print "password doesn't match"
else:
print "password should be 6-20 long, ",
print "contains only letters and numbers"
else:
print "password for %s is not correct" % name
def do_su(self, name):
if not name:
print "Usage: su [username]"
return
if not User.hasUser(name):
print "no user %s" % name
elif name == self.user_name:
print "already logged in as %s" % name
else:
pwd = getpwd.getpwd("password for %s: " % name)
if User.isValidUser(name, pwd):
self.changeUser(name)
else:
print "password error"
def do_grep(self, opt):
try:
pattern, source = opt.split(None, 1)
except:
print "Usage: grep [pattern] [string]"
self.output = "\n".join([line for line in source.split("\n") if pattern in line])
def do_pipe(self, args):
buffer = None
for arg in args:
s = arg
if buffer:
# This command just adds the output of a previous command as the last argument
s += ' ' + buffer
self.onecmd(s)
buffer = self.output
def postcmd(self, stop, line):
type = self.output.get("type", "")
value = self.output.get("value", [])
rf = self.output.get("redirect", "")
self.output = {"type":"", "value":[], "redirect":""}
fp = open(rf, "w") if rf else sys.stdout
if type == "ls":
if rf:
for i, filename in enumerate(value):
fp.write(filename[1:] + " " if (i+1)%4 else "\n")
else:
fileList = value
for i in range(len(fileList)-1):
if fileList[i][0] == "Y":
self.printBlue(fileList[i][1:].ljust(18))
else:
self.printWhite(fileList[i][1:].ljust(18))
if (i+1)%4 == 0: # each line shows 4 files' name
print
if (i+1)%4: #如果不是正好4的倍数个,则,输出一个换行符
print
elif type == "ls -l":
if rf:
for i in range(len(value)):
value[i] = value[i][1:]
fp.write("\n".join(value))
else:
for fileInfo in value:
if fileInfo[0] == "Y":
self.printBlue(fileInfo[1:])
else:
self.printWhite(fileInfo[1:])
print
elif type in ["cat"]:
if rf:
fp.write("\n".join(value))
else:
print "\n".join(value)
elif type == "find":
if rf:
fp.write("\n".join(value))
else:
print "\n".join(value)
elif type == "find -name":
if rf:
fp.write("\n".join(value))
else:
for valueList in value:
pathList = valueList.rsplit("/", 1)
self.printWhite(pathList[0]+"/")
self.printMagenta(pathList[1])
print
else:
return stop
fp.write("\n")
if rf:
fp.close()
return stop
def aliasExchange(self, line):
command = line.split()[0]
for key in self.aliasData:
if key == command:
return line.replace(key, self.aliasData[key], 1)
return line
### 将对alias命令的处理加了进去,调用aliasExchange函数
def parseline(self, line):
cmds = line.split(";")
cmdList = []
for cmd in cmds:
if ">" in cmd:
cmd = self.aliasExchange(cmd)
cmd, self.output["redirect"] = [x.strip() for x in cmd.rsplit(">", 1)]
if "|" in cmd:
for i in cmd.split("|"):
cmdList.append(self.aliasExchange(cmd))
return "pipe", cmdList, cmd
#return "pipe", cmd.split("|"), cmd
else:
cmd = self.aliasExchange(cmd)
return Cmd.parseline(self, cmd)
#self.onecmd(cmd)
'''
def do_multi(self, cmds):
for cmd in cmds:
self.onecmd(cmd)
'''
if __name__ == "__main__":
can_login = False
while True:
uname = raw_input("username: ")
if uname == "guest":
can_login = True
elif not User.hasUser(uname):
print "no such user"
else:
password = getpwd.getpwd("password: ")
if not User.isValidUser(uname, password):
print "user name and password don't match"
else:
can_login = True
if can_login:
print "Login successfully! ",
pash = Pash(uname)
pash.cmdloop()
@HQMIS

This comment has been minimized.

Copy link

commented Nov 4, 2012

哇哇, 这个还记得, 哈哈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.