当前位置:网站首页>PIP batch complete uninstall package
PIP batch complete uninstall package
2022-06-26 04:19:00 【Baiyukong】
pip Batch complete uninstall package
Background
Because there are too many third-party libraries installed in my native environment , So I'm going to uninstall them today , But because there are so many , So it's impossible to do it one by one , So I wrote a little script , This article will record the role and use of this script .
If I write this article well , Can you give me Point a praise , Comment on 、 Collection A dragon (*▽*). If you want one Focus on It's not impossible to .
Please join us at the end of this article vote Oh , If What are the shortcomings , also Please put forward in the comment area , Thank you for .
Problem analysis
To achieve the above functions , We need to solve the following problems :
- Get all installed packages
- Get the dependencies of each package
- Command line interaction , Uninstall the specified package
resolvent
The above three questions can be used subprocess.Popen Package to solve . For convenience , Third question use subprocess.run solve .
There are many articles on the Internet that are right subprocess.Popen and subprocess.run The parameters of , I won't go into more details here .
about subprocess.Popen , In addition to the order to be executed , I only set stdin、stdout、stderr Parameters .
about subprocess.run , In addition to the order to be executed , I only set the following parameters :
- universal_newlines , Set the input / output data type ,True For the string , Otherwise, it is a byte string .
- capture_output , Set whether to display the command execution results ,True Show , Otherwise it doesn't show .
- input , This is the key , Enables code to interact with the command line , That is, after the command is specified , Enter the content on the command line to execute . The role in this article is to execute pip uninstall 【 Package name 】 Post input y Make sure .
Code details
Import the required libraries first :re 、subprocess .
Then package the code that unloads a package into a function , as follows ( The chicken code level of this dish is insufficient , Please also point out the problems ):
def uninstall_completely(name):
# Libraries that are required or do not need to be uninstalled , You can set it yourself
skips = ['pip', 'urllib3', 'setuptools', 'wheel']
if name in skips or name.startswith('-'):
return
print(f'Start to uninstall {
name}')
# initialization Popen, Read command pip show 【 Package name 】 The results of the implementation of
pipe = subprocess.Popen(f'pip show {
name}', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# If the package is not installed , The exit
if b'WARNING: Package(s) not found: ' in pipe.stderr.read():
print(f'An error occurred when uninstalling {
name}: {
name} non-existent \n')
return
# Regular matching obtains all dependent package names
# stdout.read() The result is a string of bytes , Need to be converted to a string
requirements = ''.join(re.findall('Requires: (.*?)\r\n', pipe.stdout.read().decode()))
print(f"{
name}'s requirements: {
requirements}")
# Close the command line
pipe.terminate()
# Uninstall the specified package
try:
# Carry out orders pip uninstall 【 Package name 】
# After executing the command, you need to enter whether to uninstall [y/n], Because you want to uninstall , So specified input Parameter is 'y'
obj = subprocess.run(f'pip uninstall {
name}', universal_newlines=True, capture_output=True, input='y')
# If something goes wrong , Then the error reason is output
if not obj.stderr == '':
print(obj.stderr)
return
# Otherwise, the uninstall succeeds
else:
print(f'Uninstall {
name} successfully.')
# Prevent the program from stopping due to an error in the middle
except Exception as e:
print(f'An error occurred when uninstalling {
name}: {
e}')
# Output results are separated
print('-------------------------------------------')
# Uninstall all dependent packages of the specified package , Call this function recursively
for _ in requirements.split(', '):
if r == '':
continue
uninstall_completely(_)
The calling function code is as follows :
for line in subprocess.Popen('pip list', stdout=subprocess.PIPE).stdout.read().decode().split('\n')[2:]:
name = line.split(' ')[0]
if name == '':
continue
uninstall_completely(name)
among :
- pip list You can view all currently installed packages .
- .decode() Because stdout.read() The result is a string of bytes , You need to convert it to a string .
- [2:] Remove the useless lines as shown in the following figure

If only a single package is unloaded , Call function directly .
If you uninstall some packages , Traverse the list and call the functions separately .
Change BUG
When writing code BUG It's not uncommon , But this time very few . The reason for the error is that the encoding error occurred when reading the execution result .
The specific process is run Call in function Popen.communicate() function , as follows :
with Popen(*popenargs, **kwargs) as process:
try:
stdout, stderr = process.communicate(input, timeout=timeout)
except TimeoutExpired as exc:
process.kill()
And then call Popen._communicate() function , as follows :
try:
stdout, stderr = self._communicate(input, endtime, timeout)
except KeyboardInterrupt:
...
Call again Popen._readerthread() function , as follows :
self.stdout_thread = threading.Thread(target=self._readerthread,
args=(self.stdout, self._stdout_buff))
to glance at Popen._readerthread() , as follows :
def _readerthread(self, fh, buffer):
buffer.append(fh.read())
fh.close()
This will be from Popen.stdout Read command execution result in .
Look again. Popen.stdout Initialization code , as follows :
self.text_mode = encoding or errors or text or universal_newlines
...
self.stdout = io.open(c2pread, 'rb', bufsize)
if self.text_mode:
self.stdout = io.TextIOWrapper(self.stdout, encoding=encoding, errors=errors)
At this point it becomes clear , If you specify encoding 、errors、text、universal_newlines Any one or more parameters in , It means that the output is character string , And if there is no designation encoding Parameter words , The default is to use gbk code , If the encoding method is different from that in the environment, an error will be reported .
Then we can modify it Popen Source code , stay subprocess pass the civil examinations 767 That's ok self.text_mode Add the following code to the next line of the definition of :
if self.text_mode and encoding is None:
encoding = sys.getdefaultencoding()
If you want to convert a byte string to a string and do not specify an encoding format , Use the environment default encoding .
ending
Someone wants to study together python My little friends can Private confidence in me Join the group .
That's what I want to share , because A little knowledge , There will be shortcomings , also Please correct .
If you have any questions, you can also leave a message in the comment area .
边栏推荐
- List of provinces, cities and counties in China
- What should I do if the 51 SCM board cannot find the device in keil
- MySQL enable logbin in Qunhui docker
- Development prospect and investment strategic planning report of global and Chinese PVC hose industry from 2022 to 2028
- Install SVN in Pagoda and build SVN version Library
- Detr3d multi 2D picture 3D detection framework
- Syntax error of go language generic in IDE
- Which is the best embedded visual programming software? (introduction, evaluation and selection of visual programming platform) [scratch, mind+, mixly]
- Tencent Interviewer: How did binder get its system services?
- 线程同步之读写锁
猜你喜欢
![[Qunhui] import certificate](/img/1f/ab63b0556a60b98388b482d70f6156.jpg)
[Qunhui] import certificate

CTF serialization and deserialization

線程同步之讀寫鎖

After four years of outsourcing, people are directly abandoned...

一幅脑图总结一下需求分析(工作上实际遇到的情况的补充)

Nailing open platform - applet development practice (nailing applet server side)

Tp6 multi table Association (table a is associated with table B, table B is associated with table C, and table d)

A brain map to summarize the needs analysis (a supplement to the actual situation at work)

Part 4: drawing quadrilateral

2021 year end summary
随机推荐
Review of number theory
List of provinces, cities and counties in China
Part 4: drawing quadrilateral
[learn FPGA programming from scratch -45]: vision chapter - integrated circuits help high-quality development in the digital era -2- market forecast
Analysis report on development trend and market demand of global and Chinese molecular diagnostics industry from 2022 to 2028
CTF serialization and deserialization
WPF value conversion
[从零开始学习FPGA编程-45]:视野篇 - 集成电路助力数字化时代高质量发展-2-市场预测
Analysis report on development status and future trend of CMOS image sensor industry in China 2022 ~ 2028
After a test of 25K bytes, I really saw the basic ceiling
go语言泛型在IDE中语法报错
Your requirements could not be resolved
OSS CDN alicloud configuration method
Threejs专用天空盒素材,五种天空盒素材免费下载
VHDL设计
How much do you make by writing a technical book? To tell you the truth, 2million is easy!
Wechat applet is bound to a dynamic array to implement a custom radio box (after clicking the button, disable the button and enable other buttons)
What if the serial port fails to open when the SCM uses stc-isp to download software?
钉钉开放平台-小程序开发实战(钉钉小程序客户端)
But the Internet began to have a new evolution and began to appear in a new state