383

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

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

0

12 Answers 12

334

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
    
5
  • 2
    is there any way to provide stdin from a file like using < to the executing script with in the execfile().? @s-lott
    – bhanu
    Mar 2, 2016 at 7:18
  • 12
    @pzkpfw python can point to any version of python. I have seen environments with only python v3 where python points to python3.
    – StockB
    Aug 3, 2016 at 18:08
  • 2
    @pzkpfw That depends on what python executable the system finds when looking through the folders in the environment variable PATH. Dec 9, 2017 at 10:47
  • For random GIS people I could call this in ArcGIS Pro exec(open("D:\\Scripts\\myscript.py").read())
    – woodwa
    Oct 25, 2022 at 4:42
  • I'm finding that the F5 bullet applies to Spyder specifically, and it runs the already-opened temp.py. If I just run python at the Conda prompt, F5 doesn't do anything. Nov 6 at 22:49
276

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.

3
  • What does read method do? Unfortunately the official documentation site doesn't provide a clear example and explanation.
    – Dmitry
    Jan 24, 2019 at 13:56
  • It reads the file and returns (by default) the entire contents in one single string, see e.g. w3schools page on file open.
    – Max
    May 22, 2019 at 16:17
  • Here are the docs for open(): docs.python.org/3/library/io.html
    – codeape
    May 23, 2019 at 7:22
109

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

2
  • Is there a way to pass a parameter to the script? the following doesn't work: exec(open"setup.py install").read(), globals())
    – ben
    Jul 20, 2017 at 17:34
  • 2
    @ben that won't work because open directly reads the code from the script. To pass arguments, look at this answer, but instead of execfile, obviously use exec and open as shown above.
    – Nico
    Jul 22, 2017 at 8:35
79

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
0
32

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.

2
  • 4
    That won't use the global namespace, as the question requires. Use instead from filename import * Dec 23, 2015 at 13:22
  • The question does not specifically mention using a global namespace, that may be what the OP wants, but it is not obvious from the question. Mar 24, 2017 at 20:57
19

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 *
2
  • 1
    yep... this seems to be the best way... THX! but... reload isn't working for me... i'm in Python 3.9.5... any ideas???
    – ZEE
    Aug 10, 2021 at 16:56
  • 1
    @ZEE , I'm using python 3.8.5, I can use: from importlib import reload. It looks like the imp has been merged to the importlib
    – Neo li
    Sep 2, 2021 at 2:47
12

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 *
0
9

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())
0
8

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.

1
  • 5
    Plus, it should be a comment, not an answer.
    – Adam Matan
    Mar 10, 2015 at 9:30
8

For python3 use either with xxxx = name of yourfile.

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

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)
1
-1
python -c "exec(open('main.py').read())"

Not the answer you're looking for? Browse other questions tagged or ask your own question.