Include python module (dependencies) installation in your python script

后端 未结 3 1609
悲哀的现实
悲哀的现实 2020-12-18 15:52

Is there a way to include/invoke python module(s) (dependencies) installation first, before running the actual/main script?

For example, in my main.py:



        
3条回答
  •  忘掉有多难
    2020-12-18 16:39

    You should use the imp module. Here's a example:

    import imp
    import httplib2
    import sys
    
    try:
      import MultipartPostHandler
    except ImportError:
      # Here you download 
      http = httplib2.Http()
      response, content = http.request('http://where_your_file_is.com/here')
      if response.status == 200:
        # Don't forget the right managment
        with open('MultipartPostHandler.py', 'w') as f:
         f.write(content)
        file, pathname, description = imp.find_module('MultipartPostHandler')
        MultipartPostHandler = imp.load_module('MultipartPostHandler', file, pathname, description)
      else:
        sys.exit('Unable to download the file')
    

    For a full approach, use a queue:

    download_list = []
    try:
        import FirstModule
    except ImportError:
        download_list.append('FirstModule')
    
    try:
        import SecondModule
    except ImportError:
        download_list.append('SecondModule')
    
    if download_list:
        # Here do the routine to dowload, install and load_modules
    
    # THe main routine
    def main():
        the_response_is(42)
    

    You can download binaries with open(file_content, 'wb')

    I hope it help

    BR

提交回复
热议问题