fix_execfile.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright 2006 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Fixer for execfile.
  4. This converts usages of the execfile function into calls to the built-in
  5. exec() function.
  6. """
  7. from .. import fixer_base
  8. from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node,
  9. ArgList, String, syms)
  10. class FixExecfile(fixer_base.BaseFix):
  11. BM_compatible = True
  12. PATTERN = """
  13. power< 'execfile' trailer< '(' arglist< filename=any [',' globals=any [',' locals=any ] ] > ')' > >
  14. |
  15. power< 'execfile' trailer< '(' filename=any ')' > >
  16. """
  17. def transform(self, node, results):
  18. assert results
  19. filename = results["filename"]
  20. globals = results.get("globals")
  21. locals = results.get("locals")
  22. # Copy over the prefix from the right parentheses end of the execfile
  23. # call.
  24. execfile_paren = node.children[-1].children[-1].clone()
  25. # Construct open().read().
  26. open_args = ArgList([filename.clone(), Comma(), String('"rb"', ' ')],
  27. rparen=execfile_paren)
  28. open_call = Node(syms.power, [Name("open"), open_args])
  29. read = [Node(syms.trailer, [Dot(), Name('read')]),
  30. Node(syms.trailer, [LParen(), RParen()])]
  31. open_expr = [open_call] + read
  32. # Wrap the open call in a compile call. This is so the filename will be
  33. # preserved in the execed code.
  34. filename_arg = filename.clone()
  35. filename_arg.prefix = " "
  36. exec_str = String("'exec'", " ")
  37. compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str]
  38. compile_call = Call(Name("compile"), compile_args, "")
  39. # Finally, replace the execfile call with an exec call.
  40. args = [compile_call]
  41. if globals is not None:
  42. args.extend([Comma(), globals.clone()])
  43. if locals is not None:
  44. args.extend([Comma(), locals.clone()])
  45. return Call(Name("exec"), args, prefix=node.prefix)