ModuleNotFoundError: No module named 'dnf' when running yum or dnf

neozheng / 2024-08-29 / 原文

这两天干了一件很坑的事情:把  linux 服务器自带的 python3.6卸载了,然后就用不了 yum 和 dnf 了。所用的命令和大致经过和这个帖子几乎一模一样:

 

I have a friend who met the same problem.

He tried to uninstall python3.7 in linux server by some amazing cmd rpm -qa|grep python3|xargs rpm -ev --allmatches --nodeps and whereis python3 |xargs rm -frv.
This caused the yum and dnf to break.

I changed the /usr/bin/yum to use a local python3.8 version, but it caused ModuleNotFoundError: No module named 'dnf' at last, and didn't solved it.

It is not a good way to download many rpm packages on the Internet. And I can't use yum either. But I have another same linux OS server, so I've tried to copy the correlation files about python3.7.

然后博主还给出了解决方案:

$ rpm -ql python3-3.7.0-9.h4.eulerosv2r8.aarch64> py.log
$ while read -r line;do dirname $line |xargs -I {} ssh root@$remoteip "mkdir -p {}" ;scp $line root@$remoteip:$line  ;done<py.log

$ rpm -ql python3-libs-3.7.0-9.h4.eulerosv2r8.aarch64 >pylib.log
$ while read -r line;do dirname $line |xargs -I {} ssh root@$remoteip "mkdir -p {}" ;scp $line root@$remoteip:$line  ;done<pylib.log

scp -r /usr/lib/python3.7/site-packages root@$remoteip:/usr/lib/python3.7/

 

但是我没有相同的 linux服务器可供使用,所以我就采用了他所说的 "not a good way" 的方式,对, 就是把 python3*.rpm 都下载下来然后手动安装。 我选用的镜像源是 阿里云的 centos8,其中以 python3开头的rpm包有108个,就写个爬虫自动化下载了。

import os
import requests
from bs4 import BeautifulSoup

# 要爬取的 URL
url = "http://mirrors.aliyun.com/centos/8/BaseOS/x86_64/os/Packages/"

# 创建一个用于保存下载文件的目录
download_dir = "py36_rpm"
os.makedirs(download_dir, exist_ok=True)

# 发送请求并获取页面内容
response = requests.get(url)
response.raise_for_status()  # 确保请求成功

# 解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')

# 查找所有以 'python3' 开头的 rpm 包链接
for link in soup.find_all('a'):
    href = link.get('href')
    if href and href.startswith('python3') and href.endswith('.rpm'):
        # 构建完整的下载链接
        download_url = url + href
        # 下载文件并保存
        print(f"Downloading {href}...")
        rpm_response = requests.get(download_url)
        with open(os.path.join(download_dir, href), 'wb') as f:
            f.write(rpm_response.content)

print("All files downloaded.")

通过这个脚本把以 python3开头的rpm包都下载到了 py36_rpm 文件夹下,然后上传到了服务器上,执行一下命令:

rpm -ivh --force --nodeps python3*.rpm

yum 和 dnf 终于可以用了。

 

经过这个事也得长教训了,不要用 ` rpm -qa|grep python3|xargs rpm -ev --allmatches --nodeps and whereis python3 |xargs rm -frv` 方式去卸载 python ,真的好坑!!

 

参考链接:

https://stackoverflow.com/questions/53894712/modulenotfounderror-no-module-named-dnf-when-running-yum-or-dnf