Skip to content

Commit

Permalink
Convert install.py source to nb
Browse files Browse the repository at this point in the history
  • Loading branch information
hugetim committed Sep 29, 2023
1 parent cc8ed29 commit b0e8967
Show file tree
Hide file tree
Showing 7 changed files with 307 additions and 9 deletions.
1 change: 0 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,4 @@ ReviewNB gives us visual diffs for notebooks and enables PR comments specific to
* You can preview the docs locally by running [nbdev_preview](https://nbdev.fast.ai/tutorials/tutorial.html#preview-your-docs). While in preview mode, you can make updates to notebooks and they will be reflected (after a small delay) in your browser.

## Specifics to be aware of
* There is one `.py` file not derived from the notebooks: install.py
* The [@patch_to](https://fastcore.fast.ai/basics.html#patch_to) decorator is occasionally used to break up class definitions into separate cells.
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ interface](https://www.stata.com/features/overview/graphical-user-interface/)?
- rich text:
1. lists
2. **Headings**
3. <img align="left" width="54" height="18.6" src="index_files/figure-commonmark/b7f3a71a-1-image-2.png">
3. <img align="left" width="54" height="18.6" src="index_files/figure-commonmark/226326ec-1-image-2.png">
4. [links](https://hugetim.github.io/nbstata/)
5. math: $y_{it}=\beta_0+\varepsilon_{it}$

Expand All @@ -80,8 +80,7 @@ output.
`nbstata` is being developed using
[nbdev](https://nbdev.fast.ai/blog/posts/2022-07-28-nbdev2/#whats-nbdev).
The `/nbs` directory is where edits to the source code should be made.
(The python code is then exported to the `/nbdev` library folder.) The
one exception is `install.py`.
(The python code is then exported to the `/nbdev` library folder.)

For more, see
[CONTRIBUTING.md](https://github.com/hugetim/nbstata/blob/master/CONTRIBUTING.md).
Expand Down
288 changes: 288 additions & 0 deletions nbs/15_install.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "2c184729",
"metadata": {},
"source": [
"# install\n",
"\n",
"> nbstata kernel install script\n",
"- order: 15"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c7fb586a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The autoreload extension is already loaded. To reload it, use:\n",
" %reload_ext autoreload\n"
]
}
],
"source": [
"#| default_exp install\n",
"%load_ext autoreload\n",
"%autoreload 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "026b00b7",
"metadata": {},
"outputs": [],
"source": [
"#| hide\n",
"from nbdev.showdoc import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4b35edd5",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"import argparse\n",
"import json\n",
"import os\n",
"import sys\n",
"\n",
"from jupyter_client.kernelspec import KernelSpecManager\n",
"from IPython.utils.tempdir import TemporaryDirectory\n",
"import importlib.resources as resources\n",
"from shutil import copyfile\n",
"from pathlib import Path\n",
"from textwrap import dedent\n",
"from fastcore.basics import IN_NOTEBOOK"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dd9d03cf",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"kernel_json = {\n",
" \"argv\": [sys.executable, \"-m\", \"nbstata\", \"-f\", \"{connection_file}\"],\n",
" \"display_name\": \"Stata (nbstata)\",\n",
" \"language\": \"stata\",\n",
"}\n",
"\n",
"def install_my_kernel_spec(user=True, prefix=None):\n",
" with TemporaryDirectory() as td:\n",
" os.chmod(td, 0o755) # Starts off as 700, not user readable\n",
" with open(os.path.join(td, 'kernel.json'), 'w') as f:\n",
" json.dump(kernel_json, f, sort_keys=True)\n",
"\n",
" # Copy logo to tempdir to be installed with kernelspec\n",
" with resources.path('nbstata', 'logo-64x64.png') as logo_path:\n",
" copyfile(logo_path, os.path.join(td, 'logo-64x64.png'))\n",
"\n",
" print('Installing Jupyter kernel spec')\n",
" KernelSpecManager().install_kernel_spec(td, 'nbstata', user=user, prefix=prefix)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "17baa321",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def install_conf(conf_file,gen_file=False):\n",
" \"\"\"\n",
" From stata_kernel, but the conf here is much simplier.\n",
" \"\"\"\n",
"\n",
" # By avoiding an import of .config until we need it, we can\n",
" # complete the installation process in virtual environments\n",
" # without needing this submodule nor its downstream imports.\n",
" from .config import find_dir_edition\n",
" try:\n",
" stata_dir,stata_ed = find_dir_edition()\n",
" except OSError as err:\n",
" stata_dir,stata_ed = \"\", \"\"\n",
" gen_file = True\n",
" msg = \"\"\"\\\n",
" WARNING: Could not find Stata path.\n",
" Please specify it manually in configuration file.\n",
" \"\"\"\n",
" print(dedent(msg))\n",
"\n",
" conf_default = dedent(\n",
" \"\"\"\\\n",
" [nbstata]\n",
" stata_dir = {}\n",
" edition = {}\n",
" graph_format = png\n",
" echo = None\n",
" splash = False\n",
" \"\"\".format(stata_dir,stata_ed))\n",
"\n",
" if gen_file:\n",
" print(\"Creating configuration file at:\")\n",
" print(str(conf_file))\n",
" try:\n",
" with conf_file.open('w') as f:\n",
" f.write(conf_default)\n",
" except:\n",
" print(\"Actually, due to an error, configuration file was not created.\")\n",
"\n",
"def _is_root():\n",
" try:\n",
" return os.geteuid() == 0\n",
" except AttributeError:\n",
" return False # assume not an admin on non-Unix platforms"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "66170ae7",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def main(argv=None):\n",
" ap = argparse.ArgumentParser()\n",
" ap.add_argument('--user', action='store_true',\n",
" help=\"Install to the per-user kernels registry. Default if not root.\")\n",
" ap.add_argument('--sys-prefix', action='store_true',\n",
" help=\"Install to sys.prefix (e.g. a virtualenv or conda env)\")\n",
" ap.add_argument('--prefix',\n",
" help=\"Install to the given prefix. \"\n",
" \"Kernelspec will be installed in {PREFIX}/share/jupyter/kernels/\")\n",
" ap.add_argument(\n",
" '--conf-file', action='store_true',\n",
" help=\"Create a configuration file.\")\n",
" args = ap.parse_args(argv)\n",
"\n",
" if args.sys_prefix:\n",
" args.prefix = sys.prefix\n",
" if not args.prefix and not _is_root():\n",
" args.user = True\n",
"\n",
" install_my_kernel_spec(user=args.user, prefix=args.prefix)\n",
" if args.user:\n",
" conf_file = Path('~/.nbstata.conf').expanduser()\n",
" else:\n",
" conf_dir = os.path.join(args.prefix,'etc')\n",
" if not Path(os.path.join(args.prefix,'etc')).is_dir():\n",
" os.mkdir(conf_dir)\n",
" conf_file = Path(os.path.join(conf_dir,'nbstata.conf'))\n",
" if not conf_file.is_file():\n",
" install_conf(conf_file,args.conf_file)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1cc02dd-3e38-4324-866e-f19a130e38fd",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"if __name__ == \"__main__\" and not IN_NOTEBOOK:\n",
" main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c1dedf6-cda9-41e1-9eb9-34a78f22b305",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#| hide\n",
"IN_NOTEBOOK"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a42239e6-298c-4c1f-acf3-80c3fd143919",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'__main__'"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#| hide\n",
"__name__"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "34bf788c-34bb-49a3-8eee-7768c2091eb4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#| hide\n",
"__name__ == \"__main__\" and not IN_NOTEBOOK"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1c6dd777",
"metadata": {},
"outputs": [],
"source": [
"#| hide\n",
"import nbdev; nbdev.nbdev_export()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "python3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
2 changes: 1 addition & 1 deletion nbs/index.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"`nbstata` is being developed using [nbdev](https://nbdev.fast.ai/blog/posts/2022-07-28-nbdev2/#whats-nbdev). The `/nbs` directory is where edits to the source code should be made. (The python code is then exported to the `/nbdev` library folder.) The one exception is `install.py`.\n",
"`nbstata` is being developed using [nbdev](https://nbdev.fast.ai/blog/posts/2022-07-28-nbdev2/#whats-nbdev). The `/nbs` directory is where edits to the source code should be made. (The python code is then exported to the `/nbdev` library folder.)\n",
"\n",
"For more, see [CONTRIBUTING.md](https://github.com/hugetim/nbstata/blob/master/CONTRIBUTING.md)."
]
Expand Down
5 changes: 4 additions & 1 deletion nbstata/_modidx.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@
'nbstata.config.set_graph_format': ('config.html#set_graph_format', 'nbstata/config.py'),
'nbstata.config.set_pystata_path': ('config.html#set_pystata_path', 'nbstata/config.py')},
'nbstata.inspect': {'nbstata.inspect.get_inspect': ('inspect.html#get_inspect', 'nbstata/inspect.py')},
'nbstata.install': {},
'nbstata.install': { 'nbstata.install._is_root': ('install.html#_is_root', 'nbstata/install.py'),
'nbstata.install.install_conf': ('install.html#install_conf', 'nbstata/install.py'),
'nbstata.install.install_my_kernel_spec': ('install.html#install_my_kernel_spec', 'nbstata/install.py'),
'nbstata.install.main': ('install.html#main', 'nbstata/install.py')},
'nbstata.kernel': { 'nbstata.kernel.PyStataKernel': ('kernel.html#pystatakernel', 'nbstata/kernel.py'),
'nbstata.kernel.PyStataKernel.__init__': ('kernel.html#pystatakernel.__init__', 'nbstata/kernel.py'),
'nbstata.kernel.PyStataKernel.do_complete': ('kernel.html#pystatakernel.do_complete', 'nbstata/kernel.py'),
Expand Down
15 changes: 12 additions & 3 deletions nbstata/install.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/15_install.ipynb.

# %% auto 0
__all__ = ['kernel_json', 'install_my_kernel_spec', 'install_conf', 'main']

# %% ../nbs/15_install.ipynb 3
import argparse
import json
import os
Expand All @@ -9,9 +15,9 @@
from shutil import copyfile
from pathlib import Path
from textwrap import dedent
from fastcore.basics import IN_NOTEBOOK



# %% ../nbs/15_install.ipynb 4
kernel_json = {
"argv": [sys.executable, "-m", "nbstata", "-f", "{connection_file}"],
"display_name": "Stata (nbstata)",
Expand All @@ -31,6 +37,7 @@ def install_my_kernel_spec(user=True, prefix=None):
print('Installing Jupyter kernel spec')
KernelSpecManager().install_kernel_spec(td, 'nbstata', user=user, prefix=prefix)

# %% ../nbs/15_install.ipynb 5
def install_conf(conf_file,gen_file=False):
"""
From stata_kernel, but the conf here is much simplier.
Expand Down Expand Up @@ -76,6 +83,7 @@ def _is_root():
except AttributeError:
return False # assume not an admin on non-Unix platforms

# %% ../nbs/15_install.ipynb 6
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument('--user', action='store_true',
Expand Down Expand Up @@ -106,5 +114,6 @@ def main(argv=None):
if not conf_file.is_file():
install_conf(conf_file,args.conf_file)

if __name__ == '__main__':
# %% ../nbs/15_install.ipynb 7
if __name__ == "__main__" and not IN_NOTEBOOK:
main()

0 comments on commit b0e8967

Please sign in to comment.