'Why doesn't this while loop work as a substitute for this try/except block when checking the availability of modules?

The following works as intended installing the module before importing it:

#!/usr/bin/env python3

from subprocess import run
from sys import modules
try:
    from bs4 import BeautifulSoup
except:
    run("pip3 install beautifulsoup4", shell=True)
    from bs4 import BeautifulSoup    

It crossed my mind that I could accomplish the same job with a while loop. And so I wrote:

#!/usr/bin/env python3

from subprocess import run
from sys import modules

while "bs4" not in modules:# neither does  work `while not "bs4" in modules:`
    run("pip3 install beautifulsoup4", shell=True)
from bs4 import BeautifulSoup

But it does not work, I get from Python:

/home/jerzy/.local/lib/python3.8/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 0.23ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
Collecting beautifulsoup4
  Using cached beautifulsoup4-4.11.1-py3-none-any.whl (128 kB)
Requirement already satisfied: soupsieve>1.2 in /home/jerzy/.local/lib/python3.8/site-packages (from beautifulsoup4) (1.9.5)
Installing collected packages: beautifulsoup4
Successfully installed beautifulsoup4-4.11.1
Requirement already satisfied: beautifulsoup4 in /home/jerzy/.local/lib/python3.8/site-packages (4.11.1)
Requirement already satisfied: soupsieve>1.2 in /home/jerzy/.local/lib/python3.8/site-packages (from beautifulsoup4) (1.9.5)
Requirement already satisfied: beautifulsoup4 in /home/jerzy/.local/lib/python3.8/site-packages (4.11.1)
Requirement already satisfied: soupsieve>1.2 in /home/jerzy/.local/lib/python3.8/site-packages (from beautifulsoup4) (1.9.5)
Requirement already satisfied: beautifulsoup4 in /home/jerzy/.local/lib/python3.8/site-packages (4.11.1)
Requirement already satisfied: soupsieve>1.2 in /home/jerzy/.local/lib/python3.8/site-packages (from beautifulsoup4) (1.9.5)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source