如何在脚本中打印值时不断等待用户输入? [英] How to constantly wait for user input while printing values in a script?

查看:76
本文介绍了如何在脚本中打印值时不断等待用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些值的python脚本,这些值每秒在终端上打印一次.但是我的脚本应该始终等待用户输入,并依赖于输入来更改脚本中的变量.

I have a python script with some values, which are printed on the terminal for every second. But my script should be always waiting for users input and depend on input change the variables in the script.

现在,我有以下代码用于每秒打印一次值.我希望此脚本在后台不断等待用户输入,并取决于输入更改floor的值.

Now I have the following code for just printing value every second. I want this script to constantly wait for user input in the background and depends on input change the value of floor.

import argparse
import sys
import time

def createParser ():
    parser = argparse.ArgumentParser()
    parser.add_argument ('-floor', '--floor')

    return parser

parser = createParser()
namespace = parser.parse_args(sys.argv[1:])

def main():
  floor = namespace.floor
  while True:
    print(floor)
    time.sleep(1)
main()

推荐答案

在这种情况下,您不需要多线程.您希望等待最多一秒钟的输入,然后如果用户输入了任何内容,则更新floor变量.最好的工具是selectselectors模块中可用的I/O复用.

You don't need multithreading in this situation. You want to wait for input for up to one second, and then update the floor variable if anything was put in by the user. The best tool for something like this is the I/O multiplexing available in the select or selectors modules.

例如:

import sys
import select
floor = 0.0
timeout = 1.0
while True:
    rlist, wlist, xlist = select.select([sys.stdin], [], [], timeout)
    if len(rlist):
        floor = float(sys.stdin.readline().rstrip('\n'))
        print('New value received.')
    print(floor)

但是我应该指出,这不是令人愉快的用户体验.这些值会不断打印,这意味着用户的输入和输出在控制台中混合在一起.这不会影响程序的运行方式,因为stdinstdout是独立的流.当输出被同时打印时,这只会使用户难以正确输入一个值.

But I should point out that this is not a pleasant user experience. The values are constantly being printed, meaning that the user's input and the outputs are mixed together in the console. This doesn't affect how the program runs, since stdin and stdout are separate streams. It just makes it hard for the user to correctly input a value as the outputs are being printed simultaneously.

您确定需要不断打印吗?仅等待用户输入一个值,然后在收到该值时打印该值,这会更有用吗?在这种情况下,您甚至不需要select模块,只需等待使用sys.stdin.readline()进行输入即可.

Are you sure that you need to constantly print? Might it be more useful to just wait for the user to put in a value, and then print that when it's received? In this case, you don't even need the select module, just wait for input with sys.stdin.readline().

这篇关于如何在脚本中打印值时不断等待用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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