Skip to content

Instantly share code, notes, and snippets.

@DocMinus
Created March 24, 2021 13:29
Show Gist options
  • Save DocMinus/ff903221e716ef9b7e5621c017941351 to your computer and use it in GitHub Desktop.
Save DocMinus/ff903221e716ef9b7e5621c017941351 to your computer and use it in GitHub Desktop.
Argparse in Jupyter Notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Using argparse in Jupyter\n",
"Multiple scenarious possible, e.g. when obtaining cmd line script and adopting to Jupyter<br>\n",
"Or developing in Jupyter with intention to use in cmd line script later<br>\n",
"Or simply for wanting to use argparse in Jupyter.<br>\n",
"Or whatever else :D"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import argparse"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"parser = argparse.ArgumentParser()\n",
"\n",
"parser.add_argument(\"--input\", type=str, help=\"input helper\", default='sometext')\n",
"parser.add_argument(\"--number\", type=int, help=\"some number\", default=600)\n",
"args = parser.parse_args('') # important to put '' in Jupyter otherwise it will complain"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"#config = dict()\n",
"#for arg in vars(args):\n",
"# config[arg] = getattr(args, arg)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# much simpler!\n",
"config = vars(args)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Args input & number: sometext 600\n"
]
}
],
"source": [
"print(\"Args input & number:\", config['input'], \" \", config['number'])"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--input has changed: a new input text!!\n"
]
}
],
"source": [
"config['input'] = \"a new input text!!\"\n",
"print(\"--input has changed: \", config['input'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment