suji
suji

Reputation: 407

Python program which contains several python files

I want to write a python program, for example, main.py which contains two or more python programs(test1.py,test2.py..etc,.) which are placed in some other directories in these all of these programs has its own methods with parameters(test1.py,test2.py..etc,.). I tried some but cases were failed which contains parameters within the program. IS there any easy way to access several programs within one main python program?

Upvotes: 0

Views: 61

Answers (1)

user48956
user48956

Reputation: 15778

Sure. You can use import to load other python files:

# Use file1.py, file2.py
import file1
from file2 import func2

file1.func1()
func2()

In case your other files are programs, and not simply variables, class and functions, you can avoid executing the code in this programs as follows:

# file1.py(old)

def func1():
   ...

func1()  # Execute func1 when this file is loaded.
# file1.py(new)

def func1():
   ...

if __name__=='__main__':
   func1()  # Execute func1 when this file is loaded.

The code inside the if __name__=='__main__' block is only run if this is the first file loaded.

# Use file1.py, file2.py
import file1
from file2 import func2

file1.func1()
func2()

If you'd like to organize those files into a directory, you must create a 'module'. This simply requires that you place an empty __init__.py in the directory:

 + test.py
 + mymodule/
    + file1.py
    + file2.py
# Test.py. Use mymodule/file1.py, mymodule/file2.py
import mymodule.file1
from mymodule.file2 import func2

file1.func1()
func2()

This will work if mymodule is in the current directory when run. (ie. you ran python test.py and not python a/b/c/test.py.

For a detailed answer, see http://docs.python.org/3/tutorial/modules.html

Upvotes: 4

Related Questions