开发者

Printing the line above the current executing line

Is there a way for a line of code in a Python script to print the line above it?


UPDATE:

Motivations

  • It's an intriguing problem. I was wondering if Python's strong introspection goes that far.
  • I 开发者_开发技巧was saving this for a follow up question - I actually don't want to "print the line above", but rather to grab a certain line of code (I'll know which only in run-time), disassemble it and understand which variables are mentioned. I'll explain why in the follow-up :)


To read (with your eyes) you can use PDB

Just import pdb and then you can do this:

code:

a = 'test'
import pdb; pdb.set_trace()

After running a code you will get stopped in shell like enviroment and you will be able to do this:

-> import pdb; pdb.set_trace()
(Pdb) print a
test
(Pdb) l
  1     a = 'test';
  2  -> import pdb; pdb.set_trace()
[EOF]

So you want to look at l(ist) command:

List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines around at that line. With two arguments, list the given range; if the second argument is less than the first, it is interpreted as a count.

More in http://docs.python.org/library/pdb.html


If you wish to automate code morphing -

Other languages, such as Perl, Python and JavaScript, allow programs to create new code at run-time and execute it using an eval function, but do not allow existing code to be mutated. The illusion of modification (even though no machine code is really being overwritten) is achieved by modifying function pointers

Source: http://en.wikipedia.org/wiki/Self-modifying_code


If you wish to automate code reading, but not morphing, you can use linecache as shown in here http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html and just instead of printing put it into a list and get whatever value you want :)

Hope it will help.


I think you're asking the wrong question (maybe?) - are you looking to get the last item in the call stack? If so, you could possibly do something like this:

import inspect

def do_add(a, b):
        if type(a) is not int or type(b) is not int:
                print inspect.stack()[1] # last stack item
                return None

        return a + b

do_add(1, 3)
do_add(1, 'asd')

http://ideone.com/IpdQa


Depending on the complexity, and this is probably ill advised, you can read in your python file w/ readlines(), print them, and then call exec() on them in a looping structure.

example for those dumb enough to suggest that this isn't possible in the limited scope i was referring to.

>>> a = ["a=1+1","b=a","print b"]
>>> for item in a:
...     print item
...     exec(item)
... 
a=1+1
b=a
print b
2
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜