ipykernel_launcher.py
Jupyter Notebook error
unrecognized arguments
Python debugging
fix Jupyter issues

How to fix ipykernel_launcher.py error unrecognized arguments in jupyter?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

The error "ipykernel_launcher.py: error: unrecognized arguments" occurs when code using argparse (or similar argument parsers) runs in a Jupyter notebook. The Jupyter kernel process passes its own command-line arguments (like -f kernel-xxxx.json), which argparse does not recognize and treats as errors. The fix is to use parse_known_args() instead of parse_args(), which ignores unrecognized arguments. This article covers the cause, multiple fixes, and how to handle argument parsing in notebooks properly.

The Error

python
1# In a Jupyter notebook cell:
2import argparse
3
4parser = argparse.ArgumentParser()
5parser.add_argument("--epochs", type=int, default=10)
6args = parser.parse_args()  # ERROR!
 
usage: ipykernel_launcher.py [-h] [--epochs EPOCHS]
ipykernel_launcher.py: error: unrecognized arguments:
  -f /Users/alice/Library/Jupyter/runtime/kernel-abc123.json

Jupyter passes -f <connection_file> to the kernel process. parse_args() fails because it does not know about -f.

Why This Happens

When you run a Jupyter notebook, the kernel is launched as:

 
python -m ipykernel_launcher -f kernel-abc123.json

sys.argv in a notebook cell looks like:

python
1import sys
2print(sys.argv)
3# ['/path/to/ipykernel_launcher.py', '-f',
4#  '/Users/alice/Library/Jupyter/runtime/kernel-abc123.json']

argparse.parse_args() reads sys.argv[1:] by default. Since it does not know about -f, it raises an error.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument("--epochs", type=int, default=10)
5parser.add_argument("--lr", type=float, default=0.001)
6
7args, unknown = parser.parse_known_args()
8# args.epochs = 10, args.lr = 0.001
9# unknown = ['-f', '/path/to/kernel-abc123.json']
10
11print(f"Epochs: {args.epochs}, LR: {args.lr}")

parse_known_args() parses recognized arguments and returns unrecognized ones separately instead of raising an error. This is the simplest fix and works in both scripts and notebooks.

Fix 2: Pass an Empty List

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument("--epochs", type=int, default=10)
5
6# Override sys.argv by passing an empty list
7args = parser.parse_args([])
8print(args.epochs)  # 10 (uses default)
9
10# Or pass explicit arguments
11args = parser.parse_args(["--epochs", "50"])
12print(args.epochs)  # 50

This is useful when you want to hardcode arguments in a notebook for experimentation.

Fix 3: Check if Running in Jupyter

python
1import argparse
2import sys
3
4def is_notebook():
5    try:
6        from IPython import get_ipython
7        if get_ipython() is not None:
8            return True
9    except ImportError:
10        pass
11    return False
12
13parser = argparse.ArgumentParser()
14parser.add_argument("--epochs", type=int, default=10)
15parser.add_argument("--batch-size", type=int, default=32)
16
17if is_notebook():
18    args = parser.parse_args([])  # Use defaults in notebook
19else:
20    args = parser.parse_args()    # Parse sys.argv in script
21
22print(f"Epochs: {args.epochs}, Batch size: {args.batch_size}")

This lets the same code work as both a script and a notebook.

Fix 4: Clear sys.argv

python
1import sys
2sys.argv = [sys.argv[0]]  # Keep only the script name
3
4import argparse
5parser = argparse.ArgumentParser()
6parser.add_argument("--epochs", type=int, default=10)
7args = parser.parse_args()  # Now works — no extra args

This is a quick hack but can break other libraries that read sys.argv.

Fix 5: Use a Configuration Dict Instead

For notebook-heavy workflows, replace argparse with a simple config dictionary:

python
1# Instead of argparse
2config = {
3    "epochs": 10,
4    "lr": 0.001,
5    "batch_size": 32,
6    "model": "resnet50"
7}
8
9# Easy to modify in a notebook cell
10config["epochs"] = 50
11config["lr"] = 0.0005
12
13# Access like args
14print(f"Training for {config['epochs']} epochs")

For more structure, use a dataclass:

python
1from dataclasses import dataclass
2
3@dataclass
4class Config:
5    epochs: int = 10
6    lr: float = 0.001
7    batch_size: int = 32
8
9config = Config(epochs=50)
10print(config.epochs)  # 50

Handling Third-Party Libraries

Some libraries (like absl-py, tensorflow) use their own flag parsing that causes the same issue:

python
1# absl-py / TensorFlow flags
2from absl import flags
3flags.FLAGS([''])  # Initialize with empty args to avoid the error
4
5# Or for TensorFlow specifically
6import tensorflow as tf
7# TF 2.x generally handles this internally

Common Pitfalls

  • Using parse_args() in code that runs in both scripts and notebooks: parse_args() always reads sys.argv, which contains kernel arguments in Jupyter. Use parse_known_args() as a universal solution that works in both environments.
  • Clearing sys.argv globally: Setting sys.argv = [sys.argv[0]] affects all code in the session. Other libraries or notebook extensions that depend on sys.argv may break. Prefer parse_known_args() or passing an explicit empty list.
  • Not handling unknown args from parse_known_args(): parse_known_args() returns a tuple (args, unknown). If you only capture one return value, you get the tuple, not just the args. Always unpack both: args, _ = parser.parse_known_args().
  • Importing argparse-using modules at the top level: If a module calls parse_args() during import (in module-level code), it fails immediately when imported in a notebook. Move argument parsing inside if __name__ == "__main__": in library modules.
  • Forgetting to test in both environments: Code using parse_known_args() silently ignores unknown arguments. If you accidentally typo a flag name (--epohcs instead of --epochs), it silently uses the default. Add validation after parsing to catch this.

Summary

  • The error occurs because Jupyter's kernel passes -f kernel.json to sys.argv, which argparse does not recognize
  • Use parse_known_args() instead of parse_args() — the simplest and most portable fix
  • Pass an explicit empty list parse_args([]) to use defaults in notebooks
  • Use is_notebook() detection for code that must work as both a script and a notebook
  • For notebook-first workflows, replace argparse with config dictionaries or dataclasses
  • Always guard module-level argument parsing with if __name__ == "__main__": to prevent import-time errors

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.