Standard input with time limit

You've probably written a program and once wanted to create a standard input with a time limit. By the way, I don't. Since it was easily realized with Go, I will write a memo. It's for me someday.

Method

The method is very simple, just create a subroutine that receives standard input and receive the input text on the channel.

in := make(chan string, 1)
go func() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	in <- sc.Text()
}()

This can be easily achieved by combining the above channel with time.NewTimer or time.NewTicker.

timer := time.NewTimer(time.Second * 10)
select {
  case text := <-in:
    //Processing using input
  case <-timer.C:
    //Processing at the time of timeout
}

Appropriately made sample

This is a sample made by the above method. You can get a feel for it by running it locally.

package main

import (
	"bufio"
	"fmt"
	"os"
	"time"
)

func main() {
	in := make(chan string, 1)
	go func() {
		sc := bufio.NewScanner(os.Stdin)
		sc.Scan()
		in <- sc.Text()
	}()

	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	fmt.Println("The time limit is 5 seconds. Enter the author of the boy")
	for i := 0; i < 5; i++ {
		select {
		case text := <-in:
			if text == "Natsume Soseki" {
				fmt.Printf("It's amazing to be able to enter\n")
			} else {
				fmt.Printf("I'm wrong\n%s\n", text)
			}
			i = 5
		case <-ticker.C:
			switch i {
			case 0:
				fmt.Println("There is a time limit, so be quick")
			case 1:
				fmt.Println("quickly quickly")
			case 2:
				fmt.Println("Do you think it's in the way?")
			case 3:
				fmt.Println("I agree with you")
			case 4:
				fmt.Println("Game over(Lol)")
			}
		}
	}
}

Tightening

It was easy, but when will you use it?

Recommended Posts

Standard input with time limit
Matrix representation with Python standard input
[Python] Standard input
Standard input summary
Japanese input with pyautogui
[Python] About standard input
Standard input / output summary
Get standard output in real time with Python subprocess
Write standard input in code
[Python3] Standard input [Cheat sheet]
Test standard output with Pytest
Part 1 of receiving standard input
[For beginners] Summary of standard input in Python (with explanation)
Python3 standard input (competition pro)
Standard input / summary / python, ruby
Receiving standard input tips @ python
Execution time measurement with Python With
[For AtCoder] Standard input memo
Time synchronization (Windows) with Python
Python3 standard input for competitive programming
Easy time series prediction with Prophet
Get negative reaction time with psychopy.event.getKeys ()
Input / output with Python (Python learning memo ⑤)
Comply with Python coding standard PEP8
RPC completed with standard Python3 modules
Getting Started with CPU Steal Time
How to store CSV data in Amazon Kinesis Streams with standard input