How do I load a file into the python console?


I have some lines of python code that I"m continuously copying/pasting into the python console. Is there a load command or something I can run? e.g. load

Answer rating: 206

For Python 2 give execfile a try. (See other answers for Python 3)


Example usage:
Let"s use "copy con" to quickly create a small script file...

C:junk>copy con
a = [9, 42, 888]
b = len(a)
        1 file(s) copied.

...and then let"s load this script like so:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("")
>>> a
[9, 42, 888]
>>> b

Answer rating: 198

From the man page:

-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.

So this should do what you want:

python -i

Answer rating: 108

Python 3: new exec (execfile dropped) !

The execfile solution is valid only for Python 2. Python 3 dropped the execfile function - and promoted the exec statement to a builtin universal function. As the comment in Python 3.0"s changelog and Hi-Angels comment suggest:



instead of


Get Solution for free from DataCamp guru