Python写PIP源切换工具

admin 2024年5月30日20:56:30评论12 views字数 3589阅读11分57秒阅读模式

作为 Python 开发者,我们经常需要安装各种第三方库。但是,有时候由于网络环境的问题,从官方 PyPI 源下载安装包会非常缓慢。这时候,切换到国内的 PIP 源就可以大大提高安装速度。
本工具使用了 Python 和 CustomTkinter 库开发,界面简洁美观,操作也非常方便。
只需要点击界面上的按钮,就可以轻松切换到阿里云、豆瓣、清华大学等国内 PIP 源。无需记住各个源的 URL,也不需要手动修改配置文件,非常适合日常开发使用。
如果你的网络环境不太理想时,不妨试试这个 PIP 源切换工具。

工具方便用户快速切换 pip 的源,以解决由于网络问题导致的 pip 安装慢或安装失败的问题

代码:

import reimport subprocessimport customtkinter as ctkPIP_SOURCES = {    "官方 PyPI": "https://pypi.org/simple/",    "阿里云": "https://mirrors.aliyun.com/pypi/simple/",    "豆瓣": "https://pypi.douban.com/simple/",    "清华大学": "https://pypi.tuna.tsinghua.edu.cn/simple",    "中国科技大学": "https://mirrors.ustc.edu.cn/pypi/web/simple/",    "华为云": "https://repo.huaweicloud.com/repository/pypi/simple",}def get_source_name(source_url):    for source_name, url in PIP_SOURCES.items():        if source_url.lower().strip("/") == url.lower().strip("/"):            return source_name    return source_urldef get_current_pip_source():    output = subprocess.run(        ["pip", "config", "list"], capture_output=True, text=True    ).stdout    pattern = r"index-urls*=s*(.*)$"    match = re.findall(pattern, output, flags=re.M)    if match:        return match[0].strip().strip("'").strip('"')    else:        return Nonedef set_pip_source(source_name):    source_url = PIP_SOURCES.get(source_name)    if not source_url:        result_label.configure(text="无效的选项!", text_color="red")        return    try:        process = subprocess.Popen(            ["pip", "config", "set", "global.index-url", source_url],            stdout=subprocess.PIPE,            stderr=subprocess.PIPE,        )        output, error = process.communicate()        if process.returncode == 0:            result_label.configure(text=f"PIP 源已设置为:{source_name}", text_color="green")        else:            result_label.configure(text=f"设置PIP源时出现错误:{error.decode()}", text_color="red")    except Exception as e:        result_label.configure(text=f"设置PIP源时出现错误:{str(e)}", text_color="red")def center_window(window):    window.update_idletasks()    width = window.winfo_width()    height = window.winfo_height()    x = (window.winfo_screenwidth() // 2) - (width // 2)    y = (window.winfo_screenheight() // 2) - (height // 2) - 100    window.geometry("{}x{}+{}+{}".format(width, height, x, y))ctk.set_appearance_mode("dark")ctk.set_default_color_theme("blue")window = ctk.CTk()window.title("PIP 源切换工具--微信公众号:蓝胖子之家")window.geometry("480x310")window.resizable(False, False)window.withdraw()main_frame = ctk.CTkFrame(window, corner_radius=10)main_frame.pack(padx=20, pady=20, fill="both", expand=True)for i, source_name in enumerate(PIP_SOURCES.keys()):    row = i // 2    col = i % 2    button = ctk.CTkButton(        main_frame,        text=source_name,        width=200,        height=50,        command=lambda source_name=source_name: set_pip_source(source_name),        fg_color="#2196f3",        hover_color="#1e88e5",        text_color="white",        corner_radius=8,    )    button.grid(row=row, column=col, padx=10, pady=10)current_pip_source = get_current_pip_source()if current_pip_source:    current_source_name = get_source_name(current_pip_source)else:    current_source_name = "未知pip源"result_label = ctk.CTkLabel(    main_frame,    text=f"当前源:{current_source_name}",    text_color="green",)result_label.grid(row=len(PIP_SOURCES) // 2 + 1, columnspan=2, padx=10, pady=10)center_window(window)window.update()window.deiconify()window.mainloop()

1. 导入所需的库:
- `re`: 用于正则表达式匹配
- `subprocess`: 用于执行系统命令
- `customtkinter`: 用于创建 GUI 界面
2. 定义了一个字典 `PIP_SOURCES`,其中包含了常用的 PIP 源地址及其对应的名称。
3. `get_source_name()` 函数用于根据 PIP 源地址获取其对应的名称。
4. `get_current_pip_source()` 函数用于获取当前使用的 PIP 源地址。
5. `set_pip_source()` 函数用于设置 PIP 源。它首先检查输入的源名称是否有效,然后使用 `subprocess` 执行 `pip config set` 命令来设置全局 PIP 源。最后,它根据设置结果更新结果标签的文本。
6. `center_window()` 函数用于将窗口居中显示。
7. 接下来是 GUI 界面的创建和布局:
- 设置 CustomTkinter 的外观模式和颜色主题。
- 创建一个 `CTkFrame` 作为主框架,并将其居中显示。
- 在主框架中创建一个个 `CTkButton`,每个按钮对应一个 PIP 源。点击按钮会调用 `set_pip_source()` 函数来切换 PIP 源。
- 创建一个 `CTkLabel` 用于显示当前使用的 PIP 源。
8. 最后,程序进入主事件循环,等待用户交互。

运行效果:

Python写PIP源切换工具

获取文章源码和编译工具

链接:https://pan.baidu.com/s/1NyQaSZMIOJ8u-AklrrM9Rg 提取码:afnq

原文始发于微信公众号(蓝胖子之家):Python写PIP源切换工具

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2024年5月30日20:56:30
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   Python写PIP源切换工具https://cn-sec.com/archives/2797033.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息