在某些受管制的环境下,若用户在Shell终端一段时间后无操作则Shell会自动退出。针对此问题实现python套壳shell,作为区别于bash的进程运行。代码如下:
#!/usr/local/bin/python3
#应将#!后替换为实际python3路径
import readline
import os
def execCmd(cmd):
r = os.popen(cmd)
text = r.read()
r.close()
return text
while True:
pwd=os.getcwd()
command=input(f"[pyshell:{pwd}]")
if(command.strip()=="quit"):
break
if(command.startswith("cd")):
command_parts=command.split()
if(command_parts[0]=="cd" and len(command_parts)==2):
try:
os.chdir(command_parts[1])
except Exception as error:
print(error)
else:
os.system(command)
else:
os.system(command)
缺点:命令自动补全功能,ls罗列的文件名无法按照分类显示不同样式。