Using sys.stdin.readline() to read multiple lines from cmd in Python

后端 未结 3 440
醉话见心
醉话见心 2020-12-20 01:53

I\'d like to type in my input from command lines after running

if __name__ == \"__main__\":
    data = list(map(int, sys.stdin.readline().split()))
    print         


        
3条回答
  •  青春惊慌失措
    2020-12-20 02:17

    I agree with everything @Leva7 has said. Nonetheless, I'd suggest another solution, which is to use raw_input for Python 2 or input for Python 3 like so:

    args = []
    s = raw_input()                # input() for Python 3
    while s != '':
        args.extend([int(arg) for arg in s.strip().split()])
        s = raw_input()
    

    Of course, that's not a one-liner in any way, but it does the job and it's easy to see how it's done. Plus, no special characters are required at the end of the input.

提交回复
热议问题