📜  获取os环境python(1)

📅  最后修改于: 2023-12-03 15:27:48.632000             🧑  作者: Mango

获取 OS 环境的 Python

在编写 Python 程序时,我们可能需要知道操作系统上正在运行的 Python 版本以及安装的 Python 解释器的路径。在本文中,我们将介绍如何在不同的操作系统下获取这些信息。

Windows 操作系统

在 Windows 操作系统上,我们可以使用 winreg 模块来访问 Windows 注册表中存储的 Python 解释器信息。下面是一个示例代码,可以打印当前默认的 Python 版本号和路径:

import winreg


def get_python_info():
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Python\\PythonCore") as key:
        subkey_count, _, _ = winreg.QueryInfoKey(key)
        for i in range(subkey_count):
            subkey_name = winreg.EnumKey(key, i)
            with winreg.OpenKey(key, subkey_name) as subkey:
                try:
                    version = winreg.QueryValueEx(subkey, "Version")[0]
                    install_path = winreg.QueryValueEx(subkey, "InstallPath")[0]
                    print(f"Python {version} is installed at {install_path}")
                except FileNotFoundError:
                    pass


get_python_info()

输出示例:

Python 3.8.6 is installed at C:\Program Files\Python38
Python 3.9.1 is installed at C:\Program Files\Python39
macOS 操作系统

在 macOS 操作系统上,我们可以使用 subprocess 模块来运行终端命令,获取系统中所有安装的 Python 版本的路径信息。下面是一个示例代码,可以打印出所有 Python 解释器的路径:

import subprocess


def get_python_info():
    command = "ls -d /Library/Frameworks/Python.framework/Versions/*/bin/python*"
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    for line in process.stdout:
        path = line.decode().strip()
        version = path.split("/")[-3]
        print(f"Python {version} is installed at {path}")


get_python_info()

输出示例:

Python 3.8 is installed at /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8
Python 3.9 is installed at /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9
Linux 操作系统

在 Linux 操作系统上,我们可以使用 subprocess 模块来运行终端命令,获取系统中所有安装的 Python 版本的路径信息。下面是一个示例代码,可以打印出所有 Python 解释器的路径:

import subprocess


def get_python_info():
    command = "ls -d /usr/bin/python* /usr/local/bin/python*"
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    for line in process.stdout:
        path = line.decode().strip()
        version = path.split("/")[-1]
        print(f"Python {version} is installed at {path}")


get_python_info()

输出示例:

Python 2.7 is installed at /usr/bin/python2.7
Python 3.6 is installed at /usr/bin/python3.6
Python 3.7 is installed at /usr/bin/python3.7
Python 3.8 is installed at /usr/bin/python3.8
Python 3.9 is installed at /usr/local/bin/python3.9