Execute multiple python files using a single main

前端 未结 4 938
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.

    0 讨论(0)
  • 2021-01-06 13:24

    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.

    0 讨论(0)
  • 2021-01-06 13:25

    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()
    
    0 讨论(0)
  • 2021-01-06 13:26

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

    0 讨论(0)
提交回复
热议问题