Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a file within the Python interpreter?

Tags:

python

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.

like image 672
Adam Matan Avatar asked Jun 22 '09 15:06

Adam Matan


People also ask

How do I run a python interpreter file?

The most basic and easy way to run a Python script is by using the python command. You need to open a command line and type the word python followed by the path to your script file, like this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard and that's it.

How do I run a python file in a python file?

Use the execfile() Method to Run a Python Script in Another Python Script. The execfile() function executes the desired file in the interpreter. This function only works in Python 2. In Python 3, the execfile() function was removed, but the same thing can be achieved in Python 3 using the exec() method.


2 Answers

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 
like image 126
S.Lott Avatar answered Sep 17 '22 17:09

S.Lott


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.

like image 44
codeape Avatar answered Sep 21 '22 17:09

codeape