简体   繁体   中英

python import statement fails in function

I have a python module that needs to be able to run on Windows and Linux. While running it responds to certain keyboard "hotkeys". It is a python 3.3 script.

In my class constructor I do the following:

self.setup_stdin()

The function setup_stdin is this:

def setup_stdin(self):
    self.osname = os.name
    if self.osname == 'posix':
        self.setup_posix_stdin()
    elif self.osname == 'nt':
        self.setup_nt_stdin()

When I run on Linux, I have no problem with setup_posix_stdin , it just makes stdin non-blocking so I can handle keystrokes.

setup_nt_stdin is the following:

def setup_nt_stdin(self):
    import msvcrt

However, when I run on Windows 7, my program bombs with

NameError: global name 'msvcrt' is not defined

To get around this, when I run on Windows, I move the import statement to the top of the file, and replace the setup_nt_stdin function body with pass, and it works fine.

I thought I could import from a function. This function is inside a class, is there some other syntax I'm missing?

The import statement binds the name of the imported module in the local scope only.

To get around this you could do:

def setup_nt_stdin(self):
    global msvcrt
    import msvcrt

Although considering you can import something multiple times without it executing any more and you're going to need guards to check the OS before actually using the name msvcrt elsewhere, it might make more sense to just import msvcrt inside every windows-specific function that needs it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM