<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def set_installed_packages():
 """Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards. """

    global INSTALLED_PACKAGES, REQUIRED_VERSION
    if INSTALLED_PACKAGES:
        return

    if os.path.exists(BIN_PYTHON):
        pip = subprocess.Popen(
            (BIN_PYTHON, '-m', 'pip', 'freeze'),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        (stdout, stderr) = pip.communicate()
        pip.wait()

        INSTALLED_PACKAGES = [r.decode().split('==')[0].lower() for r in stdout.split()]
        REQUIRED_VERSION = next((package for package in INSTALLED_PACKAGES if re.match(r'^lore[!<>=]', package)), None)
        if REQUIRED_VERSION:
            REQUIRED_VERSION = re.split(r'[!<>=]', REQUIRED_VERSION)[-1]