Coder Perfect

How can I use the Python interpreter to run a file?


I’m attempting to run a Python command file from within the interpreter.

EDIT: Instead of invoking a new process, I’m attempting to leverage variables and settings from that file.

Asked by Adam Matan

Solution #1

Several ways.

Answered by S.Lott

Solution #2

For Python 2:

>>> execfile('')

For Python 3:

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

See the documentation for further information. See this question if you’re using Python 3.0.

For an example of how to access globals from after it has been executed, see @S.Lott’s answer.

Answered by codeape

Solution #3

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

This will run a script and place all of its global variables in the global scope of the interpreter (the normal behavior in most scripting environments).

Python 3 exec Documentation

Answered by Waylon Flinn

Solution #4

I’m surprised I haven’t come across this before. Using the -i option, you can run a file and then leave the interpreter open after it finishes:

| |
testvar = 10

def bar(bing):
  return bing*3


$ python -i
>>> testvar 
>>> bar(6)

Answered by Bennett Talpers

Solution #5

Simply importing the file with import filename (without extension; it must be in the same directory or on your PYTHONPATH) will run it, making all of its variables, functions, classes, and other features available in the filename.variable namespace.

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

If you have code outside of a function in, it will be executed immediately, however designing apps that run code on import will make it difficult to reuse your code. Put everything into functions or classes if at all possible.

Answered by mikl

Post is based on