使用Python编写的SH命令行解释器
发布时间:2024-01-19 20:52:21
以下是一个使用Python编写的SH命令行解释器的示例代码:
import os
import subprocess
def run_command(command):
try:
output = subprocess.check_output(command, shell=True)
print(output.decode("utf-8"))
except subprocess.CalledProcessError as e:
print(e.output.decode("utf-8"))
def cd_command(args):
try:
os.chdir(args[0])
except FileNotFoundError:
print("Directory not found: " + args[0])
def main():
while True:
command = input("$ ")
command = command.strip()
if command.lower() == "exit":
break
elif command.lower().startswith("cd "):
args = command.split(" ")[1:]
cd_command(args)
else:
run_command(command)
if __name__ == "__main__":
main()
在这个示例中,我们定义了一个run_command函数来执行输入的命令,并打印出结果。如果命令执行失败,会打印出错误信息。
cd_command函数用于改变工作目录。它接收一个参数,即目标目录的路径,并使用os.chdir函数来实现目录的切换。如果目标目录不存在,会打印出错误信息。
main函数是程序的主入口,它通过一个无限循环来接收用户的命令输入。如果用户输入的命令是"exit",则退出循环,结束程序。如果用户输入的命令以"cd "开头,则调用cd_command函数来执行切换目录操作。否则,将用户输入的命令传给run_command函数来执行。
使用示例:
$ python sh_interpreter.py $ ls file1.txt file2.txt dir1 dir2 $ cd dir1 $ ls subdir1 subdir2 $ cd subdir1 $ ls file3.txt file4.txt $ cd .. $ cd dir2 $ ls file5.txt file6.txt $ exit
在这个示例中,我们首先执行ls命令来列出当前目录的文件和子目录。然后我们使用cd dir1命令切换到dir1目录,并使用ls命令来列出dir1目录的内容。接着我们进入subdir1目录,再次使用ls命令来列出其内容。然后我们返回上一级目录,并切换到dir2目录,使用ls命令列出其内容。最后我们输入"exit"命令,退出程序。
