duannuo4620 2017-07-19 07:07
浏览 39
已采纳

在提示输入文本“ Enter input”之前,如何检查os.stdin

I have to promt for some input from os.stdin.How can I check this is available for reading before printing statements like "Enter your text" and then read from input.If stdin is not available it is printing bad file descriptor after "Enter your text". how to avoid this?

package main
import (
    "bufio"
    "os"
    "io"
    "fmt"
)
func main(){
consSource := NewConsoleAccessTokenSource("www.google.co.in", os.Stdin)
fmt.Print("Token: ")
    consSource.scanner.Scan()
    err := consSource.scanner.Err()
    if err != nil {
        fmt.Print(err)
    }
    fmt.Print(consSource.scanner.Text())
}
func NewConsoleAccessTokenSource(websiteUrl string, reader io.Reader) *ConsoleAccessTokenSource {
    s := &ConsoleAccessTokenSource{}
    s.WebsiteUrl = websiteUrl
    s.scanner = bufio.NewScanner(reader)
    return s
}
type ConsoleAccessTokenSource struct {
    WebsiteUrl string

    scanner *bufio.Scanner
}

This is what I am trying to do .when I run this program using "nohup executable" it is giving bad file descriptor.

  • 写回答

1条回答 默认 最新

  • doucha5080 2017-07-19 07:40
    关注

    os.Stdin is an exported variable of the os package, it is of type *os.File.

    You may call File.Stat() on it to see if it's available and also to get additional info about it (e.g. if it is being piped or its source is a terminal):

    if _, err := os.Stdin.Stat(); err != nil {
        fmt.Println("Stdin not available:", err)
    } else {
        fmt.Println("Stdin available.")
    }
    

    Let's see an example when it's not available. It won't be if we close it first e.g. with the File.Close() method:

    fmt.Println("Closing:", os.Stdin.Close())
    
    if _, err := os.Stdin.Stat(); err != nil {
        fmt.Println("Stdin not available:", err)
    } else {
        fmt.Println("Stdin available.")
    }
    

    Output (try it on the Go Playground):

    Stdin available.
    Closing: <nil>
    Stdin not available: stat /dev/stdin: Bad file number
    

    Also check related question: Check if there is something to read on STDIN in Golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?