【问题标题】:Python 2.7: read from stdin without promptingPython 2.7:从标准输入读取而不提示
【发布时间】:2015-03-28 18:19:31
【问题描述】:

我正在尝试制作一个 Arduino Yun 报警系统。它需要向我的 Web 服务器发出请求以更新其统计信息。它还需要监控一个按钮和一个运动传感器。 Linux 端正在运行一个将发出 Web 请求的 python 脚本。我需要让 Arduino 将其状态发送到 python 脚本。在 python 脚本中,我需要从 Arduino 端读取。我可以使用print raw_input() 做到这一点,但我希望它仅在有可用内容时读取,如果没有可用内容,我不希望它阻塞。例如:

import time
while 1:
    print "test"
    time.sleep(3)
    print raw_input()
    time.sleep(3)

如果我运行它,我希望它打印出来:

test

(6 seconds later)

test

代替

test
(Infinite wait until I type something in)

我尝试过线程,但它们有点难以使用。

【问题讨论】:

标签: python python-2.7 arduino stdin arduino-yun


【解决方案1】:

等待单行数据的简单解决方案。使用类似文件的sys.stdin 对象。

import sys

while True:
    print "Pre"
    sys.stdin.readline()
    print "Post"

【讨论】:

  • 很遗憾,这不起作用,因为脚本在执行 sys.stdin.readline() 时暂停。
【解决方案2】:

我看了 jakekimds 的评论,发现我可以这样做:

while 1:
    rlist,_,_=select([sys.stdin],[],[],0)
    content=""
    while rlist:
        content+=raw_input()
        rlist,_,_=select([sys.stdin],[],[],0)
    print "blocking task - content:"+content
    time.sleep(5)

这将:

  1. 如果标准输入中的内容可用,则将其存储在content
  2. 执行阻塞任务。
  3. 睡眠 5 秒。
  4. 返回步骤 1。

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 2018-07-26
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2019-12-05
    • 2013-03-30
    • 2012-02-17
    相关资源
    最近更新 更多