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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With