Skip to content

Python SDK: Add support for non-terminal-based applications in aipnut #738

@ksaylor

Description

@ksaylor

Description

I am encountering an issue when building an executable using cx_freeze that is not terminal-based. The current implementation of ainput in util.py leads to an AttributeError: 'NoneType' object has no attribute 'write'. To resolve this issue, I am requesting an update to the ainput function.

Current Code

async def ainput(string: str, printer: Callable = sys.stdout.write) -> str:
    """Async version of input

    Args:
        string (str): prompt string
        printer (Callable): Callable to display prompt. Defaults to sys.stdout.write.

    Returns:
        str: Input read from console
    """
    await asyncio.get_event_loop().run_in_executor(None, lambda s=string: printer(s + " "))  # type: ignore
    return await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)

Proposed Code Change

async def ainput(string: str, printer: Callable = None) -> str:
    """Async version of input

    Args:
        string (str): prompt string
        printer (Callable): Callable to display prompt. Defaults to sys.stdout.write.

    Returns:
        str: Input read from console
    """
    if not printer:
        printer = sys.stdout.write
    await asyncio.get_event_loop().run_in_executor(None, lambda s=string: printer(s + " "))  # type: ignore
    return await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)

Reason for the Update

When running an executable built with the current version of util.py, using cx_freeze for a non-terminal-based application, the following error occurs (this is snippet of the Traceback):

in <module> async def ainput(string: str, printer: Callable = sys.stdout.write) -> str:
                                                   ^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'write'

This error occurs because sys.stdout is None in a non-terminal environment, leading to the AttributeError. By modifying the default value for printer to None and setting it to sys.stdout.write within the function if it is not provided, this issue is resolved.

Thank you for considering this change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions