How do you read from stdin?

后端 未结 22 2594
余生分开走
余生分开走 2020-11-21 06:46

I\'m trying to do some of the code golf challenges, but they all require the input to be taken from stdin. How do I get that in Python?

22条回答
  •  悲&欢浪女
    2020-11-21 07:17

    I use the following method, it returns a string from stdin (I use it for json parsing). It works with pipe and prompt on Windows (not tested on Linux yet). When prompting, two line breaks indicate end of input.

    def get_from_stdin():
    
      lb = 0
      stdin = ''
    
      for line in sys.stdin:
        if line == "\n":
            lb += 1
            if lb == 2:
                break
        else:
            lb = 0
            stdin += line
    
      return stdin
    

提交回复
热议问题