Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 execfile work? What about os.system?

like image 578
user1938464 Avatar asked Dec 30 '12 20:12

user1938464


People also ask

How do you access a Python file from another folder?

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.

How do I run Python without adding to path?

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.

Can you run a script from another script Python?

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

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

like image 182
rbanffy Avatar answered Oct 10 '22 04:10

rbanffy


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

like image 39
Pradyumna Avatar answered Oct 10 '22 04:10

Pradyumna