Search code examples
pythonimportargumentsprogram-entry-point

Python - How to call the main fuction of a module in another module?


I am trying to write a python module that calls the main function of another module in its main function.

The module I am writing is called Trial.py and the module that contains the function to be called is called print_all.py .

print_all.py is a module is a library called mrtparse. The library can be found here.

Note that when I run print_all.py in the Linux shell it requires a file (.gz) as argument as follows

$ python print_all.py updates.gz

Trial.py looks something like this:

from mrtparse import *
import gzip
import print_all   
import os
from urllib2 import urlopen, URLError, HTTPError

def fn1():
    Bla Bla

def fn2():
    Bla Bla

def main():
    mrtparse.print_all.main(updates.gz)  //I want to do something like this

if __name__ == '__main__':
    main()

All the modules and the files to be passed as arguments are in the same directory. It seems like an easy to do thing but I am having such a hard time with it.


Solution

  • I suppose, you should use:

    # ...
    
    import print_all
    
    # ...
    
    def main():
        print_all.main("updates.gz") 
    

    Honestly, print_all — is not a module and you cannot import it from any place. Notice, that there is no __init__.py in examples-folder. Otherwise, you will be able to use mrtparse.examples.print_all. But now mrtparse does not see anything in examples.

    So, you can put print_all-script near your script and use it like I show above.

    After that

    Main function in print_all have no arguments. It gets data from command line arguments.

    I think, you have two ways:

    • Wrong — patch sys.argv;
    • Right — rewrite main from print_all.

    Patch sys.argv (bad way)

    import sys
    sys.argv = sys.argv = [sys.argv[0], 'updates.gz']
    
    # ...
    
    import print_all
    
    # ...
    
    def main():
        print_all.main() 
    
    # ...
    

    Rewrite main()

    Post this function into print_all and use it instead of main.

    def do_work(filename):
    
        d = Reader(filename)
    
        # if you want to use 'asdot+' or 'asdot' for AS numbers,
        # comment out either line below.
        # default is 'asplain'.
        #
        # as_repr(AS_REPR['asdot+'])
        # as_repr(AS_REPR['asdot'])
        for m in d:
            m = m.mrt
            print('---------------------------------------------------')
            if m.err == MRT_ERR_C['MRT Header Error']:
                prerror(m)
                continue
            print_mrt(m)
    
            if m.err == MRT_ERR_C['MRT Data Error']:
                prerror(m)
                continue
            if m.type == MRT_T['TABLE_DUMP']:
                print_td(m)
            elif m.type == MRT_T['TABLE_DUMP_V2']:
                print_td_v2(m)
            elif ( m.type == MRT_T['BGP4MP']
                or m.type == MRT_T['BGP4MP_ET']):
                print_bgp4mp(m)
    

    Right way

    Place do_work in your own module or anywhere else in your code. After that, for example, yout file will be look like this:

    import sys
    from optparse import OptionParser
    from datetime import *
    from mrtparse import *
    from print_all import *
    import gzip
    import print_all   
    import os
    from urllib2 import urlopen, URLError, HTTPError
    
    
    def fn1():
        Bla Bla
    
    def fn2():
        Bla Bla
    
    def do_work(filename):
    
        d = Reader(filename)
    
        # if you want to use 'asdot+' or 'asdot' for AS numbers,
        # comment out either line below.
        # default is 'asplain'.
        #
        # as_repr(AS_REPR['asdot+'])
        # as_repr(AS_REPR['asdot'])
        for m in d:
            m = m.mrt
            print('---------------------------------------------------')
            if m.err == MRT_ERR_C['MRT Header Error']:
                prerror(m)
                continue
            print_mrt(m)
    
            if m.err == MRT_ERR_C['MRT Data Error']:
                prerror(m)
                continue
            if m.type == MRT_T['TABLE_DUMP']:
                print_td(m)
            elif m.type == MRT_T['TABLE_DUMP_V2']:
                print_td_v2(m)
            elif ( m.type == MRT_T['BGP4MP']
                or m.type == MRT_T['BGP4MP_ET']):
                print_bgp4mp(m)
    
    
    def main():
        do_work('updates.gz') 
    
    if __name__ == '__main__':
        main()