Python: Accept user input at any time

2019-07-03 22:39发布

问题:

I am creating a unit that will do a number of things, one of them counting cycles of a machine. While I will be transferring this over to ladder logic (CoDeSys), I am putting my ideas into Python first.

I will have a count running, with just a simple

    counter += 1
    print("counter")

to keep track of what cycle I'm on. However, I want to be able to reset this count at any time, preferably by typing "RESET" I understand how to use the input command,

    check = input()

however, I do not know how to let the program run while it is searching for an input, or whether or not this is possible at all. Thank you in advance for any answer.

If it helps to understand, here is the code. The big gap is where the problem is. http://pastebin.com/TZDsa4U4

回答1:

If you only want to signal a reset of the counter, you can catch KeyboardInterrupt exception.

while True:
    counter = 0
    try:
        while True:
            counter += 1
            print("counter")
    except KeyboardInterrupt:
        pass


标签: python input