Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

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

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: I know docker exists, but am talking at a python/script level or a direct system level for purely execution purposes.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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')

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 .

It will generate the following requirements.txt file:

requests==2.23.0
beautifulsoup4==4.9.1

which you can install with:

pip install -r requirements.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...