python 版本切换脚本(切记根据自己的需求更改,出错自己负责)

本文介绍了一个Python脚本,用于在Windows系统中切换Python版本的环境变量。通过修改注册表键值来实现Python版本从2.7到3.5的切换,并触发环境变量更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
author = 'nathan'


import os
import re
import getpass
import sys
import time
import _winreg
import ctypes

import win32api
import win32gui, win32con 
def version_change():
    #注册表去查看自己所需要修改的位置,_winreg.KEY_ALL_ACCESS是SAM属性,win7,win8需先在注册表中开放用户权限
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\ControlSet001\Control\Session Manager\Environment',0,_winreg.KEY_ALL_ACCESS) 
    # get the current value
    value, typ = _winreg.QueryValueEx (hKey, 'path')
    #print value
    try:
        value, typ = _winreg.QueryValueEx (hKey, 'current_py_version')
    except:
        print r"新建系统环境变量current_py_version"
        #newKey = _winreg.CreateKey(hKey,"current_py_version")
        #_winreg.SetValue(newKey,"ValueName",0,"ValueContent")
        _winreg.SetValueEx(hKey, "current_py_version", 0, typ, ''.join('C:\Python27') )


    print'---更改current_py_version中----'


    value, typ = _winreg.QueryValueEx (hKey, 'current_py_version')
    print "原本为:",value
    if (value=='C:\Python27'):
        _winreg.SetValueEx(hKey, "current_py_version", 0, typ, ''.join(r'C:\Users\nathan\AppData\Local\Programs\Python\Python35') )
    else:
        _winreg.SetValueEx(hKey, "current_py_version", 0, typ, ''.join(r'C:\Python27') )    
    value, typ = _winreg.QueryValueEx (hKey, 'current_py_version')
    print "现版本为",value
    rc, dwReturnValue = win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 5000)
version_change()
path = os.environ['path']

print path


解决了注册表更新的问题,不过需要使用到win32


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值