使用winreg用python创建“@”条目

2024-05-13 20:47:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用winreg将以下注册表参数转换为python:

REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf]
@="@SYS:Does_Not_Exist"

痛苦在于我无法复制的“@”。看看C语言中的例子,他们使用空字符串“”来输入@。如果手动导入上述内容并使用winreg的EnumValue(),则此条目也会显示为“”。但我似乎无法在pythonwinreg中执行类似的操作,到目前为止还没有找到解决方法。你知道吗

显示问题的代码:

from winreg import *
import os
import platform

import sys, time
import win32api as wa, win32con as wc, win32service as ws

def registrySetKey(hive, regpath, key, type, value):
    try:
        reg = OpenKey(hive, regpath, 0, KEY_ALL_ACCESS)
    except EnvironmentError:
        try:
            reg = CreateKey(hive, regpath, 0, KEY_ALL_ACCESS)
            SetValueEx(reg, key, None, type, value)
            CloseKey(reg)
        except:
            print("*** Unable to register path %s, key %s!" % (regpath, key))
            return
        print("--- Python", version, "is now registered!")
        return
    try:
        if (QueryValue(reg, key) == value):
            return
    except:
        SetValueEx(reg, key, None, type, value)
    CloseKey(reg)


reg = CreateKey(HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf')

# This does not work
registrySetKey(HKEY_LOCAL_MACHINE, 
               r'Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf', 
               '', REG_SZ, '@SYS:Does_Not_Exist')

在手动导入之后,条目的名称是(默认),使用它也不起作用。你知道吗

谨致问候, 斯文


Tags: keyimportvaluewindowslocalmachineregmicrosoft
1条回答
网友
1楼 · 发布于 2024-05-13 20:47:15

您正在使用的函数将与您的调用一起工作,但是当值当前不匹配时,您需要添加以下内容,即当前没有实际设置任何内容:

else:
    SetValueEx(reg, key, None, type, value)

因此,全部功能如下:

from winreg import *
import os
import platform

import sys, time
import win32api as wa, win32con as wc, win32service as ws

def registrySetKey(hive, regpath, key, type, value):
    try:
        reg = OpenKey(hive, regpath, 0, KEY_ALL_ACCESS)
    except EnvironmentError:
        try:
            reg = CreateKey(hive, regpath, 0, KEY_ALL_ACCESS)
            SetValueEx(reg, key, None, type, value)
            CloseKey(reg)
        except:
            print("*** Unable to register path %s, key %s!" % (regpath, key))
            return
        print(" - Python", version, "is now registered!")
        return
    try:
        if (QueryValue(reg, key) == value):
            return
        else:
            SetValueEx(reg, key, None, type, value)     # added
    except:
        SetValueEx(reg, key, None, type, value)
    CloseKey(reg)


reg = CreateKey(HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf')

registrySetKey(HKEY_LOCAL_MACHINE, 
               r'Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf', 
               '', REG_SZ, '@SYS:Does_Not_Exist') 

根据您的Windows版本,执行此操作可能会修改以下键:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf

相关问题 更多 >