Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Python dynamic loading dependency with code

Shulou Source: shulou.com Published: 2022-06-02 05:07:50 11月06日 Update

Today, I will talk to you about how to use code to achieve Python dynamic loading dependency, many people may not understand, in order to make you better understand, the editor summarized the following, I hope you can get something according to this article.

A few days ago in an open source project encountered a lot of user feedback, will not install dependencies, or the implementation of pip install-r requirements.txt did not respond.

There are many possible causes, and it is troublesome to investigate them one by one.

If you want to solve this problem once and for all, you usually go to site-packages to export the required packages and put them in the root directory of the project.

But after all, this is too rough to conform to Python's elegant personality.

So I wondered if I could introduce the package dynamically, and if not, call pip to download it. In the end, my vision almost came true.

I recommend using quick start-injecting code to run

Quick start

Kneel and beg for star GitHub-louisyoungx/dypend

Install and run through pip

Download the dypend dependency package at PyPI

Pip install dypend

Generate requirements.txt dependent files locally

Pip freeze > requirements.txt

Introduce dypend at the top of the entry file of the project without changing any other code

Import dypend

At this point, dypend will check whether there are all packages in requirements.txt in your Python environment, and if not, dypend will call pip to download.

The injected code runs

Generate requirements.txt dependent files locally

Pip freeze > requirements.txt

Add the following code to the top of the entry file of the project without changing any other code

Import osimport reREQUIREMENTS = os.getcwd () +'/ requirements.txt'def getDepends (): requirements = open (REQUIREMENTS,'r') libs = requirements.readlines () libList = [] for lib in libs: try: name = re.search ("^. + (? =)", lib) .group (0) version = re.search ("(?

Tags: Code file project dynamic content run upper layer no entry environment check build elegant rough once and for all almost personality reason way more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Xiaomi MariaDB vpn