# Python 3.14 lets pdb into a hung process, but not always at once

> The new pdb -p PID option attaches a debugger to a live CPython process with no restart, though one blocked on I/O will keep you waiting.

Original: https://fdetimes.net/en/guides/attach-pdb-to-hung-python-process/

From Python 3.14, `pdb` can attach to a running Python process with a single option: `python -m pdb -p 1234`. The feature rests on PEP 768 and the `sys.remote_exec()` function.

For FDEs this is an everyday problem. A client's data-sync job has sat motionless since last night, and the log has not gained a line. Restart it and the job runs again, but the evidence of where it got stuck goes with it.

This guide walks through a routine you can rehearse on a laptop today: check the preconditions, inspect the stack with read-only tools, attach pdb, exit safely, then set things up so the next incident is less painful. You need Python 3.14, a Linux or macOS machine and sudo rights on it.

## Build a hung process to practice on

Practice on a process you created yourself before working on a client's system. The script below counts through a loop for a few seconds and then stops to wait on `input()`.

```python
# hang.py
import os, time

print("PID:", os.getpid())
for i in range(5):
    time.sleep(1)
    print("tick", i)
answer = input("Waiting... ")
print("Received:", answer)
```

Run `python3.14 hang.py` in one terminal and note the PID. Wait until the script stops at the `input()` line. At that point it looks exactly like a process hung on I/O.

## Three conditions to check before attaching

The first condition is the version. `sys.remote_exec` requires the target process to run CPython with the same major and minor version as the interpreter you use to issue the command. If either is a pre-release, the versions must match exactly. On a client machine, find out which binary the hung process is running, then invoke pdb with that same binary.

```bash
python3.14 --version
```

The second condition is that remote debugging has not been disabled. It can be switched off with the environment variable `PYTHON_DISABLE_REMOTE_DEBUG=1` set before the interpreter starts, with the `-X disable-remote-debug` option, or with the `--without-remote-debug` build flag.

On Linux you can inspect a process's environment as follows (an ordinary shell command, not a Python tool):

```bash
tr '\0' '\n' < /proc/1234/environ | grep PYTHON_DISABLE_REMOTE_DEBUG
```

The third condition is operating-system permission, and this is where people most often get blocked. On Linux you can usually debug your own processes, but Yama's ptrace restrictions can get in the way.

There are two ways to relax them. The first applies only to the process that will be debugged: launch it with `setpriv`, using the same interpreter you will attach with.

```bash
setpriv --ptracer any python3.14 hang.py
```

The second disables the restriction system-wide until the next reboot. The Python documentation warns that this weakens the system's protection and should be used only in environments with low security requirements.

```bash
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
```

In containers, Docker 19.03 and later and containerd 1.6.7 and later, running on Linux kernel 4.8 or later, allow the ptrace syscall inside the container by default.

On macOS the operating system blocks debugging of other processes by default, so the simple route is to attach with `sudo`: processes running as superuser are exempt from that check. The exception is certain binaries belonging to the operating system itself, which System Integrity Protection guards with an extra layer.

Before moving on, you should be able to answer three questions with confidence: which Python version the target runs, whether remote debugging is disabled, and whether you need `sudo`.

## Why look at the stack before attaching pdb?

**Key point:** Look at the stack first, touch the process second.

pdb runs code inside the target process. In production, the first job is to read the process's state without changing anything. That information is often enough to tell which function it is stuck in.

py-spy suits this well. Its `dump` command prints the call stack of every thread without restarting the program or modifying its code. Add `--locals` to see local variables and `--native` to include native frames.

```bash
sudo py-spy dump --pid 1234 --locals
```

Attaching by PID usually needs root on Linux and always needs it on macOS. In Docker, if you are blocked, run the container with `--cap-add SYS_PTRACE`.

For asyncio applications, Python 3.14 ships two commands. `python -m asyncio ps 1234` prints a table of pending tasks, and `python -m asyncio pstree 1234` prints the tree of await relationships. Both only read the target's state and execute no code inside it. A coroutine waiting forever on another coroutine will show up in that tree.

If the environment already has Python 3.15, the `profiling.sampling` module offers a `dump` command that reads a running process's stack once and exits, handy for investigating a hang. By default it shows only the main thread. Add `-a` to see every thread, and use `--async-aware` when working with asyncio.

## Attaching pdb, and why it sometimes won't get in straight away

Once the stack tells you where to look, open a second terminal and attach:

```bash
python3.14 -m pdb -p 1234
```

With `hang.py`, this command will not get in immediately. The pdb documentation is explicit: if the process is stuck in a system call or waiting on I/O, pdb can attach only when the next bytecode instruction runs, or when the process receives a signal.

An experiment with `sys.remote_exec` on CPython 3.14 recorded the same behavior: when the target was waiting at `input()`, the injected script ran only after the `input` call returned.

Verify it yourself. Go back to the first terminal, type a line and press Enter. As soon as `input()` returns, the pdb session opens in the second terminal. If you attach while the `time.sleep(1)` loop is still running, pdb gets in almost instantly, because the process resumes executing bytecode every second.

Once inside, pressing Ctrl-C on Unix makes the pdb client send SIGINT to the target process; according to a comment in the pdb source on the 3.14 branch, this interrupts I/O on the main thread. From there, the familiar pdb commands such as `where`, `p` and `up` let you read frames and variables.

## Exiting without killing the client's process

In the pdb code on the 3.14 branch, the remote debug server has a detach step: it removes the debugger and closes the socket without raising `BdbQuit`. That step is called after the user types `quit`. The pdb documentation, however, describes the `quit` command in general as aborting the program being debugged.

The two sources disagree, so do not try it for the first time on a client's machine. Attach to `hang.py`, type `quit`, and check whether the process is still alive. Only once you have seen the behavior for yourself, on the exact Python version the client runs, should you do it in production.

## Next time, prepare from inside the code

Attaching from outside is most useful when nothing was set up in advance. For services you deploy yourself there is a cheaper option: `faulthandler.register(signum)` installs a handler so that when the process receives that signal, it writes the traceback of every thread to a file, stderr by default. The function is not available on Windows.

```python
import faulthandler, signal
faulthandler.register(signal.SIGUSR1)
```

When the service hangs, running `kill -USR1 ` puts the traceback in the log. No ptrace is needed, and no negotiation over root access with the client's operations team.

## How this skill shows up on client sites

On a client site you rarely have root, you often meet tightly locked-down containers, and someone is always waiting for the system to come back. The order in this guide follows those constraints: check version and permissions, read the stack with read-only tools, and only then attach pdb.

When asking for access, say exactly what you need, for example `SYS_PTRACE` on one container for 15 minutes, rather than asking for root in general.

On a CV, a specific line such as "diagnosed a hung production Python job with py-spy and pdb -p, without a restart" carries far more weight than "proficient in Python". In an interview, walk through that same sequence and explain why you read the stack before attaching a debugger.

The next time someone says "just restart it", ask for five minutes to read the stack first. Those five minutes often decide whether the bug is fixed at the root or comes back tomorrow night.

**Try this week:**

- Run the sample hung script from this guide with Python 3.14, attach to it with python -m pdb -p PID, and watch the command take effect only after input() returns.
- Install py-spy and run py-spy dump with --locals against a Python process running on your machine.
- Add faulthandler.register(signal.SIGUSR1) to an internal service, then send kill -USR1 to see the traceback of every thread.

## Sources

- [What’s new in Python 3.14](https://docs.python.org/3/whatsnew/3.14.html)

- [pdb — The Python Debugger](https://docs.python.org/3/library/pdb.html)

- [sys — System-specific parameters and functions](https://docs.python.org/3/library/sys.html#sys.remote_exec)

- [Checking Out CPython 3.14's remote debugging protocol](https://rtpg.co/2025/06/28/checking-out-sys-remote-exec/)

- [Remote debugging attachment protocol](https://docs.python.org/3/howto/remote_debugging.html)

- [cpython/Lib/pdb.py (nhánh 3.14)](https://raw.githubusercontent.com/python/cpython/3.14/Lib/pdb.py)

- [Command-line introspection tools](https://docs.python.org/3/library/asyncio-tools.html)

- [py-spy README](https://raw.githubusercontent.com/benfred/py-spy/master/README.md)

- [profiling.sampling](https://docs.python.org/3/library/profiling.sampling.html)

- [faulthandler — Dump the Python traceback](https://docs.python.org/3/library/faulthandler.html)
