如何判断Python程序是否有从stdin读取的内容? [英] How can you tell if a Python program has anything to read from stdin?

查看:336
本文介绍了如何判断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?

我已阅读< a href =https://stackoverflow.com/questions/699390/whats-the-best-way-to-tell-if-a-python-program-has-anything-to-read-from-stdin>这个类似的问题,但答案只描述如何判断输入是否通过管道输入到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读取的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆