如果输入很少,如何使用raw_input()运行While True循环?

时间:2016-02-25 03:06:13

标签: python loops raw-input

我目前正在开发一个项目,我需要通过Serial持久发送数据,但需要偶尔根据新输入更改数据。我的问题是我的当前循环仅在raw_input()提供新输入时才起作用。在收到另一个raw_input()之前,没有任何内容会再次运行。

我当前(非常瘦的)循环看起来像这样:

while True:
    foo = raw_input()
    print(foo)

我希望不管发生变化的频率如何,都要不断打印(或传递给其他函数)。

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

select(或在Python 3.4 +,selectors)模块中,您可以在不进行线程的情况下解决此问题,同时仍然执行定期更新。

基本上,您只需编写正常循环,但使用select确定新输入是否可用,如果可用,请抓住它:

import select

while True:
    # Polls for availability of data on stdin without blocking
    if select.select((sys.stdin,), (), (), 0)[0]:
        foo = raw_input()
    print(foo)

如上所述,print远比你想要的要多得多;您可以在每个time.sleep之后print,或将超时参数更改为select.select到0以外的值;例如,如果您将其设为1,那么您将在新数据可用时立即更新,否则,您将在放弃并再次打印旧数据之前等待一秒钟。

答案 1 :(得分:0)

如何在打印数据的同时输入数据?

但是,如果您确保数据源不会干扰数据输出,则可以使用多线程。

import thread

def give_output():
    while True:
        pass  # output stuff here

def get_input():
    while True:
        pass  # get input here

thread.start_new_thread(give_output, ())
thread.start_new_thread(get_input, ())

您的数据来源可能是另一个程序。您可以使用文件或套接字连接它们。