Execute multiple python files using a single main

前端 未结 4 964
Happy的楠姐
Happy的楠姐 2021-01-06 12:55

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.

4条回答
  •  既然无缘
    2021-01-06 13:14

    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.

提交回复
热议问题