Repository: h2oai/wave
File: py/examples/tour.py (Python)

Code before:
py_lexer = get_lexer_by_name('python')
html_formatter = HtmlFormatter(full=True, style='xcode')
example_dir = os.path.dirname(os.path.realpath(__file__))

_app_host = '127.0.0.1'
_app_port = '10102'


class Example:
    def __init__(self, filename: str, title: str, description: str, source: str):
        self.name = os.path.splitext(filename)[0]
        self.filename = filename
        self.title = title
        self.description = description
        self.source = source
        self.code = highlight(source, py_lexer, html_formatter)
        self.previous_example: Optional[Example] = None
        self.next_example: Optional[Example] = None
        self.process: Optional[subprocess.Popen] = None
        self.is_app = source.find('@app(') > 0

    async def start(self):
        if self.is_app:
            self.process = subprocess.Popen(
                [sys.executable, '-m', 'uvicorn', '--port', _app_port, f'examples.{self.name}:main'],
                env=self.adjust_env_for_platform(dict(H2O_WAVE_EXTERNAL_ADDRESS=f'http://{_app_host}:{_app_port}')))
        else:
            self.process = subprocess.Popen([sys.executable, os.path.join(example_dir, self.filename)])

    async def stop(self):
        if self.process and self.process.returncode is None:
            self.process.terminate()
            self.process.wait()

    def adjust_env_for_platform(self, env):
        """ Add required platform-specific adjustments to env.
        """
        if sys.platform.startswith('win'):
            self._add_systemroot_to_env_win32(env)

    def _add_systemroot_to_env_win32(self, env):
        """ Sets ``%SYSTEMROOT%`` environment variable, if not present in :py:attr:`target_environ` .

        Args:
            env (dict): desired environment variables
        """
        # 'SYSTEMROOT' unnecessary unless 'PATH' is set.
        if env is None:
            return
        # leave SYSTEMROOT alone if set by user
        if 'SYSTEMROOT' in env:

Review comment (suggestion):
If I'm not mistaken, all this is doing is:
"if the platform is Windows and `SYSTEMROOT` is present in the OS env, copy it to `env`"

If so, it's simpler to inline it here instead of additional methods - the methods are static anyway.

Also, it would be good to add a comment why `SYSTEMROOT` needs to be copied to `env`.


Code after:
py_lexer = get_lexer_by_name('python')
html_formatter = HtmlFormatter(full=True, style='xcode')
example_dir = os.path.dirname(os.path.realpath(__file__))

_app_host = '127.0.0.1'
_app_port = '10102'


class Example:
    def __init__(self, filename: str, title: str, description: str, source: str):
        self.name = os.path.splitext(filename)[0]
        self.filename = filename
        self.title = title
        self.description = description
        self.source = source
        self.code = highlight(source, py_lexer, html_formatter)
        self.previous_example: Optional[Example] = None
        self.next_example: Optional[Example] = None
        self.process: Optional[subprocess.Popen] = None
        self.is_app = source.find('@app(') > 0

    async def start(self):
        # The environment passed into Popen must include SYSTEMROOT, otherwise Popen will fail when called
        # inside python during initialization if %PATH% is configured, but without %SYSTEMROOT%.
        env = {'SYSTEMROOT': os.environ['SYSTEMROOT']} if sys.platform.lower().startswith('win') else {}
        if self.is_app:
            self.process = subprocess.Popen(
                [sys.executable, '-m', 'uvicorn', '--port', _app_port, f'examples.{self.name}:main'],
                env=dict(H2O_WAVE_EXTERNAL_ADDRESS=f'http://{_app_host}:{_app_port}', **env))
        else:
            self.process = subprocess.Popen([sys.executable, os.path.join(example_dir, self.filename)], env=env)

    async def stop(self):
        if self.process and self.process.returncode is None:
            self.process.terminate()
            self.process.wait()


active_example: Optional[Example] = None


def read_lines(p: str) -> List[str]:
    with open(p, encoding='utf-8') as f:
        return f.readlines()


def read_file(p: str) -> str:
    with open(p, encoding='utf-8') as f:
        return f.read()