Skip to content Skip to sidebar Skip to footer

How To Run A Python File Not In Directory From Another Python File?

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 execfi

Solution 1:

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).

Solution 2:

import sys, change "sys.path" by appending the path during run time,then import the module that will help

Solution 3:

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

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

Doing it that literally is brittle, of course. If baz is always a subirectory of foo you could derive it from foo's 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 in locations that can be seen by your python -- ie, the folders are in sys.path or have been added to the search path using site you can import baz from foo and call it's functions directly. If you need to actually act on information from baz, instead of just triggering an action, this is a better way to go. As long as there is an init.py in each folder You could just do

import baz
baz.do_a_function_defined_in_baz() 

Post a Comment for "How To Run A Python File Not In Directory From Another Python File?"