| 1 |
import errno |
| 2 |
import os |
| 3 |
import sys |
| 4 |
import types |
| 5 |
|
| 6 |
|
| 7 |
CAN_USE_PYREPL: bool |
| 8 |
FAIL_REASON: str |
| 9 |
try: |
| 10 |
if sys.platform == "win32" and sys.getwindowsversion().build < 10586: |
| 11 |
raise RuntimeError("Windows 10 TH2 or later required") |
| 12 |
if not os.isatty(sys.stdin.fileno()): |
| 13 |
raise OSError(errno.ENOTTY, "tty required", "stdin") |
| 14 |
from .simple_interact import check |
| 15 |
if err := check(): |
| 16 |
raise RuntimeError(err) |
| 17 |
except Exception as e: |
| 18 |
CAN_USE_PYREPL = False |
| 19 |
FAIL_REASON = f"warning: can't use pyrepl: {e}" |
| 20 |
else: |
| 21 |
CAN_USE_PYREPL = True |
| 22 |
FAIL_REASON = "" |
| 23 |
|
| 24 |
|
| 25 |
def interactive_console(mainmodule=None, quiet=False, pythonstartup=False): |
| 26 |
if not CAN_USE_PYREPL: |
| 27 |
if not os.getenv('PYTHON_BASIC_REPL') and FAIL_REASON: |
| 28 |
from .trace import trace |
| 29 |
trace(FAIL_REASON) |
| 30 |
print(FAIL_REASON, file=sys.stderr) |
| 31 |
return sys._baserepl() |
| 32 |
|
| 33 |
if not mainmodule: |
| 34 |
mainmodule = types.ModuleType("__main__") |
| 35 |
|
| 36 |
namespace = mainmodule.__dict__ |
| 37 |
|
| 38 |
# sys._baserepl() above does this internally, we do it here |
| 39 |
startup_path = os.getenv("PYTHONSTARTUP") |
| 40 |
if pythonstartup and startup_path: |
| 41 |
sys.audit("cpython.run_startup", startup_path) |
| 42 |
|
| 43 |
import tokenize |
| 44 |
with tokenize.open(startup_path) as f: |
| 45 |
startup_code = compile(f.read(), startup_path, "exec") |
| 46 |
exec(startup_code, namespace) |
| 47 |
|
| 48 |
# set sys.{ps1,ps2} just before invoking the interactive interpreter. This |
| 49 |
# mimics what CPython does in pythonrun.c |
| 50 |
if not hasattr(sys, "ps1"): |
| 51 |
sys.ps1 = ">>> " |
| 52 |
if not hasattr(sys, "ps2"): |
| 53 |
sys.ps2 = "... " |
| 54 |
|
| 55 |
from .console import InteractiveColoredConsole |
| 56 |
from .simple_interact import run_multiline_interactive_console |
| 57 |
console = InteractiveColoredConsole(namespace, filename="<stdin>") |
| 58 |
run_multiline_interactive_console(console) |