Python — How do you view output that doesn't f

2020-06-01 07:32发布

I should say I'm looking for a solution to the problem of viewing output that does not fit on your screen. For example, range(100) will show the last 30ish lines in your terminal of 30 height.

I am only looking to be nudged in the right direction and am curious how you guys have approached this problem.

What have you done when you run into a situation where you wish you could conveniently scroll through some large output?

Best Answer

Use the scrollback buffer on your terminal.

If you're using GNU Screen, it can be set with defscrollback 1000 or any other number in HOME/.screenrc.

Use Ctrl-a, [ to enter copy mode

j -    Move the cursor down by one line
k -    Move the cursor up by one line
C-u -  Scrolls a half page up.
C-b -  Scrolls a full page up.
C-d -  Scrolls a half page down.
C-f -  Scrolls the full page down.
G -    Moves to the specified line 

The best part is ? for reverse search, / for forward search while in copy mode.

Super convenient.

Thank you!


Original question:

What is the python equivalent of the bash less command?

LongString | less 

Is there something like that for python? I find myself thinking I could use it fairly often but just move on and find some other solution.

By "long things" I mean anything that generates more output lines than my screen. 1000 print messages, a dictionary, a large string, range(1000), etc.

My googlefu has failed.

标签: python
9条回答
走好不送
2楼-- · 2020-06-01 07:42

Say you're writing a program in Python and all it does is pretty print some stuff. The output is in prettiest_print_ever. You already do weird tricks importing fcntl, termios, struct and friends to get the terminal size so that you can use the full width of the terminal (if any); that also gives you the screen height, so it makes sense to use it. (That also means you've long given up any pretenses of cross-platform compatibility, too.)

Sure, you can reinvent the wheel, or you can rely on less like other programs do (e.g. git diff). This should be the outline of a solution:

def smart_print(prettiest_print_ever, terminal_height = 80):
  if len(prettiest_print_ever.splitlines()) <= terminal_height:
    #Python 3: make sure you write bytes!
    sys.stdout.buffer.write(prettiest_print_ever.encode("utf-8"))
  else
    less = subprocess.Popen("less", stdin=subprocess.PIPE)
    less.stdin.write(prettiest_print_ever.encode("utf-8"))
    less.stdin.close()
    less.wait()
查看更多
老娘就宠你
3楼-- · 2020-06-01 07:42

If you work in ipython you can issue shell commands within your interactive python session. That means that you just do

In [1]: less myfile.txt

I also really like being able to arrow up and down to get previous commands and getting the output from previous commands by doing something like

In [33]: print cos(Out[7]*pi/180)
查看更多
Summer. ? 凉城
4楼-- · 2020-06-01 07:44

What have you done when you run into a situation where you wish you could conveniently > scroll through some large output?

  1. Don't create large output. Use functions to summarize or show selected details.

  2. Simplify the application to avoid creating large output in the first place.

  3. Focus what I'm looking at to avoid large output.

  4. Generally avoid large output.

It seems simpler to avoid large output than to fuss around trying to display something I never cared about in the first place.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-06-01 07:45

It's easy to write your own:

def less(s, line_count = 5):
    lines = []
    for i, line in enumerate(s.split('\n'), 1):
        lines.append(line)
        if (i % line_count) == 0:
            yield '\n'.join(lines)
            lines = []

    if lines:
        yield '\n'.join(lines)
查看更多
姐就是有狂的资本
6楼-- · 2020-06-01 07:50

There's one fundamental difference between less run in a shell, and Python: Python is a programming language, less is a program.

Bash is aware of what the linecount is in the console, and less can query that (and a number of other things), Python on its own can't be, it's a language and it's agnostic to its environment (that's left to libraries).

On top of that, less obeys some of its own standards. Careted lines get moved to top, it feeds to termcap, it's conceptually part of the OS tools, and it's meant to send to output even if it hasn't finished reading the file.

You can write less in Python if you want, or run it from inside a python script, but its functionality is more (and too specific) than a single method of file should contain.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2020-06-01 07:50

if your data is json serilizable then you can try

import simplejson
print simplejson.dumps({'shipping-line': {'price': '0.00', 'code': 'Local Pickup (Portland, OR)', 'title': 'Local Pickup (Portland, OR)'}}, indent=4)

Output will be look something like

{
    "shipping-line": {
        "price": "0.00", 
        "code": "Local Pickup (Portland, OR)", 
        "title": "Local Pickup (Portland, OR)"
    }
}

this is specifically used to debug and to see the actual content......in well readble format..

EDIT:

if your screen is limited to 25 lines..........

import simplejson
data = simplejson.dumps({'shipping-line': {'price': '0.00', 'code': 'Local Pickup (Portland, OR)', 'title': 'Local Pickup (Portland, OR)'}}, indent=4)

cnt = 0

for line in data.split('\n'):
    cnt+=1
    print line
    raw_input() if cnt%25==0 else None
查看更多
登录 后发表回答