【发布时间】:2023-03-14 12:57:01
【问题描述】:
我在网上找到了这个 python 终端模拟器的代码 sn-p,我觉得它看起来很酷,所以我继续尝试使用它。我注意到我无法使用“cd”命令,我被困在运行文件的目录中。这是为什么?这是怎么回事?以及如何修改此代码以使其像完美的本机终端一样运行?我对编程还是很陌生,一生中只玩过一次子流程模块。请帮忙!
import subprocess
import re
while True:
# prevents lots of python error output
try:
s = raw_input('> ')
except:
break
# check if you should exit
if s.strip().lower() == 'exit':
break
# try to run command
try:
cmd = subprocess.Popen(re.split(r'\s+', s), stdout=subprocess.PIPE)
cmd_out = cmd.stdout.read()
# Process output
print cmd_out
except OSError:
print 'Invalid command'
【问题讨论】:
-
因为你需要使用 os.chdir 来改变目录,改变进程的目录是没有效果的,你为什么要使用 re 来分割空白,你从 raw_input 捕获了什么错误?
-
如果你想制作一个真正的终端模拟器,你需要使用the
ptymodule。 -
也许你的意思是shell而不是终端模拟器?您在终端仿真器中运行并让这段代码更能运行诸如“cd”之类的东西不会让它更接近终端仿真器。
-
cd始终是 shell 内置命令。它在文件系统中不存在。没有这样的可执行文件。