【问题标题】:Interact with an interactive shell script on python在 python 上与交互式 shell 脚本交互
【发布时间】:2016-05-29 05:31:27
【问题描述】:

我在 Windows 上有一个交互式 shell 应用程序。 我想编写一个 python 脚本,它将命令发送到该 shell 应用程序并读回响应。 但是我想以交互方式进行,即我希望 shell 应用程序在 python 脚本运行时一直运行。

我试过了

self.m_process subprocess.Popen(path_to_shell_app,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)

然后使用标准输入和标准输出来发送和接收数据。 似乎正在打开 shell 应用程序,但我无法与之通信。

我做错了什么?

【问题讨论】:

  • 你可能想看看 subprocess.PIPE 是什么意思
  • 如何使用标准输入/标准输出?文档说:Warning 使用communicate() 而不是.stdin.write、.stdout.read 或.stderr.read 以避免由于任何其他操作系统管道而导致的死锁缓冲区填满并阻塞子进程。

标签: python interactive-shell


【解决方案1】:

有一个专门为此而构建的模块:pexpect。要使用import pexpect,然后使用process = pexpect.spawn(myprogram) 创建新的子流程,然后使用process.expect(mystring)process.expect_exact(mystring) 搜索提示或获取响应。 process.send(myinput)process.sendline(myinput) 用于向子进程发送信息。

【讨论】:

    【解决方案2】:

    接下来你应该使用communicate

    stdout, stderr = self.m_process.communicate(input=your_input_here)
    

    来自subprocess 模块文档

    Popen.communicate(input=None)
    与进程交互:将数据发送到标准输入。从 stdout 和 stderr 读取数据,直到到达文件结尾。 等待进程终止。可选的输入参数应该是 要发送到子进程的字符串,如果不应该有数据,则为 None 发送给孩子。

    communicate() 返回一个元组 (stdoutdata, stderrdata)。

    注意,如果你想向进程的标准输入发送数据,你需要 使用 stdin=PIPE 创建 Popen 对象。同样,得到任何东西 除了结果元组中的 None 之外,您需要给出 stdout=PIPE 和/或 stderr=PIPE。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2015-06-29
      • 2023-03-09
      • 2011-08-31
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多