Copying and pasting code into the Python interpreter
Solution 1:
You can usually easily and safely do copy-pasting with IPython, through the commands %cpaste
(manually end code with --
) and %paste
(execute code immediately). This is very handy for testing code that you copy from web pages, for instance, or from your editor: these commands even strip leading prompts (like In[1]
and ...
) for you.
IPython also has a %run
command that runs a program and leaves you in a Python shell with all the variables that were defined in the program, so that you can play with them.
In order to get help on these functions: %cpaste?
, etc.
Solution 2:
You can call execfile(filename). More or less the same as importing a module, except that it skips the module administration part and doesn't require you to add a folder to sys.path.
EDIT: To address the original question: copy-pasted code can be executed by calling exec(codestring).