5

I have multiple python files, each with different classes and methods in it. I want to execute all those files with a main function I have separately outside all of them.

For example:

I have three files say one.py, two.py, three.py

I have no main method in any of them, but when I execute them then I want them to pass through the main function that I have separately. Is this possible, how?

Thanks.

vinay polisetti
  • 374
  • 1
  • 3
  • 15
  • can you create a new file like a driver.py and have it import and execute the correct code? or were you interested in something more dynamic? – dm03514 Sep 26 '12 at 14:02

4 Answers4

8

Do you mean you want to import them?

import one
import two
import three

result = one.func()
instance = two.YourClass()
something = three.func()

Note that there is no "main method" in python (perhaps you've been using JAVA?). When you say python thisfile.py, python executes all of the code in "thisfile.py". One neat little trick that we use is that each "module" has an attribute "name". the script invoked directly (e.g. thisfile.py) gets assigned the name "__main__". That allows you to separate the portion of a module which is meant to be a script, and the portion which is meant to be reused elsewhere. A common use case for this is testing:

#file: thisfile.py
def func():
   return 1,2,3

if __name__ == "__main__":
   if func() != (1,2,3):
      print "Error with func"
   else:
      print "func checks out OK"

Now if I run this as python thisfile.py, it will print func checks out OK, but if I import it in another file, e.g:

#anotherfile.py
import thisfile

and then I run that file via python anotherfile.py, nothing will get printed.

mgilson
  • 300,191
  • 65
  • 633
  • 696
5

use them as modules and import them into your script containing main.

import one
import two
import three

if __name__ == '__main__':
    one.foo()
    two.bar()
    three.baz()
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
1

Create a new file that imports these files and run that file.

Bitwise
  • 7,577
  • 6
  • 33
  • 50
1

As previous answers suggest, if you simply need to re-use the functionality do an import.

However, if you do not know the file names in advance, you would need to use a slightly different import construct. For a file called one.py located in the same directory, use:

Contents of the one.py:

print "test"
def print_a():
    print "aa"

Your main file:

if __name__ == "__main__":
    imp = __import__("one")
    print dir(imp)

Prints out test and also gives information about the methods contained in the imported file.

petr
  • 2,554
  • 3
  • 20
  • 29