如何根据需要从 python 脚本自动安装所需的包? [英] How to automatically install required packages from a python script as necessary?

查看:45
本文介绍了如何根据需要从 python 脚本自动安装所需的包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 或 linux 中有什么东西基本上指示系统安装任何必要的东西".基本上我觉得为我工作的每个新脚本/系统/服务器安装 python 包很烦人.无论如何,每次我最终都会执行 sudo pip 或 apt-get 或 dnf.为什么不在脚本本身内自动化.无论何时出现找不到包"错误,请将库名称传递给安装语句.有吗?

Is there anything in python or linux what basically instructs the system to "install whatever is necessary". Basically I find it annoying to install python packages for each new script/system/server that I work on. Each time I end up doing a sudo pip or an apt-get or dnf anyway. Why not automate that within the script itself. Whereever a 'no package found' error crops up, pass the library name to the install statement. Is this there ?

PS:我知道 docker 存在,但我只是在 Python/脚本级别或直接系统级别进行讨论,仅用于执行目的.

PS: I know docker exists, but am talking at a python/script level or a direct system level for purely execution purposes.

谢谢

推荐答案

如何根据需要从 python 脚本自动安装所需的包?

How to automatically install required packages from a python script as necessary?

假设您的 Python 脚本是 example.py:

Let's assume that your Python script is example.py:

import os
import time
import sys
import fnmatch
import requests
import urllib.request
from bs4 import BeautifulSoup
from multiprocessing.dummy import Pool as ThreadPool 
print('test')

您可以使用 pipreqs 自动生成基于 requirements.txt 的文件在 Python 脚本包含的 import 语句上.使用pipreqs,假设你在example.py所在的目录:

You can use pipreqs to automatically generate a requirements.txt file based on the import statements that the Python script(s) contain. To use pipreqs, assuming that you are in the directory where example.py is located:

pip install pipreqs
pipreqs .

它将生成以下requirements.txt文件:

requests==2.23.0
beautifulsoup4==4.9.1

你可以安装:

pip install -r requirements.txt

这篇关于如何根据需要从 python 脚本自动安装所需的包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆