Include python module (dependencies) installation in your python script

后端 未结 3 1602
悲哀的现实
悲哀的现实 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:52

    There's a few ways to do this. One way is to surround the import statement with a try...except ImportError block and then have some Python code that installs the package if the ImportError exception is raised, so something like:

    try:
        import MultipartPostHandler
    except ImportError:
        # code that installs MultipartPostHandler and then imports it
    

    I don't think this approach is very clean. Plus if there are other unrelated importing issues, that won't be detected here. A better approach might be to have a bash script that checks to see if the module is installed:

    pip freeze | grep MultipartPostHandler
    

    and if not, installs the module:

    pip install MultipartPostHandler
    

    Then we can safely run the original Python code.

    EDIT: Actually, I like FLORET's answer better. The imp module is exactly what you want.

提交回复
热议问题