github.com/yunabe/lgo@v0.0.0-20190709125917-42c42d410fdf/jupyter/gojupyterscaffold-example/install_kernel (about)

     1  #!/usr/bin/python
     2  # -*- coding: utf-8 -*-
     3  #
     4  # 
     5  
     6  import argparse
     7  import json
     8  import os
     9  import sys
    10  
    11  from jupyter_client.kernelspec import KernelSpecManager
    12  from IPython.utils.tempdir import TemporaryDirectory
    13  
    14  kernel_json = {
    15      "argv": [os.path.join("/home/yunabe/local/gocode", "bin/gojupyterscaffold-example"), "--connection_file={connection_file}"],
    16      "display_name": "gojupyterscaffold-example",
    17      "language": "txt",
    18  }
    19  
    20  def install_kernel_spec(user=True, prefix=None):
    21      with TemporaryDirectory() as td:
    22          os.chmod(td, 0o755) # Starts off as 700, not user readable
    23          with open(os.path.join(td, 'kernel.json'), 'w') as f:
    24              json.dump(kernel_json, f, sort_keys=True)
    25          # TODO: Copy any resources
    26  
    27          print('Installing Jupyter kernel spec')
    28          KernelSpecManager().install_kernel_spec(td, 'gojupyterscaffold', user=user, replace=True, prefix=prefix)
    29  
    30  def _is_root():
    31      try:
    32          return os.geteuid() == 0
    33      except AttributeError:
    34          return False # assume not an admin on non-Unix platforms
    35  
    36  def main(argv=None):
    37      ap = argparse.ArgumentParser()
    38  
    39      ap.add_argument('--user', action='store_true',
    40          help="Install to the per-user kernels registry. Default if not root.")
    41      ap.add_argument('--sys-prefix', action='store_true',
    42          help="Install to sys.prefix (e.g. a virtualenv or conda env)")
    43      ap.add_argument('--prefix',
    44          help="Install to the given prefix. "
    45               "Kernelspec will be installed in {PREFIX}/share/jupyter/kernels/")
    46      args = ap.parse_args(argv)
    47  
    48      if args.sys_prefix:
    49          args.prefix = sys.prefix
    50      if not args.prefix and not _is_root():
    51          args.user = True
    52  
    53      install_kernel_spec(user=args.user, prefix=args.prefix)
    54  
    55  if __name__ == '__main__':
    56      main()