import importlib.util
import inspect
import os
import re
import sys
import types
import warnings
from pathlib import Path

from .. import config, console, constants, logger


def get_module(file_name: Path):
    if str(file_name) == "-":
        module = types.ModuleType("input_scenes")
        logger.info(
            "Enter the animation's code & end with an EOF (CTRL+D on Linux/Unix, CTRL+Z on Windows):"
        )
        code = sys.stdin.read()
        if not code.startswith("from manim import"):
            logger.warning(
                "Didn't find an import statement for Manim. Importing automatically..."
            )
            code = "from manim import *\n" + code
        logger.info("Rendering animation from typed code...")
        try:
            exec(code, module.__dict__)
            return module
        except Exception as e:
            logger.error(f"Failed to render scene: {str(e)}")
            sys.exit(2)
    else:
        if Path(file_name).exists():
            ext = file_name.suffix
            if ext != ".py":
                raise ValueError(f"{file_name} is not a valid Manim python script.")
            module_name = ext.replace(os.sep, ".").split(".")[-1]

            warnings.filterwarnings(
                "default", category=DeprecationWarning, module=module_name
            )

            spec = importlib.util.spec_from_file_location(module_name, file_name)
            module = importlib.util.module_from_spec(spec)
            sys.modules[module_name] = module
            sys.path.insert(0, str(file_name.parent.absolute()))
            spec.loader.exec_module(module)
            return module
        else:
            raise FileNotFoundError(f"{file_name} not found")


def get_scene_classes_from_module(module):
    from ..scene.scene import Scene

    def is_child_scene(obj, module):
        return (
            inspect.isclass(obj)
            and issubclass(obj, Scene)
            and obj != Scene
            and obj.__module__.startswith(module.__name__)
        )

    return [
        member[1]
        for member in inspect.getmembers(module, lambda x: is_child_scene(x, module))
    ]


def get_scenes_to_render(scene_classes):
    if not scene_classes:
        logger.error(constants.NO_SCENE_MESSAGE)
        return []
    if config["write_all"]:
        return scene_classes
    result = []
    for scene_name in config["scene_names"]:
        found = False
        for scene_class in scene_classes:
            if scene_class.__name__ == scene_name:
                result.append(scene_class)
                found = True
                break
        if not found and (scene_name != ""):
            logger.error(constants.SCENE_NOT_FOUND_MESSAGE.format(scene_name))
    if result:
        return result
    return (
        [scene_classes[0]]
        if len(scene_classes) == 1
        else prompt_user_for_choice(scene_classes)
    )


def prompt_user_for_choice(scene_classes):
    num_to_class = {}
    for count, scene_class in enumerate(scene_classes):
        count += 1  # start with 1 instead of 0
        name = scene_class.__name__
        console.print(f"{count}: {name}", style="logging.level.info")
        num_to_class[count] = scene_class
    try:
        user_input = console.input(
            f"[log.message] {constants.CHOOSE_NUMBER_MESSAGE} [/log.message]"
        )
        return [
            num_to_class[int(num_str)]
            for num_str in re.split(r"\s*,\s*", user_input.strip())
        ]
    except KeyError:
        logger.error(constants.INVALID_NUMBER_MESSAGE)
        sys.exit(2)
    except EOFError:
        sys.exit(1)


def scene_classes_from_file(file_path, require_single_scene=False):
    module = get_module(file_path)
    all_scene_classes = get_scene_classes_from_module(module)
    scene_classes_to_render = get_scenes_to_render(all_scene_classes)
    if require_single_scene:
        assert len(scene_classes_to_render) == 1
        return scene_classes_to_render[0]
    return scene_classes_to_render

manim/utils/module_ops.py
import importlib.util
import inspect
import os
import re
import sys
import types
import warnings
from pathlib import Path

from .. import config, console, constants, logger


def get_module(file_name: Path):
    if str(file_name) == "-":
        module = types.ModuleType("input_scenes")
        logger.info(
            "Enter the animation's code & end with an EOF (CTRL+D on Linux/Unix, CTRL+Z on Windows):"
        )
        code = sys.stdin.read()
        if not code.startswith("from manim import"):
            logger.warning(
                "Didn't find an import statement for Manim. Importing automatically..."
            )
            code = "from manim import *\n" + code
        logger.info("Rendering animation from typed code...")
        try:
            exec(code, module.__dict__)
            return module
        except Exception as e:
            logger.error(f"Failed to render scene: {str(e)}")
            sys.exit(2)
    else:
        if Path(file_name).exists():
            ext = file_name.suffix
            if ext != ".py":
                raise ValueError(f"{file_name} is not a valid Manim python script.")
            module_name = ext.replace(os.sep, ".").split(".")[-1]

            warnings.filterwarnings(
                "default", category=DeprecationWarning, module=module_name
            )

            spec = importlib.util.spec_from_file_location(module_name, file_name)
            module = importlib.util.module_from_spec(spec)
            sys.modules[module_name] = module
            sys.path.insert(0, str(file_name.parent.absolute()))
            spec.loader.exec_module(module)
            return module
        else:
            raise FileNotFoundError(f"{file_name} not found")


def get_scene_classes_from_module(module):
    from ..scene.scene import Scene

    def is_child_scene(obj, module):
        return (
            inspect.isclass(obj)
            and issubclass(obj, Scene)
            and obj != Scene
            and obj.__module__.startswith(module.__name__)
        )

    return [
        member[1]
        for member in inspect.getmembers(module, lambda x: is_child_scene(x, module))
    ]


def get_scenes_to_render(scene_classes):
    if not scene_classes:
        logger.error(constants.NO_SCENE_MESSAGE)
        return []
    if config["write_all"]:
        return scene_classes
    result = []
    for scene_name in config["scene_names"]:
        found = False
        for scene_class in scene_classes:
            if scene_class.__name__ == scene_name:
                result.append(scene_class)
                found = True
                break
        if not found and (scene_name != ""):
            logger.error(constants.SCENE_NOT_FOUND_MESSAGE.format(scene_name))
    if result:
        return result
    return (
        [scene_classes[0]]
        if len(scene_classes) == 1
        else prompt_user_for_choice(scene_classes)
    )


def prompt_user_for_choice(scene_classes):
    num_to_class = {}
    config["write_all"] = True
    for count, scene_class in enumerate(scene_classes):
        count += 1  # start with 1 instead of 0
        name = scene_class.__name__
        console.print(f"{count}: {name}", style="logging.level.info")
        num_to_class[count] = scene_class
    try:
        user_input = console.input(
            f"[log.message] {constants.CHOOSE_NUMBER_MESSAGE} [/log.message]"
        )
        return [
            num_to_class[int(num_str)]
            for num_str in re.split(r"\s*,\s*", user_input.strip())
        ]
    except KeyError:
        logger.error(constants.INVALID_NUMBER_MESSAGE)
        sys.exit(2)
    except EOFError:
        sys.exit(1)


def scene_classes_from_file(file_path, require_single_scene=False):
    module = get_module(file_path)
    all_scene_classes = get_scene_classes_from_module(module)
    scene_classes_to_render = get_scenes_to_render(all_scene_classes)
    if require_single_scene:
        assert len(scene_classes_to_render) == 1
        return scene_classes_to_render[0]
    return scene_classes_to_render

manim/utils/module_ops.py
diff --git a/manim/utils/module_ops.py b/manim/utils/module_ops.py
index 5de1d83df7..501109a1f1 100644
--- a/manim/utils/module_ops.py
+++ b/manim/utils/module_ops.py
@@ -94,6 +94,7 @@ def get_scenes_to_render(scene_classes):
 
 def prompt_user_for_choice(scene_classes):
     num_to_class = {}
+    config["write_all"] = True
     for count, scene_class in enumerate(scene_classes):
         count += 1  # start with 1 instead of 0
         name = scene_class.__name__

Multiple animations are saved in the same file when a Scene is not specified
## Description of bug / unexpected behavior
I've made a file with different `Scenes` _(A, B, C & D)_ called bug.py . When trying to render, if I don't specify which `Scene` I'd like to render, manim asks me to choose number corresponding to desired scene, as expected. If I input multiple numbers (separated with commas), manim starts rendering them all, (as expected), but, after finishing the rendering of a scene, it saves it with the name of the first animation. So, **A** will be saved as _A.mp4_, but **B** will also be saved as _A.mp4_, overwriting the previous animation. In the end, I only have the last animation(**D**), saved as _A.mp4_.


## Expected behavior
<!-- Add a clear and concise description of what you expected to happen. -->
I expect each animation to be saved in it's own file.

## How to reproduce the issue
Create multiple classes in the same file.

Render as follows: `manim bug.py`
Manim will ask you to specify which `Scene`/s to render:
```
Choose number corresponding to desired scene/arguments.
(Use comma separated list for multiple entries)
Choice(s):
```
Input `1,2,3,4` as choice(s)


```py
from manim import *

class A(Scene):
    def construct(self):
        self.add(Arrow(ORIGIN, UP))
        self.wait(0.5)

class B(Scene):
    def construct(self):
        self.add(Arrow(ORIGIN, LEFT))
        self.wait(0.5)

class C(Scene):
    def construct(self):
        self.add(Arrow(ORIGIN, DOWN))
        self.wait(0.5)

class D(Scene):
    def construct(self):
        self.add(Arrow(ORIGIN, RIGHT))
        self.wait(0.5)
```

</details>


## Additional media files
<!-- Paste in the files manim produced on rendering the code above. -->

<details><summary>Images/GIFs</summary>

</details>


## Logs
<details><summary>Terminal output</summary>
<!-- Add "-v DEBUG" when calling manim to generate more detailed logs -->

```
(mce) PS C:\Users\jero0\OneDrive\Documentos\Jero\Programación\Python\Manim> manim bug.py
Manim Community v0.6.0

1: A
2: B
3: C
4: D
 
Choose number corresponding to desired scene/arguments.
(Use comma separated list for multiple entries)
Choice(s):  1,2,3,4
[05/26/21 12:01:22] INFO     Animation 0 : Using cached data (hash : 450974505_2763922376_1174069105)                                                                               cairo_renderer.py:100                    INFO                                                                                                                                                         scene_file_writer.py:585                             File ready at C:\Users\jero0\OneDrive\Documentos\Jero\Programación\Python\Manim\media\videos\bug\1080p60\A.mp4

                    INFO     Rendered A                                                                                                                                                      scene.py:217                             Played 1 animations
[05/26/21 12:01:23] INFO     Animation 0 : Using cached data (hash : 450974505_2763922376_1361091488)                                                                               cairo_renderer.py:100                    INFO                                                                                                                                                         scene_file_writer.py:585                             File ready at C:\Users\jero0\OneDrive\Documentos\Jero\Programación\Python\Manim\media\videos\bug\1080p60\A.mp4

                    INFO     Rendered B                                                                                                                                                      scene.py:217                             Played 1 animations
                    INFO     Animation 0 : Using cached data (hash : 450974505_2763922376_1101716671)                                                                               cairo_renderer.py:100                    INFO                                                                                                                                                         scene_file_writer.py:585                             File ready at C:\Users\jero0\OneDrive\Documentos\Jero\Programación\Python\Manim\media\videos\bug\1080p60\A.mp4

                    INFO     Rendered C                                                                                                                                                      scene.py:217                             Played 1 animations
                    INFO     Animation 0 : Using cached data (hash : 450974505_2763922376_2709036221)                                                                               cairo_renderer.py:100[05/26/21 12:01:24] INFO                                                                                                                                                         scene_file_writer.py:585                             File ready at C:\Users\jero0\OneDrive\Documentos\Jero\Programación\Python\Manim\media\videos\bug\1080p60\A.mp4

                    INFO     Rendered D                                                                                                                                                      scene.py:217                             Played 1 animations
```

```
PASTE HERE OR PROVIDE LINK TO https://pastebin.com/ OR SIMILAR
```

<!-- Insert screenshots here (only when absolutely necessary, we prefer copy/pasted output!) -->

</details>


## System specifications

<details><summary>System Details</summary>

- OS (with version, e.g Windows 10 v2004 or macOS 10.15 (Catalina)):  Windows 10 Home
- RAM: 12GB DDR4
- Python version (`python/py/python3 --version`): Python 3.8.10
- Installed modules (provide output from `pip list`): 
```
Package             Version
------------------- ---------
appdirs             1.4.4
CacheControl        0.12.6
cachy               0.3.0
certifi             2020.12.5
chardet             4.0.0
cleo                0.8.1
click               7.1.2
click-default-group 1.2.2
clikit              0.6.2
cloup               0.7.1
colorama            0.4.4
colour              0.1.5
commonmark          0.9.1
crashtest           0.3.1
decorator           4.4.2
distlib             0.3.1
et-xmlfile          1.0.1
filelock            3.0.12
glcontext           2.3.3
html5lib            1.1
idna                2.10
joblib              1.0.1
keyring             21.8.0
lockfile            0.12.2
manim               0.6.0
ManimPango          0.2.6
mapbox-earcut       0.12.10
moderngl            5.6.4
moderngl-window     2.3.0
msgpack             1.0.2
multipledispatch    0.6.0
networkx            2.5
numpy               1.20.0
openpyxl            3.0.7
packaging           20.9
pandas              1.2.3
pastel              0.2.1
pexpect             4.8.0
Pillow              8.1.0
pip                 21.0.1
pkginfo             1.7.0
poetry              1.1.4
poetry-core         1.0.0
ptyprocess          0.7.0
pycairo             1.20.0
pydub               0.24.1
pyFirmata           1.1.0
pyglet              1.5.16
Pygments            2.7.4
pylev               1.3.0
pyparsing           2.4.7
pyrr                0.10.3
pyserial            3.5
python-dateutil     2.8.1
pytz                2021.1
pywin32-ctypes      0.2.0
requests            2.25.1
requests-toolbelt   0.9.1
rich                6.2.0
scikit-learn        0.24.2
scipy               1.6.0
setuptools          53.0.0
shellingham         1.4.0
six                 1.15.0
threadpoolctl       2.1.0
tomlkit             0.7.0
tqdm                4.56.0
typing-extensions   3.7.4.3
urllib3             1.26.3
virtualenv          20.4.2
watchdog            2.1.0
webencodings        0.5.1
wheel               0.36.2
```
</details>

<details><summary>LaTeX details</summary>

+ LaTeX distribution (e.g. TeX Live 2020):
+ Installed LaTeX packages:
<!-- output of `tlmgr list --only-installed` for TeX Live or a screenshot of the Packages page for MikTeX -->
</details>

<details><summary>FFMPEG</summary>

Output of `ffmpeg -version`:

```
ffmpeg version 4.3.1-2021-01-01-full_build-www.gyan.dev Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 10.2.0 (Rev5, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-lzma 
--enable-libsnappy --enable-zlib --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libdav1d --enable-libzvbi --enable-librav1e --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
```
</details>

## Additional comments
![manim_bug](https://user-images.githubusercontent.com/68753500/119688629-87b4c700-be1e-11eb-8904-6c411c1700ff.png)


