1

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

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

痛苦在于我似乎无法复制的“@”。查看 C# 中的示例,他们使用例如空字符串 '' 来输入 @。如果我手动导入上述内容并使用 Winreg 的 EnumValue(),则此条目也显示为“”。但我似乎无法在 python winreg 中做类似的事情,到目前为止我还没有找到解决方法。

显示问题的代码:

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')

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

问候,斯文

4

1 回答 1

0

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

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
于 2016-03-04T11:52:35.027 回答