python - Python交互式shell在子进程中运行时不响应输入
问题描述
我正在制作一个终端命令行界面程序作为更大项目的一部分。我希望用户能够运行任意命令(如在 cmd 中)。问题是,当我使用 启动python
进程时subprocess
,python 不会向stdout
. 我什至不确定它是否读到我写的内容stdin
。这是我的代码:
from os import pipe, read, write
from subprocess import Popen
from time import sleep
# Create the stdin/stdout pipes
out_read_pipe_fd, out_write_pipe_fd = pipe()
in_read_pipe_fd, in_write_pipe_fd = pipe()
# Start the process
proc = Popen("python", stdin=in_read_pipe_fd, stdout=out_write_pipe_fd,
close_fds=True, shell=True)
# Make sure the process started
sleep(2)
# Write stuff to stdin
write(in_write_pipe_fd, b"print(\"hello world\")\n")
# Read all of the data written to stdout 1 byte at a time
print("Reading:")
while True:
print(repr(read(out_read_pipe_fd, 1)))
当我更改为由 MinGW 编译的用 C++ 编写的 hello world 程序在哪里时,上面的"python"
代码有效"myexe.exe"
。myexe.exe
为什么会这样?这是完整的代码,但上面的示例显示了我的问题。当我更改"python"
为"cmd"
.
PS:当我python
从命令提示符运行时,它给了我:
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
这意味着应该有东西写入stdout
.
解决方案
问题
请注意,您将 python 连接到非 tty 标准输入,因此它的行为与您python
在终端中运行命令时的行为不同。相反,它的行为就像您使用了 command 一样cat script | python
,这意味着它会等到 stdin 关闭,然后将所有内容作为单个脚本执行。文档中描述了此行为:
解释器的操作有点像 Unix shell:当使用连接到 tty 设备的标准输入调用时,它以交互方式读取和执行命令;当使用文件名参数或文件作为标准输入调用时,它会从该文件读取并执行脚本。
在阅读之前尝试添加close(in_write_pipe_fd)
,您会看到它成功了。
解决方案1:强制python交互运行
为了解决您的问题,我们需要 python 来忽略它不是交互式运行的事实。运行时,python --help
您可能会注意到标志-i
:
-i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x
听起来不错 :) 只需将您的Popen
电话更改为:
Popen("python -i", stdin=in_read_pipe_fd, stdout=out_write_pipe_fd,
close_fds=True, shell=True)
东西应该开始按预期工作。
解决方案2:伪装成终端
您可能听说过pty
,一种伪终端设备。这是一些操作系统中的一个功能,它允许您将管道连接到 tty 驱动程序而不是终端仿真器,因此,在您的情况下,允许您自己编写终端仿真器。您可以使用 python 模块pty
打开一个并将其连接到子进程而不是普通管道。这将欺骗 python 认为它连接到一个实际的 tty 设备,并且还允许您模拟 Ctrl-C 按下、向上箭头/向下箭头等。
但这是有代价的——一些程序在连接到 tty 时,也会相应地改变它们的输出。例如,在许多 linux 发行版中,该grep
命令会为输出中的匹配模式着色。如果您不确定您可以在程序中正确处理颜色,或者配置 tty 以声明它不支持颜色(和其他 tty 功能),您将开始在某些命令的输出中得到垃圾。
小笔记
我确实觉得这可能不是实现目标的最佳方法。如果您更详细地描述它,我也许可以帮助您考虑替代方案:)
推荐阅读
- html - 如何在 ReactJS 中动态选择要渲染的元素
- c++ - GPU 上的 BFCAllocator 真的支持在 GPU 执行之前进行主机端释放吗?
- bootstrap-modal - Laravel 5.8 将 HTML 文本从数据库解析为模态
- triggers - 创建在特定列更新后插入数据的触发器
- python-3.x - 在 Python 中建立一个模拟数据库以进行单元测试
- javascript - JavaScript:从全局函数返回的多个变量不能被对象访问
- oracle-apex - Oracle APEX - 区域显示选择器 - 选择特定选项卡
- cron - 使用 cron 运行 ansible-playbook
- java - 401 Malformed HTTP basic Authorization header: Error on execution api through RestTemplate
- apache-kafka - Kafka - 并非所有消费者都会收到订阅的消息