Joey
Joey

Reputation: 21

Why is my "import msvcrt" statement not working?

I am writing this code in python (on my windows 10 machine) :

import msvcrt

a = getch()

and I'm getting this error when I try to run it using python3:

Traceback (most recent call last):
  File "Simon.py", line 2, in <module>
    import msvcrt
ModuleNotFoundError: No module named 'msvcrt'
[Exit 1 ]

Anyone know how I can make this import work? The functionality of the getch() method is the last thing I need for this program to work.

Upvotes: 2

Views: 7705

Answers (1)

Grismar
Grismar

Reputation: 31354

You are likely trying this in an environment that runs on Linux. msvcrt is part of the standard Python libraries for Windows, but not available on Linux.

If you only need it on Windows:

from platform import system
if system() == 'Windows':
    from msvcrt import getch

If you need it on both Windows and Linux, you may want to install the third party getch library. For example, on my CentOS VM that would would be:

sudo yum install gcc
sudo yum install python3-devel
pip install getch

After that, you can update your code to:

from platform import system
if system() == 'Windows':
    from msvcrt import getch
else:
    from getch import getch

Alternatively, make clear what you need getch() for and look for an alternative that doesn't depend on platform-specific imports.

Upvotes: 3

Related Questions