How do I load a file into the python console? How do I load a file into the python console? python python

How do I load a file into the python console?


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

execfile('file.py')

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

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

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

C:\junk>\python27\pythonPython 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> execfile('execfile_example.py')>>> a[9, 42, 888]>>> b3>>>


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 file.py


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:

use

exec(open(<filename.py>).read())

instead of

execfile(<filename.py>)


matomo