I met a lot of user feedback in an open source project a few days ago , No dependencies will be installed , Or perform pip install -r requirements.txt
No response .
There are many possible causes , It's also troublesome to check one by one .
Want to solve this problem once and for all , Generally, everyone comes to site-packages
Inside, guide out the required bags , Put it in the project root .
But it's too rough after all , Do not conform to the Python Elegant personality .
So I thought , Can you dynamically import packages , If not , Call again pip
download . Finally, I almost realized my idea .
I probably checked , No one seems to have used this scheme now , It's very convenient for me to use , Share with you .
Although I want to make it library For everyone to download , Later, I thought that I had to rely on pip, Against the original intention of dynamic dependency So I recommend using
Quick start - Inject code to run
Ways in
pip
Installation and operation stay PyPI
download dypend
Dependency package
pip install dypend
Generate... Locally requirements.txt
Dependency file
pip freeze > requirements.txt
Introduce... At the top level of the entry file of the project dypend
, Don't change any other code
import dypend
At this time dypend
Will check your Python Are there any in the environment requirements.txt
In the package , without , dypend
Would call pip
download .
Generate... Locally requirements.txt
Dependency file
pip freeze > requirements.txt
Add the following code at the top of the entry file of the project , Don't change any other code
import os import re REQUIREMENTS = 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("(?<===).+$", lib).group(0) libDict = { "name": name, "version": version } libList.append(libDict) except: continue return libList def importLib(): """Load python dependent libraries dynamically""" libList = getDepends() from pip._internal import main as pip_main import importlib def install(package): pip_main(['install', package]) createVar = locals() for lib in libList: print(lib) try: createVar[lib["name"]] = importlib.import_module(lib["name"]) except Exception as e: try: install(f'{lib["name"]}=={lib["version"]}') createVar[lib["name"]] = importlib.import_module(lib["name"]) except Exception as e: print(e) importLib()
At this time dypend Will check your Python Are there any in the environment requirements.txt
In the package , without ,dypend Will automatically download .
If this article is helpful to you , Please give a compliment before you leave ~