Inspect code of next line in Python
Question: 
    # script.py  
    
    greeting = "hi"
    import inspect; import traceback; print traceback.format_stack(inspect.currentframe())[-1]
    print greeting
    

The code on the fourth line of the script prints out the file name, line
number and the current line:

    
    
    $ python script.py   
    File "script.py", line 4, in <module>
        import inspect; import traceback; print traceback.format_stack(inspect.currentframe())[-1]
    hi
    

But how can I print out the line number and the content for the next
line(`print greeting`) instead of the current one?

This would be convenient for debugging, a oneliner to show the code of the
line beneath it.

## Edit

Via Ben's answer I got to this hideous creature:

    
    
    import inspect; import sys; _lne = inspect.currentframe().f_lineno; print "{0}, line {1}:".format(__file__, _lne+1); print open(sys.argv[0]).readlines()[_lne].strip()
    

It's 166 chars long, very verbose. Beware that it raises an `IndexError` when
the there is no next line.

Running `python script.py` would print out the following

    
    
    script.py, line 5:  
    print greeting
    hi
    

I'm hoping some minor change in the original line I posted could lead to the
desired behavior, because that included the file name and number without the
need of explicitly printing these. And the indentation it provided wasn't
unwelcome either.


Answer: Add a little helper function to lookup and print the relevant filename and
line:

    
    
    import inspect, linecache
    
    def show_next(cf):
        'Show the line following the active line in a stackframe'
        filename = cf.f_code.co_filename
        line = cf.f_lineno
        print linecache.getline(filename, line+1)
    
    
    greeting = "hi"
    
    show_next(inspect.currentframe())
    print greeting
    

Of course, if need, it can go into one-line:

    
    
    greeting = "hi"
    import inspect, linecache; _f=inspect.currentframe(); print linecache.getline(_f.f_code.co_filename, _f.f_lineno+1)
    print greeting
    

