Paging output from print statement

后端 未结 3 1968
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 02:52

I\'m essentially trying to achieve this:

>>>print \"SOME_VERY_LONG_TEXT\" | more

Of course, it doesn\'t work in Python 2.7(IDLE).

相关标签:
3条回答
  • Writing something terminal and os independent might be a bigger task.

    But if you can get the height of the terminal then you can use something like this this Assuming your input is a generator/list of line seperated text, or else you can call text.split('\n') before calling this function

    def pagetext(text_lined, num_lines=25):
       for index,line in enumerate(text_lined):
           if index % num_lines == 0 and index:
               input=raw_input("Hit any key to continue press q to quit")
               if input.lower() == 'q':
                   break
           else:
               print line
    

    Also there is a pager module on pypy haven't used it but the author says it was supposed to be included in the standard library.

    0 讨论(0)
  • 2021-01-04 03:08

    You could call it as an external process. (You have to be careful with shell=True, though.)

    import subprocess
    longStr = 'lots of text here'
    subprocess.call(['echo "'+longStr+'" | more'], shell=True)
    
    0 讨论(0)
  • 2021-01-04 03:23

    Although a bit late, the following worked for me:

    def less(data):
        process = Popen(["less"], stdin=PIPE)
    
        try:
            process.stdin.write(data)
            process.communicate()
        except IOError as e:
            pass
    
    0 讨论(0)
提交回复
热议问题