문제

I'm new to python and trying to wrap my head around this error from the code below:

try:
    import _winreg as winreg
except ImportError:
    pass

...

path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        try:
                 key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        except WindowsError, e:
                if e.errno == 2:
                        return []
                else:
                        raise e

Outputs: NameError global name 'winreg' is not defined.

What am I missing to get this working? My guess is that they included 'import as' because _winreg is simply winreg in python 3+. I have tried simply importing as _winreg and replacing the winreg -> _winreg but that also returns a NameError with '_winreg' not defined. Thanks in advance!

도움이 되었습니까?

해결책

You're silencing the ImportError.

try:
    import _winreg as winreg
except ImportError:
    pass

winreg is most likely not getting imported here, hence the NameError: the winreg name was never assigned because import failed.

You could remove the try / except block to confirm what's happening.


Since you want to support Python 3, what you're most likely looking for is:

try:
    import _winreg as winreg  # Try importing on Python 2
except ImportError:
    import winreg  # Fallback to Python 3 (if this raises an Exception, it'll escalate)

(_winreg was renamed in Python 3)

다른 팁

Your code works on python 2.x but fails silently on python 3.x. The proper thing to do is to try the 3.x import and fall back to the 2.x import if that fails. Since the second import is not protected by a try/except block, it will fail if winreg doesn't exist in either form - for instance, if its run on a linux machine.

try:
    # try python3 import
    import winreg
except ImportError:
    # fall back to python2 import
    import _winreg as winreg
# test code proves it works
print(winreg)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top