Let's say I have a file foo.py, and within the file I want to execute a file bar.py. But, bar.py isn't in the same directory as foo.py, it's in a subdirectory call baz. Will execfile
work? What about os.system
?
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
You can optionally just type in the full path minus the . py file extension. You could also just CD to the directory where a python script is located, and then type in the script name (with or without the extension) and press Enter , and python should run the script logic accordingly.
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.
Just add an empty __init__.py
file to signal baz
is a module and, from foo.py
do:
from baz import bar
Unless, of course, you have a good reason not to make baz
into a module (and use execfile).
import sys, change "sys.path" by appending the path during run time,then import the module that will help
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