The Python Oracle

How do I load a file into the python console?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 Question
00:26 Accepted answer (Score 207)
01:04 Answer 2 (Score 229)
01:37 Answer 3 (Score 122)
02:12 Answer 4 (Score 35)
02:31 Thank you

--

Full question
https://stackoverflow.com/questions/5280...

Accepted answer links:
[execfile]: https://docs.python.org/2.7/library/func...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #readevalprintloop

#avk47



ANSWER 1

Score 243


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



ACCEPTED ANSWER

Score 211


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.py
a = [9, 42, 888]
b = len(a)
^Z
        1 file(s) copied.

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

C:\junk>\python27\python
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('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>



ANSWER 3

Score 36


From the shell command line:

python file.py

From the Python command line

import file

or

from file import *



ANSWER 4

Score 25


You can just use an import statement:

from file import *

So, for example, if you had a file named my_script.py you'd load it like so:

from my_script import *