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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?