How to import and call 'main' functions from different files

Viewed 49

I have bunch of python script files that i've created, and running them one by one. how can call these script files and run methods one by one from a different script file. I need little help as method in each file is named main() and i'm not sure how to import and call this method by the same name.

file1.py

import sys

def main():
   #do something

if __name__ == '__main__':
  main()

file2.py

import sys

def main():
   #do something else

if __name__ == '__main__':
  main()
3 Answers

You can simply import them as modules, and call the main() function for each

import file1, file2
file1.main()
file2.main()

I think the following syntax will work for you:

from file1 import main as main1
from file2 import main as main2
...

if you want to import main from file1.py into file2.py, you can do from file1 import main as main1 or some other name. This way, you give an alias to the function name. Alternatively, import file1 and then call file1.main()

Related