How to execute a file within the Python interpreter?

Python

Python Problem Overview


I'm trying to execute a file with Python commands from within the interpreter.

EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.

Python Solutions


Solution 1 - Python

Several ways.

  • From the shell

    python someFile.py
    
  • From inside IDLE, hit F5.

  • If you're typing interactively, try this (Python3):

    >>> exec(open("filename.py").read())
    
  • For Python 2:

    >>> variables= {}
    >>> execfile( "someFile.py", variables )
    >>> print variables # globals from the someFile module
    

Solution 2 - Python

For Python 2:

>>> execfile('filename.py')

For Python 3:

>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())

See the documentation. If you are using Python 3.0, see this question.

See answer by @S.Lott for an example of how you access globals from filename.py after executing it.

Solution 3 - Python

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation

Solution 4 - Python

Surprised I haven't seen this yet. You can execute a file and then leave the interpreter open after execution terminates using the -i option:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

Solution 5 - Python

> I'm trying to use variables and settings from that file, not to invoke a separate process.

Well, simply importing the file with import filename (minus .py, needs to be in the same directory or on your PYTHONPATH) will run the file, making its variables, functions, classes, etc. available in the filename.variable namespace.

So if you have cheddar.py with the variable spam and the function eggs – you can import them with import cheddar, access the variable with cheddar.spam and run the function by calling cheddar.eggs()

If you have code in cheddar.py that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.

Solution 6 - Python

From my view, the best way is:

import yourfile

and after modifying yourfile.py

reload(yourfile)   

or in python3:

import imp; 
imp.reload(yourfile)

but this will make the function and classes looks like that: yourfile.function1, yourfile.class1.....

If you cannot accept those, the finally solution is:

reload(yourfile)
from yourfile import *

Solution 7 - Python

Just do,

from my_file import *

Make sure not to add .py extension. If your .py file in subdirectory use,

from my_dir.my_file import *

Solution 8 - Python

I am not an expert but this is what I noticed:

if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import *' if you want to make all variables available to the interpreter.

Solution 9 - Python

For Python 3:

>>> exec(open("helloworld.py").read())

Make sure that you're in the correct directory before running the command.

To run a file from a different directory, you can use the below command:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

Solution 10 - Python

For python3 use either with xxxx = name of yourfile.

exec(open('./xxxx.py').read())

Solution 11 - Python

Supposing you desire the following features:

  1. Source file behaves properly in your debugger (filename shows in stack, etc)
  2. __name__ == '__main__' is True so scripts behave properly as scripts.

The exec(open('foo.py').read()) fails feature 1 The import foo strategy fails feature 2

To get both, you need this:

    source = open(filename).read()
    code = compile(source, filename, 'exec')
    exec(code)

Solution 12 - Python

python -c "exec(open('main.py').read())"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam MatanView Question on Stackoverflow
Solution 1 - PythonS.LottView Answer on Stackoverflow
Solution 2 - PythoncodeapeView Answer on Stackoverflow
Solution 3 - PythonWaylon FlinnView Answer on Stackoverflow
Solution 4 - PythonBennett TalpersView Answer on Stackoverflow
Solution 5 - PythonmiklView Answer on Stackoverflow
Solution 6 - PythonNeo liView Answer on Stackoverflow
Solution 7 - PythonShital ShahView Answer on Stackoverflow
Solution 8 - Pythoncarlos e orozcoView Answer on Stackoverflow
Solution 9 - PythonPrashant GongaView Answer on Stackoverflow
Solution 10 - PythonAMGView Answer on Stackoverflow
Solution 11 - PythonKen SeehartView Answer on Stackoverflow
Solution 12 - PythonbluevariantView Answer on Stackoverflow