Python交互式shell在子进程中运行时不响应输入 小笔记

如何解决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)))

当我将 "python" 更改为 "myexe.exe" 时,上面的代码有效,其中 myexe.exe 是我用 C++ 编写的 hello world 程序,由 MinGW 编译。为什么会发生这种情况? This 是完整代码,但上面的示例显示了我的问题。当我将 "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 时不同。相反,它的行为就像您使用命令 cat script | python 一样,这意味着它会等到 stdin 关闭,然后将所有内容作为单个脚本执行。此行为在 docs 中描述:

解释器的操作有点像 Unix shell:当被调用时 使用连接到 tty 设备的标准输入,它读取并执行 交互式命令;当使用文件名参数或使用 一个文件作为标准输入,它从中读取并执行一个脚本 文件。

在阅读前尝试添加 close(in_write_pipe_fd),您会看到它成功。

方案一:强制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)

一切都应该按预期开始工作。

方案二:伪装成终端

您可能听说过 pty,一种伪终端设备。它是一些操作系统中的一项功能,允许您将管道连接到 tty 驱动程序而不是终端模拟器,因此,在您的情况下,允许您自己编写终端模拟器。您可以使用 python 模块 pty 打开一个并将其连接到子进程而不是普通管道。这将诱使 python 认为它已连接到实际的 tty 设备,并且还允许您模拟 Ctrl-C 按下、向上箭头/向下箭头等。

但是这是有代价的——一些程序在连接到 tty 时,也会相应地改变它们的输出。例如,在许多 linux 发行版中,grep 命令在输出中为匹配的模式着色。如果你不能确保你可以在你的程序中正确处理颜色,或者配置 tty 以声明它不支持颜色(和其他 tty 功能),你将开始在某些命令的输出中得到垃圾。

小笔记

我确实觉得这可能不是实现目标的最佳方法。如果您更详细地描述它,我可能会帮助您想到替代方法:)

,

python 解释器比交互模式更常用于从命令行运行脚本,因此它的交互元素不会写入 stdout 否则它们会干扰脚本输出。没有人愿意从脚本输出中删除介绍性文本。

为方便起见,在与用户交互时,解释器使用 sys.displayhook 方法有意将输出发送到 stdout,否则不会发送到 stdout。其余部分(例如介绍文本和 >>> 提示)根据 the docs 写入 stderr

  • stdin 用于所有交互式输入(包括对 input() 的调用);
  • stdout用于print()和表达式语句的输出以及input()的提示;
  • 解释器自己的提示及其错误消息会转到 stderr。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res