如何判断Python程序是否有从stdin读取的内容?

编程入门 行业动态 更新时间:2024-10-26 06:25:38
本文介绍了如何判断Python程序是否有从stdin读取的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在用Python编写一个聊天程序,需要在接受来自sys.stdin的用户输入之前连接到服务器。如果无法建立连接,则程序退出。

I'm writing a chat program in Python that needs to connect to a server before user input from sys.stdin is accepted. If a connection cannot be made then the program exits.

从shell运行此命令,如果连接失败并且在尝试连接时发送了输入,则输入将回显到程序退出后的shell:

Running this from the shell, if a connection fails and input was sent while attempting to connect, the input is echoed to the shell after the program exits:

jtink@gab-dec:~$ python chat.py attempting to connect... Hey there! # This is user input How are you? # This is more user input connection failed jtink@gab-dec:~$ Hey there! Hey there!: command not found jtink@gab-dev:~$ How are you? How are you?: command not found jtink@gab-dev:~$

有没有办法判断sys.stdin上是否还有输入,以便我可以在聊天程序退出之前读取它?

Is there a way to tell if there is input left on sys.stdin, so that I can read it before the chat program exits?

我已阅读这个类似的问题,但答案只描述如何判断输入是否通过管道输入到python程序,而不是如何判断是否有输入。

I have read this similar question, but the answers only describe how to tell if input is being piped to a python program, not how to tell if there is input.

推荐答案

我认为你需要检查这个关于stdin 上的非阻塞I / O的问题在subprocess.PIPE上的非阻塞读取在python中

I think that you need to check this SO question about non-blocking I/O on stdin Non-blocking read on a subprocess.PIPE in python

更多推荐

如何判断Python程序是否有从stdin读取的内容?

本文发布于:2023-07-27 02:49:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何判断   程序   内容   Python   stdin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!