replwrap - Control read-eval-print-loops¶
Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
New in version 3.3.
-
class
pexpect.replwrap.
REPLWrapper
(cmd_or_spawn, orig_prompt, prompt_change, new_prompt='[PEXPECT_PROMPT>', continuation_prompt='[PEXPECT_PROMPT+', extra_init_cmd=None)[source]¶ Wrapper for a REPL.
Parameters: - cmd_or_spawn – This can either be an instance of
pexpect.spawn
in which a REPL has already been started, or a str command to start a new REPL process. - orig_prompt (str) – The prompt to expect at first.
- prompt_change (str) – A command to change the prompt to something more
unique. If this is
None
, the prompt will not be changed. This will be formatted with the new and continuation prompts as positional parameters, so you can use{}
style formatting to insert them into the command. - new_prompt (str) – The more unique prompt to expect after the change.
- extra_init_cmd (str) – Commands to do extra initialisation, such as disabling pagers.
-
run_command
(command, timeout=-1, async_=False)[source]¶ Send a command to the REPL, wait for and return output.
Parameters: - command (str) – The command to send. Trailing newlines are not needed.
This should be a complete block of input that will trigger execution;
if a continuation prompt is found after sending input,
ValueError
will be raised. - timeout (int) – How long to wait for the next prompt. -1 means the
default from the
pexpect.spawn
object (default 30 seconds). None means to wait indefinitely. - async (bool) – On Python 3.4, or Python 3.3 with asyncio
installed, passing
async_=True
will make this return anasyncio
Future, which you can yield from to get the same result that this method would normally give directly.
- command (str) – The command to send. Trailing newlines are not needed.
This should be a complete block of input that will trigger execution;
if a continuation prompt is found after sending input,
- cmd_or_spawn – This can either be an instance of
-
pexpect.replwrap.
PEXPECT_PROMPT
¶ A string that can be used as a prompt, and is unlikely to be found in output.
Using the objects above, it is easy to wrap a REPL. For instance, to use a Python shell:
py = REPLWrapper("python", ">>> ", "import sys; sys.ps1={!r}; sys.ps2={!r}")
py.run_command("4+7")
Convenience functions are provided for Python and bash shells:
-
pexpect.replwrap.
python
(command='python')[source]¶ Start a Python shell and return a
REPLWrapper
object.
-
pexpect.replwrap.
bash
(command='bash')[source]¶ Start a bash shell and return a
REPLWrapper
object.