从 sys.stdin 获取输入,非阻塞 [英] Taking input from sys.stdin, non-blocking

查看:28
本文介绍了从 sys.stdin 获取输入,非阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个用于竞赛的机器人,它通过 sys.stdin 接收输入并使用 Python 的 print() 进行输出.我有以下几点:

I'm working on a bot for a competition that receives its input through sys.stdin and uses Python's print() for output. I have the following:

import sys

def main():
    while True:
        line = sys.stdin.readline()
        parts = line.split()
        if len(parts) > 0:
            # do stuff

问题是输入是通过流进入的,使用上面的方法会阻止我打印任何东西,直到流关闭.我该怎么做才能完成这项工作?

The problem is that the input comes in through a stream and using the above, blocks me from printing anything back until the stream is closed. What can I do to make this work?

推荐答案

通过关闭阻止,您一次只能读取一个字符.所以,没有办法让 readline() 在非阻塞上下文中工作.我假设您只想阅读按键来控制机器人.

By turning blocking off you can only read a character at a time. So, there is no way to get readline() to work in a non-blocking context. I assume you just want to read key presses to control the robot.

我在 Linux 上使用 select.select() 没有运气,并创建了一种调整 termios 设置的方法.所以,这是特定于 Linux 的,但对我有用:

I have had no luck using select.select() on Linux and created a way with tweaking termios settings. So, this is Linux specific but works for me:

import atexit, termios
import sys, os
import time


old_settings=None

def init_anykey():
   global old_settings
   old_settings = termios.tcgetattr(sys.stdin)
   new_settings = termios.tcgetattr(sys.stdin)
   new_settings[3] = new_settings[3] & ~(termios.ECHO | termios.ICANON) # lflags
   new_settings[6][termios.VMIN] = 0  # cc
   new_settings[6][termios.VTIME] = 0 # cc
   termios.tcsetattr(sys.stdin, termios.TCSADRAIN, new_settings)

@atexit.register
def term_anykey():
   global old_settings
   if old_settings:
      termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

def anykey():
   ch_set = []
   ch = os.read(sys.stdin.fileno(), 1)
   while ch != None and len(ch) > 0:
      ch_set.append( ord(ch[0]) )
      ch = os.read(sys.stdin.fileno(), 1)
   return ch_set;

init_anykey()
while True:
   key = anykey()
   if key != None:
      print key
   else:
      time.sleep(0.1)

更好的 Windows 或跨平台答案在这里:非阻塞控制台输入?

A better Windows or cross-platform answer is here: Non-blocking console input?

这篇关于从 sys.stdin 获取输入,非阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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