检测子进程何时等待 stdin

如何解决检测子进程何时等待 stdin

我正在制作一个能够运行任何可执行文件的终端程序(请忽略安全问题)。我需要检测子进程何时等待用户输入(来自 stdin)。我使用以下方法启动子进程:

process = subprocess.Popen(command,close_fds=False,shell=True,**file_descriptors)

我可以想到两种检测子进程是否在等待 stdin 的方法:

  • 写一个字符然后退格并检查子进程是否已经处理了这 2 个字节。但是 here 它说“CMD 确实支持退格键”。所以我需要找到一个字符,当打印到屏幕上时,它会删除命令提示符中 stdin 缓冲区中的内容。
  • 第二种方法是使用 pywin32 library 并使用 WaitForInputIdle 函数,如 here 所述。我查看了 subprocess 库的源代码,发现它使用 pywin32 并保留对进程句柄的引用。所以我尝试了这个:
win32event.WaitForInputIdle(proc._handle,100)

但是我收到了这个错误:

(1471,'WaitForInputIdle','Unable to finish the requested operation because the specified process is not a GUI process.')

同样在 windows api 文档 here 中它说:“WaitForInputIdle 只等待一次进程变为空闲;随后的 WaitForInputIdle 调用会立即返回,无论进程是空闲还是忙碌。 ”。我认为这意味着我不能多次使用该功能来解决我的问题

编辑: 这只需要在 Windows 上运行,但稍后我可能会尝试使我的程序也可以在 Linux 上计算。此外,我正在为 stdin/stdout/stderr 使用管道。

为什么我需要知道孩子是否在等待标准输入

目前,当用户按下 Enter 键时,我会将他们迄今为止写入的所有数据发送到 stdin 并禁止用户更改它。问题是当子进程正在睡眠/计算并且用户写入一些输入并希望在进程再次开始读取 stdin 之前对其进行更改。

基本上让我们来看看这个程序:

sleep(10)
input("Enter value:")

假设我输入了“abc\n”。使用 cmd 时,如果孩子还在睡觉,我可以按退格键并删除输入。目前,我的程序会在检测到“\n”并将其发送到 stdin 时将所有文本标记为只读。

解决方法

class STDINHandle:
    def __init__(self,read_handle,write_handle):
        self.handled_write = False
        self.working = Lock()
        self.write_handle = write_handle
        self.read_handle = read_handle

    def check_child_reading(self):
        with self.working:
            # Reset the flag
            self.handled_write = True
            # Write a character that cmd will ignore
            self.write_handle.write("\r")
            thread = Thread(target=self.try_read)
            thread.start()
            sleep(0.1)
            # We need to stop the other thread by giving it data to read
            if self.handled_write:
                # Writing only 1 "\r" fails for some reason.
                # For good measure we write 10 "\r"s
                self.write_handle.write("\r"*10)
                return True
            return False

    def try_read(self):
        data = self.read_handle.read(1)
        self.handled_write = False

    def write(self,text):
        self.write_handle.write(text)

我做了一些测试,我认为 cmd 会忽略 "\r" 字符。我找不到 cmd 将其解释为实际字符的情况(就像我执行 "\b" 时发生的情况)。发送 "\r" 字符并测试它是否留在管道中。如果它确实留在管道中,则意味着孩子尚未处理它。如果我们无法从管道中读取它,则意味着孩子已经处理了它。但是我们有一个问题——如果我们不能从 stdin 读取,我们需要停止读取,否则它会干扰下一次对 stdin 的写入。为此,我们将更多的 "\r" 写入管道。

注意:我可能需要更改 sleep(0.1) 行上的时间。

,

我不确定这是一个好的解决方案,但如果您有兴趣,可以尝试一下。我只是假设我们在给定 2 个输入 outputdata 的情况下为其 TIMEOUT 执行子进程。

process = subprocess.Popen(command,close_fds=False,shell=True,**file_descriptors)

try:
    output,_ = process.communicate(data,TIMEOUT)
except subprocess.TimeoutExpired:
    print("Timeout expires while waiting for a child process.")
    # Do whatever you want here

    return None

cmd_output = output.decode()

您可以找到 TimeoutExpired here 的更多示例。

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地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-