Top Related Projects
Library for building powerful interactive command line applications in Python
Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.
bpython - A fancy curses interface to the Python interactive interpreter
Awesome autocompletion, static analysis and refactoring library for python
Python composable command line interface toolkit
Quick Overview
ptpython is an advanced Python REPL (Read-Eval-Print Loop) built on top of the prompt_toolkit library. It offers a feature-rich interactive Python shell with syntax highlighting, multiline editing, and code completion, providing a more powerful alternative to the standard Python REPL.
Pros
- Enhanced code completion and syntax highlighting
- Multiline editing with in-editor syntax validation
- Customizable interface with themes and key bindings
- Integration with IPython for additional features
Cons
- Slightly slower startup time compared to the standard Python REPL
- May have occasional compatibility issues with some Python packages
- Requires additional installation and setup compared to the built-in REPL
Code Examples
- Basic usage:
from ptpython.repl import embed
embed(globals(), locals())
This code embeds ptpython in your Python script, allowing you to drop into an interactive shell.
- Customizing the REPL:
from ptpython.repl import embed
def configure(repl):
repl.vi_mode = True
repl.confirm_exit = False
embed(globals(), locals(), configure=configure)
This example customizes the REPL by enabling vi mode and disabling exit confirmation.
- Using ptpython as a debugger:
from ptpython.repl import embed
def my_function():
x = 10
y = 20
embed(globals(), locals()) # Start interactive debugging here
return x + y
result = my_function()
This code demonstrates how to use ptpython for interactive debugging within a function.
Getting Started
To get started with ptpython:
- Install ptpython:
pip install ptpython
- Launch the interactive shell:
ptpython
- For IPython integration, install ptipython:
pip install ptipython
- Launch the IPython-integrated shell:
ptipython
Competitor Comparisons
Library for building powerful interactive command line applications in Python
Pros of python-prompt-toolkit
- More versatile, can be used for various command-line interfaces beyond Python REPLs
- Offers a wider range of customization options and features
- Provides a solid foundation for building complex interactive applications
Cons of python-prompt-toolkit
- Steeper learning curve due to its broader scope and more extensive API
- Requires more setup and configuration for basic Python REPL functionality
- May have unnecessary features for those solely interested in a Python REPL
Code Comparison
ptpython:
from ptpython.repl import embed
embed(globals(), locals())
python-prompt-toolkit:
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
while True:
user_input = prompt('> ', history=FileHistory('history.txt'),
auto_suggest=AutoSuggestFromHistory())
print(f"You entered: {user_input}")
This comparison shows that ptpython provides a more straightforward setup for a Python REPL, while python-prompt-toolkit offers more flexibility but requires additional configuration for similar functionality.
Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.
Pros of IPython
- More extensive feature set, including magic commands and shell integration
- Larger community and ecosystem with numerous extensions
- Better documentation and learning resources
Cons of IPython
- Heavier and more complex, which can lead to slower startup times
- Less customizable in terms of appearance and behavior
- Steeper learning curve for advanced features
Code Comparison
IPython:
%timeit [i**2 for i in range(1000)]
!ls -l
%matplotlib inline
import numpy as np
np.random.rand(10)
ptpython:
# No direct equivalent for magic commands
# Standard Python syntax for timing and system commands
import time
start = time.time()
[i**2 for i in range(1000)]
print(f"Time: {time.time() - start}")
import os
os.system("ls -l")
Summary
IPython offers a more feature-rich environment with magic commands and extensive integrations, making it ideal for data science and interactive computing. ptpython, built on prompt-toolkit, provides a lightweight and customizable alternative with a focus on enhanced REPL experience. While IPython has a larger ecosystem, ptpython offers better performance and customization options for those who prefer a simpler, more tailored Python shell.
bpython - A fancy curses interface to the Python interactive interpreter
Pros of bpython
- Lightweight and fast, with minimal dependencies
- Offers syntax highlighting and auto-indentation out of the box
- Provides a simple and intuitive interface for beginners
Cons of bpython
- Less customizable compared to ptpython
- Limited multi-line editing capabilities
- Fewer advanced features for power users
Code Comparison
bpython:
>>> import math
>>> math.
math.acos math.atan math.ceil math.cos math.exp
math.asin math.atan2 math.copysign math.cosh math.expm1
ptpython:
>>> import math
>>> math.
acos() atan() ceil() cos() exp()
asin() atan2() copysign() cosh() expm1()
Both projects offer enhanced Python REPLs with features like auto-completion and syntax highlighting. bpython focuses on simplicity and ease of use, making it ideal for beginners or quick scripting tasks. ptpython, built on the prompt-toolkit library, provides more advanced features and customization options, catering to power users and those who prefer a more tailored experience. The code comparison shows similar auto-completion functionality, with ptpython offering a slightly more detailed display of function signatures.
Awesome autocompletion, static analysis and refactoring library for python
Pros of Jedi
- Focused on static analysis and autocompletion for Python
- Widely used as a backend for various IDEs and editors
- Provides more in-depth code intelligence and refactoring capabilities
Cons of Jedi
- Not a standalone REPL environment like ptpython
- Requires integration with other tools for interactive use
- May have a steeper learning curve for direct usage
Code Comparison
Jedi (used as a library):
import jedi
script = jedi.Script("import os\nos.")
completions = script.complete(1, 3)
for c in completions:
print(c.name)
ptpython (interactive REPL usage):
from ptpython.repl import embed
embed(globals(), locals())
# Now in interactive REPL with autocompletion
While Jedi focuses on providing code intelligence and autocompletion as a library, ptpython offers a full-featured interactive Python REPL with syntax highlighting, multiline editing, and autocompletion (which may use Jedi under the hood). Jedi is more suitable for integration into development tools, while ptpython is designed for direct use as an enhanced Python shell.
Python composable command line interface toolkit
Pros of Click
- Designed for creating command-line interfaces (CLIs), offering a more focused approach for building CLI applications
- Extensive documentation and a large community, making it easier to find solutions and support
- Provides decorators for easy command and option definitions, simplifying the process of creating complex CLIs
Cons of Click
- Limited to CLI development, lacking the interactive REPL capabilities of ptpython
- May require more setup for simple scripts compared to ptpython's immediate interactive environment
- Less suitable for exploratory programming or quick Python experimentation
Code Comparison
Click example:
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
for _ in range(count):
click.echo(f"Hello, {name}!")
ptpython example:
from ptpython.repl import embed
def greet(name, count=1):
for _ in range(count):
print(f"Hello, {name}!")
embed(globals(), locals())
While Click focuses on building CLI applications with structured commands and options, ptpython provides an enhanced interactive Python shell for exploration and development.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ptpython
|Build Status| |PyPI| |License|
A better Python REPL
::
pip install ptpython
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/example1.png
Ptpython is an advanced Python REPL. It should work on all Python versions from 2.6 up to 3.11 and work cross platform (Linux, BSD, OS X and Windows).
Note: this version of ptpython requires at least Python 3.6. Install ptpython 2.0.5 for older Python versions.
Installation
Install it using pip:
::
pip install ptpython
Start it by typing ptpython
.
Features
- Syntax highlighting.
- Multiline editing (the up arrow works).
- Autocompletion.
- Mouse support. [1]
- Support for color schemes.
- Support for
bracketed paste <https://cirw.in/blog/bracketed-paste>
_ [2]. - Both Vi and Emacs key bindings.
- Support for double width (Chinese) characters.
- ... and many other things.
[1] Disabled by default. (Enable in the menu.)
[2] If the terminal supports it (most terminals do), this allows pasting without going into paste mode. It will keep the indentation.
Command Line Options
The help menu shows basic command-line options.
::
$ ptpython --help
usage: ptpython [-h] [--vi] [-i] [--light-bg] [--dark-bg] [--config-file CONFIG_FILE]
[--history-file HISTORY_FILE] [-V]
[args ...]
ptpython: Interactive Python shell.
positional arguments:
args Script and arguments
optional arguments:
-h, --help show this help message and exit
--vi Enable Vi key bindings
-i, --interactive Start interactive shell after executing this file.
--asyncio Run an asyncio event loop to support top-level "await".
--light-bg Run on a light background (use dark colors for text).
--dark-bg Run on a dark background (use light colors for text).
--config-file CONFIG_FILE
Location of configuration file.
--history-file HISTORY_FILE
Location of history file.
-V, --version show program's version number and exit
environment variables:
PTPYTHON_CONFIG_HOME: a configuration directory to use
PYTHONSTARTUP: file executed on interactive startup (no default)
pt_repr: A nicer repr with colors
When classes implement a __pt_repr__
method, this will be used instead of
__repr__
for printing. Any prompt_toolkit "formatted text" <https://python-prompt-toolkit.readthedocs.io/en/master/pages/printing_text.html>
_
can be returned from here. In order to avoid writing a __repr__
as well,
the ptpython.utils.ptrepr_to_repr
decorator can be applied. For instance:
.. code:: python
from ptpython.utils import ptrepr_to_repr
from prompt_toolkit.formatted_text import HTML
@ptrepr_to_repr
class MyClass:
def __pt_repr__(self):
return HTML('<yellow>Hello world!</yellow>')
More screenshots
The configuration menu:
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/ptpython-menu.png
The history page and its help:
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/ptpython-history-help.png
Autocompletion:
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/file-completion.png
Embedding the REPL
Embedding the REPL in any Python application is easy:
.. code:: python
from ptpython.repl import embed
embed(globals(), locals())
You can make ptpython your default Python REPL by creating a PYTHONSTARTUP file <https://docs.python.org/3/tutorial/appendix.html#the-interactive-startup-file>
_ containing code
like this:
.. code:: python
import sys try: from ptpython.repl import embed except ImportError: print("ptpython is not available: falling back to standard prompt") else: sys.exit(embed(globals(), locals()))
Note config file support currently only works when invoking ptpython
directly.
That it, the config file will be ignored when embedding ptpython in an application.
Multiline editing
Multi-line editing mode will automatically turn on when you press enter after a colon.
To execute the input in multi-line mode, you can either press Alt+Enter
, or
Esc
followed by Enter
. (If you want the first to work in the OS X
terminal, you have to check the "Use option as meta key" checkbox in your
terminal settings. For iTerm2, you have to check "Left option acts as +Esc" in
the options.)
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/multiline.png
Syntax validation
Before execution, ptpython
will see whether the input is syntactically
correct Python code. If not, it will show a warning, and move the cursor to the
error.
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/validation.png
Asyncio REPL and top level await
In order to get top-level await
support, start ptpython as follows:
.. code::
ptpython --asyncio
This will spawn an asyncio event loop and embed the async REPL in the event
loop. After this, top-level await will work and statements like await asyncio.sleep(10)
will execute.
Additional features
Running system commands: Press Meta-!
in Emacs mode or just !
in Vi
navigation mode to see the "Shell command" prompt. There you can enter system
commands without leaving the REPL.
Selecting text: Press Control+Space
in Emacs mode or V
(major V) in Vi
navigation mode.
Configuration
It is possible to create a config.py
file to customize configuration.
ptpython will look in an appropriate platform-specific directory via appdirs <https://pypi.org/project/appdirs/>
. See the appdirs
documentation for the
precise location for your platform. A PTPYTHON_CONFIG_HOME
environment
variable, if set, can also be used to explicitly override where configuration
is looked for.
Have a look at this example to see what is possible:
config.py <https://github.com/jonathanslenders/ptpython/blob/master/examples/ptpython_config/config.py>
_
Note config file support currently only works when invoking ptpython
directly.
That it, the config file will be ignored when embedding ptpython in an application.
IPython support
Run ptipython
(prompt_toolkit - IPython), to get a nice interactive shell
with all the power that IPython has to offer, like magic functions and shell
integration. Make sure that IPython has been installed. (pip install ipython
)
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/ipython.png
This is also available for embedding:
.. code:: python
from ptpython.ipython import embed
embed(globals(), locals())
Django support
django-extensions <https://github.com/django-extensions/django-extensions>
_
has a shell_plus
management command. When ptpython
has been installed,
it will by default use ptpython
or ptipython
.
PDB
There is an experimental PDB replacement: ptpdb <https://github.com/jonathanslenders/ptpdb>
_.
Windows support
prompt_toolkit
and ptpython
works better on Linux and OS X than on
Windows. Some things might not work, but it is usable:
.. image :: https://github.com/jonathanslenders/ptpython/raw/master/docs/images/windows.png
Windows terminal integration
If you are using the `Windows Terminal <https://aka.ms/terminal>`_ and want to
integrate ``ptpython`` as a profile, go to *Settings -> Open JSON file* and add the
following profile under *profiles.list*:
.. code-block:: JSON
{
"commandline": "%SystemRoot%\\System32\\cmd.exe /k ptpython",
"guid": "{f91d49a3-741b-409c-8a15-c4360649121f}",
"hidden": false,
"icon": "https://upload.wikimedia.org/wikipedia/commons/e/e6/Python_Windows_interpreter_icon_2006%E2%80%932016_Tiny.png",
"name": "ptpython@cmd"
}
FAQ
***
**Q**: The ``Ctrl-S`` forward search doesn't work and freezes my terminal.
**A**: Try to run ``stty -ixon`` in your terminal to disable flow control.
**Q**: The ``Meta``-key doesn't work.
**A**: For some terminals you have to enable the Alt-key to act as meta key, but you
can also type ``Escape`` before any key instead.
Alternatives
************
- `BPython <http://bpython-interpreter.org/downloads.html>`_
- `IPython <https://ipython.org/>`_
If you find another alternative, you can create an issue and we'll list it
here. If you find a nice feature somewhere that is missing in ``ptpython``,
also create a GitHub issue and maybe we'll implement it.
Special thanks to
*****************
- `Pygments <http://pygments.org/>`_: Syntax highlighter.
- `Jedi <http://jedi.jedidjah.ch/en/latest/>`_: Autocompletion library.
- `wcwidth <https://github.com/jquast/wcwidth>`_: Determine columns needed for a wide characters.
- `prompt_toolkit <http://github.com/jonathanslenders/python-prompt-toolkit>`_ for the interface.
.. |Build Status| image:: https://github.com/prompt-toolkit/ptpython/actions/workflows/test.yaml/badge.svg
:target: https://github.com/prompt-toolkit/ptpython/actions/workflows/test.yaml
.. |License| image:: https://img.shields.io/github/license/prompt-toolkit/ptpython.svg
:target: https://github.com/prompt-toolkit/ptpython/blob/master/LICENSE
.. |PyPI| image:: https://img.shields.io/pypi/v/ptpython.svg
:target: https://pypi.org/project/ptpython/
:alt: Latest Version
Top Related Projects
Library for building powerful interactive command line applications in Python
Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.
bpython - A fancy curses interface to the Python interactive interpreter
Awesome autocompletion, static analysis and refactoring library for python
Python composable command line interface toolkit
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot