简体   繁体   中英

Pushing Python introspection to limits

Simple question – can I print the source code of this if ?

if __name__ == '__main__':
  # ...
  # this is the `if` I want to print
  #  V 
  if args and args[0][0] == '-':
    if args[0] in ('--help','-h','-?'):
      print_source_of_block(level=2)
    icase = 'i' in args[0]
    desc = 'd' in args[0]
    args = args[1:]

Please don't ask me why I need it, nor give me advice on how to write user help. I want to know it because I'm curious.

Might want to look at the inspect module ( https://docs.python.org/2/library/inspect.html ). Specifically, the inspect.getsource(object) method.

Yeah, that's doable. Here's a quick sketch of how you could do it and what tools would be involved:

  1. Retrieve the stack frame of print_source_of_block 's caller with inspect.currentframe().f_back .
  2. Determine the caller's source file and line number within that source file with inspect.getframeinfo .
  3. Open the source file.
  4. Either
  5. Using either the abstract syntax tree or the token stream, determine where the requested source block begins and ends.
  6. Print the block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM