-3
我发现这个代码片段在线为python终端模拟器,我认为它看起来很酷,所以我继续前进,并试图使用它。我注意到我无法使用“cd”命令,我被困在我运行该文件的目录中。为什么?这是怎么回事?我怎样才能修改这段代码使它像一个完美的本地终端一样运行?我对编程还很陌生,在我的生活中只使用了子进程模块。请帮忙!Python终端模拟器:不能使用“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捕获什么错误? –
如果你想创建一个*真实的*终端模拟器,你需要使用['pty'模块](https://docs.python.org/3/library/pty.html)。 – icktoofay
也许你的意思是shell而不是终端模拟器?你正在运行终端模拟器,并使得这段代码更能够运行诸如'cd'之类的东西,不会让它更接近终端模拟器。 – pvg