# coding=utf-8
import os,socket,getpass,time
def main():
print('欢迎使用模拟linux shell (v1.0)')
username = getpass.getuser() # 获取当前用户名
hostname = socket.gethostname() # 获取当前主机名
while True:
cwd=os.getcwd()
lastpathname=os.path.basename(cwd)
try:
cmd=input('%s@%s ~%s $'%(username,hostname,lastpathname))
except:
print('\n谢谢使用shell')
exit(0)
l=cmd.split(' ')
cmd=l[0]
args=l[1:]
if cmd=='help':
help()
elif cmd=='cd':
try:
os.chdir(args[0])
except:
print('找不到指定的路径')
elif cmd=='ls':
print(cwd)
listdir(cwd)
elif cmd=='pwd':
print(cwd)
elif cmd=='cp':
copyfile(args[0],args[1])
elif cmd=='mv':
if os.path.exists(args[1]):
print('[%s] 已经存在,不能继续操作'%args[1])
else:
try:
os.rename(args[0],args[1])
except BaseException as e:
print(e)
else:
print('未知命令')
print()
def help():
print('pwd\t显示当前目录')
print('ls\t列出当前目录下的文件信息')
print('cd\t切换目录')
print('cp\t切换目录复制文件')
print('mv\t移动文件或改名。例子:mv 文件名 新路径\文件名')
def listdir(path):
l=os.listdir(path)
for item in l:
mtime=os.path.getmtime(item)
mtime=timestamp2time(mtime)
filesize=getfilesize(item)
isdir=' '
if os.path.isdir(item):
isdir='<DIR>'
print(mtime,' ',filesize,' \t',isdir,'\t',item,sep='')
def timestamp2time(timestamp):
t = time.localtime(timestamp)
return time.strftime('%Y-%m-%d %H:%M',t)
def getfilesize(filePath):
'''返回文件大小,没有精确计算,是约数'''
fsize = os.path.getsize(filePath)
re=''
if fsize<1024:
re='%s B'% fsize
elif fsize<1024*1024:
re='%s KB'% (fsize//1024)
elif fsize<1024*1024*1024:
re='%s MB'% (fsize//(1024*1024))
elif fsize<1024*1024*1024*1024:
re='%s GB'% (fsize//(1024*1024*1024))
# fsize = fsize/float(1024*1024)
return re
def copyfile(srcname,targetname):
if os.path.exists(targetname):
print('[%s] 已经存在,不能继续操作'%targetname)
return
with open(srcname,'rb') as sf,open(targetname,'wb') as tf:
data=sf.read(1024*64)
while data:
tf.write(data)
data=sf.read(1024*64)
if __name__ == "__main__":
main()
原文出处:/show_1EF30jOS6jgC.html