How to run a Python file not in a directory from another Python file?

Say I have a foo.py file, and inside the file I want to execute the bar.py file. But bar.py is not in the same directory as foo.py, it is in the call baz subdirectory. Will execfile work? What about os.system ?

+6
source share
3 answers

Just add an empty __init__.py file to the baz signal - this is a module and from foo.py do:

 from baz import bar 

Unless, of course, you have a good reason not to turn baz into a module (and use execfile).

+4
source

import sys, modify "sys.path" by adding a path at runtime, then import the module to help

+2
source

The question implies that you want to run them as scripts, so yes: you can use execfile in 2.X or subprocess (call the interpreter and pass the script as an argument). You just need to provide absolute file paths.

 # Python 2.X only! execfile ('c:/python/scripts/foo/baz/baz.py') 

Doing it is literally fragile, of course. If baz is always a subdirectory of foo, you can extract it from the foo file :

 baz_dir = os.path.join(os.path.dirname(__file__), "baz") baz_file = os.path.join(baz_dir, "baz.py") execfile(baz_file) 

If both files are located in places that can be seen on your python - that is, the folders are located in sys.path or were added to the search path using site, you can import baz from foo and directly call its functions. If you need to actually work on the information from baz, and not just initiate an action, this is the best way to go. So far, each folder has init .py. You can just do

 import baz baz.do_a_function_defined_in_baz() 
+1
source

All Articles