【问题标题】:Python terminal emulator: Cannot use "cd" command.Python 终端模拟器:无法使用“cd”命令。
【发布时间】: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 pty module
  • 也许你的意思是shell而不是终端模拟器?您在终端仿真器中运行并让这段代码更能运行诸如“cd”之类的东西不会让它更接近终端仿真器。
  • cd 始终是 shell 内置命令。它在文件系统中不存在。没有这样的可执行文件。

标签: python bash terminal


【解决方案1】:

当您打开一个新进程时,您会更改新进程的当前目录,而不是调用进程。您应该改用os.chdir 来更改程序的目录。所以你需要解析命令行并检查命令是否为cd,然后决定不调用Popen,而是改为os.chdir

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2015-05-29
    • 2018-09-20
    • 2013-08-25
    • 2018-12-28
    相关资源
    最近更新 更多