Passing command line arguments to argv in jupyter/ipython notebook

After a lot of looking around I found very cumbersome, custom libraries, but solved it with a few lines of code which I thought was pretty slick. I used nbconvert to end up with an html report as output that contains all graphics and markdown from the notebook, but accepts command line parameters just as always through a minimal python wrapper:

The python file (which takes command line params as normal):

import sys,os
IPYNB_FILENAME = 'test_argv.ipynb'
CONFIG_FILENAME = '.config_ipynb'

def main(argv):
    with open(CONFIG_FILENAME,'w') as f:
        f.write(' '.join(argv))
    os.system('jupyter nbconvert --execute {:s} --to html'.format(IPYNB_FILENAME))
    return None

if __name__ == '__main__':

The notebook contains:

import sys,os,argparse
from IPython.display import HTML
CONFIG_FILE = '.config_ipynb'
if os.path.isfile(CONFIG_FILE):
    with open(CONFIG_FILE) as f:
        sys.argv =
    sys.argv = ['', 'input_file', '--int_param', '12']

parser = argparse.ArgumentParser()
parser.add_argument("input_file",help="Input image, directory, or npy.")
parser.add_argument("--int_param", type=int, default=4, help="an optional integer parameter.")
args = parser.parse_args()
p = args.int_param

and I can run the python notebook with arguments parsed as usual:

python my_input_file --int_param 12

I tend to paste the block with argparse calls into the python wrapper so that command line errors are caught by the python script and -h works properly.

I think this Gist may help you :

This is an attempt at a simple argument parser for mostly key=value pairs that can be used both on the command line and in IPython notebooks. It support query parameters in notebook URLs and a Run command for notebooks.

There are two projects I've found that do what you ask for

  • Papermill, will add a cell to your notebook with arguments that you pass to it on the command line. So this is quite straightforward, you define your defaults in the first cell (the should have parameters tag)
  • nbparameterise it is a similar concept but you don't tag your cell with defaults, it has to be first.

Here is a good resource discussing the issue:

If you use iPython for testing, transforming argparse into class format can be a quick dummy solution like this.

class Args:
  data = './data/penn'
  model = 'LSTM'
  emsize = 200
  nhid = 200


Github page offers web transformation service.
Hope that it would be helpful for your testing. Jan 9/19 many bugs are fixed.

Transform argparse module into class format. Python3 is required.

python3 [] []

then copy & paste class format to replace argparse functions.

#!/usr/bin/env python3
from collections import OrderedDict
import sys
import re
DBG = False

#add_argument(), set_defaults() only available.
ListStartPatt = re.compile(r'\s*\[.*')
ListStartPatt2 = re.compile(r'\).*\[.*') # list out of function scope.
ListPatt = re.compile(r'(\[.*?\])')
GbgPatt = re.compile(r'(.*?)\)[^\)]+') # for float('inf') cmplx.
GbgPatt2 = re.compile(r'(.*?)\).*') # general gbg, ? for non greedy.
LpRegex = re.compile(r'\({1,}\s{0,}')
RpRegex = re.compile(r'\s{0,}\){1,}')
PrRegex = re.compile(r'\((.*)(\))(?!.*\))') # from \( to last \).
CmRegex = re.compile(r'\s{0,},\s{0,}')
StrRegex = re.compile(r'\'(.*?)\'')

# Argument dict : {arg_name : value}

# process 'default=' value.
def default_value(tval, dtype=''):
  # string pattern.
  regres = StrRegex.match(tval) 
  if regres and not'int|float|long|bool|complex', dtype):
    if DBG:
      print('default_value: str patt found')
    tval =
    return tval

  # typed pattern.
  CommaSeparated = CmRegex.split(tval)[0]
  if DBG:
    print('comma sepearated value:', CommaSeparated)

  if ListStartPatt.match(CommaSeparated) and not ListStartPatt2.match(CommaSeparated):
    lres =
    if lres:
      tval =
    if DBG:
      print('list patt exist tval: ', tval)
  else :
    tval = CmRegex.split(tval)[0]
    if DBG:
      print('no list format tval: ', tval)

  # if default value is not like - int('inf') , remove characters after ')' garbage chars.
  ires = RpRegex.split(tval)[0]
  if not ('int|float|long|bool|complex', ires) and'[a-z]+\(',ires)):
    if DBG:
      print('not int("inf") format. Rp removed tval : ', tval)
    tval = re.split(r'\s{0,}\){1,}',tval)[0]
    gbg =
    if gbg:
      tval =  
      if DBG:
        print('garbage exist & removed. tval : ', tval)

  # int('inf') patt.
    if DBG:
      print('type("inf") value garbaging!')
    gbg =
    if gbg:
      if DBG:
        print('garbage found, extract!')
      tval =

  return tval

# Handling add_argument()
def add_argument(arg_line):
  global argDct
  if DBG:
    print('\nin add_argument : **Pre regex: ', arg_line)

  argument name
  # argname = DdRegex.split(arg_line)[1] # Dash or regex for arg name.
  argname ='\'--(.*?)\'', arg_line)
  if not argname:
    argname ='\'-+(.*?)\'', arg_line)

  # dest= keyword handling.
  dest =',\s*dest\s*=(.*)', arg_line)
  if dest:
    dval =
    dval = default_value(dval)
    argname =

  # hyphen(-) to underscore(_)
  if argname:
    argname ='-', '_')
  else :
    # naive str argname.
    sres = StrRegex.match(arg_line)
    if sres:
      argname =
    if not argname:
      return # no argument name 

  check for syntaxes (type=, default=, required=, action=, help=, choices=)
  dtype = ''
  dres =',\s*type\s*=\s*(.*)', arg_line)
  if dres:
    dtype =
    dtype = CmRegex.split(dtype)[0]

  dfult =',\s*default\s*=\s*(.*)', arg_line)
  rquird =',\s*required\s*=\s*(.*)', arg_line)
  action =',\s*action\s*=\s*(.*)', arg_line)
  hlp =',\s*help\s*=\s*(.*)', arg_line)
  chice =',\s*choices\s*=\s*(.*)', arg_line)

  # help message
  hlp_msg = ''
  if hlp:
    thl =
    if DBG:
      print('handling help=')
    hlp_msg = default_value(thl)
    if hlp_msg:
      hlp_msg = 'help='+hlp_msg

  # choice message
  choice_msg = ''
  if chice:
    tch =
    if DBG:
      print('handling choices=')
    choice_msg = default_value(tch)
    if choice_msg:
      choice_msg = 'choices='+choice_msg+' '

  argument value
  # tval: argument value.
  tval = ''
  # default exist.
  if dfult:
    tval =
    tval = default_value(tval, dtype)
    if DBG:
      print('value determined : ', tval)

  # action or required syntaxes exist.
  elif action or rquird:
    if DBG:
      print('in action/required handling')
    msg_str = ''
    if action:
      tval =
      msg_str = 'action'
    elif rquird:
      tval =
      msg_str = 'required'

    tval = default_value(tval)
    tval = ' ** ' + msg_str + ' '+tval+'; '+choice_msg+ hlp_msg

  # no default, action, required.
  else : 
    argDct[argname] = ' ** default not found; '+choice_msg+ hlp_msg

  # value found.
  if tval:
    argDct[argname] = tval

# Handling set_defaults()
def set_defaults(arg_line):
  global argDct
  if DBG:
    print('\nin set_defaults arg_line: ', arg_line)

  # arguments to process.
  # arguments of set_default()
  SetPatt = re.compile(r'(.+=.+\)?)')
  sres = SetPatt.match(arg_line)
  if sres:
    tv =
    if DBG:
      print("setPatt res: ", tv)
    tv = re.sub(r'\s+','', tv)
    if DBG:
      print('\nset_default values: ', tv)

  # one arguemnt regex.
  SetArgPatt = re.compile(r',?([^=]+=)[^=,]+,?')
  # handling multiple set_default() arguments. (may have a bug)
  while True:
    tval =''
    # func closed.
    if re.match(r',*\).*',tv):
    if DBG:
      print('set_default remaining: ', tv)

    nres = SetArgPatt.match(tv)
    if nres:
      tname =
      if len(tv.split(tname, 1)) > 1:
        tval = tv.split(tname,1)[1]
        tval = default_value(tval)
        tname = tname.rsplit('=',1)[0]

      if DBG:
        print('set_default tnam: ', tname)
        print('set_default tval: ', tval)
      if tname:
        argDct[tname] = tval

      # split with processed argument.
      tv = tv.split(tnv)
      if len(tv) > 1:
        tv = tv[1]
      # no more value to process

    # no arg=value pattern found.

# Remove empty line & Concatenate line-separated syntax.
def preprocess(fname):
  try :
    with open(fname, 'r', encoding='UTF8') as f:
      txt =
      t = txt.splitlines(True)
      t = list( filter(None, t) )

      # remove empty line
      t = [x for x in t if not re.match(r'\s{0,}\n',x)]
      # concatenate multiple lined arguments.
      # empl : lines to be deleted from t[].
      empl = []
      for i in range(len(t)-1, 0, -1):
        if not'add_argument|set_defaults', t[i]):
          t[i-1] += t[i]
          t[i-1]=re.sub(r'\s{1,}',' ',t[i-1])

      for d in empl:
      for i, line in enumerate(t):
        t[i] = line.replace('\"', '\'').split('parse_args()')[0]
      return t

  except IOError:
    print('IOError : no such file.', fname)

def transform(fname):
  # t : list() contains add_argument|set_defaults lines.
  arg_line_list = preprocess(fname)

  for i, arg_line in enumerate(arg_line_list):
    t =

    if t:
      t = # t: content of add_argument Parentheses.
    else :
      continue # nothing to parse.

    if'add_argument\s*\(', arg_line):
    else :
      # Nothing to parse.

  print('\nclass Args:')
  for i in argDct:
    print(' ',i, '=', argDct[i])

def main():
  if len(sys.argv) <2:
    print('Usage : python [] [] ...')

  #handling multiple file input.
  for fname in sys.argv:

if(__name__ == "__main__"):

sys.argv yields a list, so I used


in a jupyter notebook, which allowed me to append extra members and pretend like I'm passing in arguments from the command line.

you can use Jupyter build-in magic command %run within the notebook.

From this link, you can use:

%run -p [prof_opts] [args to program]

Or something like %run -i False

Or if you are parsing the arguments %run -i --flag1 False --flag2 True