Modify CPy #1: Changing the Python REPL prompt
Introduction
This is the first in a series of posts that show how to make micro
modifications to CPython v3.7.0. If you’d like to follow along you can
grab a copy of the CPython source from either the CPython Github
repository or the official tarball. If using the git repo make sure to
switch over to v3.7.0 (git checkout v3.7.0
). To keep all the build
related files separate from the source, I’m going to make a directory
named build inside of the source directory. Now the command
../configure && make
inside of this directory will compile a build
that we can test. For more information on CPython I’d recommend
browsing the following helpful resources:
- https://devguide.python.org/exploring
- https://docs.python.org/3/c-api
- https://docs.python.org/3/extending/index.html
In this post we’ll do the most simple change; that is, change the
Python REPL prompt to display MODFIY_CPy>>>
instead of >>>
. This
will make it obvious that you’ve started the correct/incorrect python
binary in later posts.
Where does this prompt get set?
In the output from running a recursive grep on all C source and header
files we can see that the string: ">>> "
, is used on line 110 in the
Python/pythonrun.c file.
$ grep -rn --include='*.[ch]' '(">>> ")' Python-3.7.0
Python-3.7.0/Python/pythonrun.c:110: _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
The function it’s used in is called PyRun_InteractiveLoopFlags
,
which, according to the documentation, can:
Read and execute statements from a file associated with an interactive device until EOF is reached. The user will be prompted using sys.ps1 and sys.ps2. filename is decoded from the filesystem encoding (sys.getfilesystemencoding()). Returns 0 at EOF or a negative number upon failure.
Making the change
After making the change and recompiling, see if our change shows up in
Python REPL by running ./python
inside the build directory.
Python 3.7.0 (default, Jan 02 2019, 20:46:52)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
MODIFY_CPy>>>