Reputation: 384
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.
Upvotes: 5
Views: 39509
Reputation: 309891
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.
Upvotes: 8
Reputation: 2586
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.
Upvotes: 1
Reputation: 60604
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()
Upvotes: 5