PyCharm not willing to import modules

2020-04-09 08:10发布

问题:

Whenever I try to import modules in PyCharm, the line of code is highlighted grey and it gives me the error "unused import statement". This seems to happen for every module I try to import. Does anyone know what could be causing this?

回答1:

Once you call those modules in your script, you should see those greyed out lines turn to their normal color.

You can turn off the code inspection that looks at import, but I don't advise doing that unless you're absolutely sure you don't need it.

I changed my "Unused Symbol" in Settings > Editor > Colors&Fonts > General to just be grey without the underline. This helps me quickly see if I have a variable or an import that I'm not using in my code.

Then I also changed the code inspection severity on unused. Settings > Editor > Inspections > Python > Unused local I set the severity to 'INFO' and 'In All Scopes'.

This allows you to still gain the benefit of knowing you have unused variables without it treating it like an error.

As you can see from my screenshot, I'm not using tz or tzinfo even though I imported them. I find that pretty handy.



回答2:

You need to actually use the module.

For example, this will have a grey line:

import easygui   # Pretend there is a grey line

The module easygui is imported and is used for nothing. So PyCharm tells you that the module is unused, not unsuccessfully imported. If you use the module in another piece of code, the grey line will disappear:

import easygui
easygui.msgbox("There will be no more grey line.")