Passing command line arguments to argv in jupyter/ipython notebookPass arguments to jupyter notebookHow to pass command line arguments in IPython jupyter notebookhow to use argument parser in jupyter notebookLocking in python does not behave like expectedUser input and command line argumentsBest way to parse command line arguments in C#?How to pass command line arguments to a rake taskHow to read/process command line arguments?How do I pass command line arguments to a Node.js program?Using IPython notebooks under version controlHow to make IPython notebook matplotlib plot inlineExecute Python script within Jupyter notebook using a specific virtualenvHow to run an .ipynb Jupyter Notebook from terminal?How to pass command line arguments in IPython jupyter notebook
Clarification of algebra in moment generating functions
Dirichlet series with a single zero
Is there a word for food that's gone 'bad', but is still edible?
Can full drive backup be used instead of MSSQL database backup?
How can a hefty sand storm happen in a thin atmosphere like Martian?
How to pass query parameters in URL in Salesforce Summer 19 Release?
Does running exec do anything?
Which US defense organization would respond to an invasion like this?
Is there a word that describes the unjustified use of a more complex word?
What to do when scriptures go against conscience?
Find the limit or prove that it does not exist
Make me a minimum magic sum
What Kind of Wooden Beam is this
Why is my arithmetic with a long long int behaving this way?
How to pass hash as password to ssh server
Why does blending blueberries, milk, banana and vanilla extract cause the mixture to have a yogurty consistency?
Is 'contemporary' ambiguous and if so is there a better word?
Is Iron Man stronger than the Hulk?
Some Russian letters overlap the next line of text when used in drop caps
Page count conversion from single to double-space for submissions
How to remap repeating commands i.e. <number><command>?
As a GM, is it bad form to ask for a moment to think when improvising?
Sheared off exhasut pipe: How to fix without a welder?
Sparring against two opponents test
Passing command line arguments to argv in jupyter/ipython notebook
Pass arguments to jupyter notebookHow to pass command line arguments in IPython jupyter notebookhow to use argument parser in jupyter notebookLocking in python does not behave like expectedUser input and command line argumentsBest way to parse command line arguments in C#?How to pass command line arguments to a rake taskHow to read/process command line arguments?How do I pass command line arguments to a Node.js program?Using IPython notebooks under version controlHow to make IPython notebook matplotlib plot inlineExecute Python script within Jupyter notebook using a specific virtualenvHow to run an .ipynb Jupyter Notebook from terminal?How to pass command line arguments in IPython jupyter notebook
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm wondering if it's possible to populate sys.argv
(or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it's done through a python script.
For instance, if I were to run a python script as follows:
python test.py False
Then sys.argv
would contain the argument False
. But if I run a jupyter notebook in a similar manner:
jupyter notebook test.ipynb False
Then the command line argument gets lost. Is there any way to access this argument from within the notebook itself?
python jupyter-notebook command-line-arguments jupyter papermill
add a comment |
I'm wondering if it's possible to populate sys.argv
(or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it's done through a python script.
For instance, if I were to run a python script as follows:
python test.py False
Then sys.argv
would contain the argument False
. But if I run a jupyter notebook in a similar manner:
jupyter notebook test.ipynb False
Then the command line argument gets lost. Is there any way to access this argument from within the notebook itself?
python jupyter-notebook command-line-arguments jupyter papermill
No. Notebooks are often loaded from the notebook dashboard, so it wouldn't make much sense for them to rely on command line arguments. If you're interested in passing input variables into a notebook, have a look at nbparameterise, which has a different take on how to do it.
– Thomas K
Jun 2 '16 at 16:09
add a comment |
I'm wondering if it's possible to populate sys.argv
(or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it's done through a python script.
For instance, if I were to run a python script as follows:
python test.py False
Then sys.argv
would contain the argument False
. But if I run a jupyter notebook in a similar manner:
jupyter notebook test.ipynb False
Then the command line argument gets lost. Is there any way to access this argument from within the notebook itself?
python jupyter-notebook command-line-arguments jupyter papermill
I'm wondering if it's possible to populate sys.argv
(or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it's done through a python script.
For instance, if I were to run a python script as follows:
python test.py False
Then sys.argv
would contain the argument False
. But if I run a jupyter notebook in a similar manner:
jupyter notebook test.ipynb False
Then the command line argument gets lost. Is there any way to access this argument from within the notebook itself?
python jupyter-notebook command-line-arguments jupyter papermill
python jupyter-notebook command-line-arguments jupyter papermill
edited Mar 29 at 17:00
spicyramen
3,64723972
3,64723972
asked May 30 '16 at 22:39
justadampauljustadampaul
157126
157126
No. Notebooks are often loaded from the notebook dashboard, so it wouldn't make much sense for them to rely on command line arguments. If you're interested in passing input variables into a notebook, have a look at nbparameterise, which has a different take on how to do it.
– Thomas K
Jun 2 '16 at 16:09
add a comment |
No. Notebooks are often loaded from the notebook dashboard, so it wouldn't make much sense for them to rely on command line arguments. If you're interested in passing input variables into a notebook, have a look at nbparameterise, which has a different take on how to do it.
– Thomas K
Jun 2 '16 at 16:09
No. Notebooks are often loaded from the notebook dashboard, so it wouldn't make much sense for them to rely on command line arguments. If you're interested in passing input variables into a notebook, have a look at nbparameterise, which has a different take on how to do it.
– Thomas K
Jun 2 '16 at 16:09
No. Notebooks are often loaded from the notebook dashboard, so it wouldn't make much sense for them to rely on command line arguments. If you're interested in passing input variables into a notebook, have a look at nbparameterise, which has a different take on how to do it.
– Thomas K
Jun 2 '16 at 16:09
add a comment |
6 Answers
6
active
oldest
votes
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 test_args.py (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__':
main(sys.argv)
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 = f.read().split()
else:
sys.argv = ['test_args.py', '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
print(args.input_file,p)
and I can run the python notebook with arguments parsed as usual:
python test_args.py 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.
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
add a comment |
I think this Gist may help you : https://gist.github.com/gbishop/acf40b86a9bca2d571fa
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.
1
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
add a comment |
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 haveparameters
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: https://github.com/jupyter/help/issues/218
1
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
add a comment |
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
args=Args()
Github page
offers web transformation service. http://35.192.144.192:8000/arg2cls.html
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 [arg2cls.py] [argparse_script.py]
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,s0,')
RpRegex = re.compile(r's0,)1,')
PrRegex = re.compile(r'((.*)())(?!.*))') # from ( to last ).
CmRegex = re.compile(r's0,,s0,')
StrRegex = re.compile(r''(.*?)'')
# Argument dict : arg_name : value
argDct=OrderedDict()
# process 'default=' value.
def default_value(tval, dtype=''):
# string pattern.
regres = StrRegex.match(tval)
if regres and not re.search('int|float|long|bool|complex', dtype):
if DBG:
print('default_value: str patt found')
tval = regres.group(0)
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 = ListPatt.search(tval)
if lres:
tval = lres.group(1)
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 (re.search('int|float|long|bool|complex', ires) and re.search(r'[a-z]+(',ires)):
if DBG:
print('not int("inf") format. Rp removed tval : ', tval)
tval = re.split(r's0,)1,',tval)[0]
gbg = GbgPatt2.search(tval)
if gbg:
tval = gbg.group(1)
if DBG:
print('garbage exist & removed. tval : ', tval)
# int('inf') patt.
else:
if DBG:
print('type("inf") value garbaging!')
gbg = GbgPatt.search(tval)
if gbg:
if DBG:
print('garbage found, extract!')
tval = gbg.group(1)
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 = re.search(''--(.*?)'', arg_line)
if not argname:
argname = re.search(''-+(.*?)'', arg_line)
# dest= keyword handling.
dest = re.search(r',s*dests*=(.*)', arg_line)
if dest:
dval = dest.group(1)
dval = default_value(dval)
argname = StrRegex.search(dval)
# hyphen(-) to underscore(_)
if argname:
argname = argname.group(1).replace('-', '_')
else :
# naive str argname.
sres = StrRegex.match(arg_line)
if sres:
argname = sres.group(1)
if not argname:
return # no argument name
'''
check for syntaxes (type=, default=, required=, action=, help=, choices=)
'''
dtype = ''
dres = re.search(r',s*types*=s*(.*)', arg_line)
if dres:
dtype = dres.group(1)
dtype = CmRegex.split(dtype)[0]
dfult = re.search(r',s*defaults*=s*(.*)', arg_line)
rquird = re.search(r',s*requireds*=s*(.*)', arg_line)
action = re.search(r',s*actions*=s*(.*)', arg_line)
hlp = re.search(r',s*helps*=s*(.*)', arg_line)
chice = re.search(r',s*choicess*=s*(.*)', arg_line)
# help message
hlp_msg = ''
if hlp:
thl = hlp.group(1)
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 = chice.group(1)
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 = dfult.group(1)
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 = action.group(1)
msg_str = 'action'
elif rquird:
tval = rquird.group(1)
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.
tv=''
# arguments of set_default()
SetPatt = re.compile(r'(.+=.+)?)')
sres = SetPatt.match(arg_line)
if sres:
tv = sres.group(1)
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:
tname=''
tval =''
tnv=''
# func closed.
if re.match(r',*).*',tv):
tv=''
break
if DBG:
print('set_default remaining: ', tv)
nres = SetArgPatt.match(tv)
if nres:
tname = nres.group(1)
if len(tv.split(tname, 1)) > 1:
tval = tv.split(tname,1)[1]
tval = default_value(tval)
tnv=tname+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
else:
break
# no arg=value pattern found.
else:
break
# Remove empty line & Concatenate line-separated syntax.
def preprocess(fname):
try :
with open(fname, 'r', encoding='UTF8') as f:
txt = f.read()
t = txt.splitlines(True)
t = list( filter(None, t) )
# remove empty line
t = [x for x in t if not re.match(r's0,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 re.search('add_argument|set_defaults', t[i]):
t[i-1] += t[i]
t[i-1]=re.sub(r'n0,','',t[i-1])
t[i-1]=re.sub(r's1,',' ',t[i-1])
empl.append(t[i])
for d in empl:
t.remove(d)
for i, line in enumerate(t):
t[i] = line.replace('"', ''').split('parse_args()')[0]
return t
except IOError:
print('IOError : no such file.', fname)
sys.exit()
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 = PrRegex.search(arg_line)
if t:
t = t.group(1) # t: content of add_argument Parentheses.
else :
continue # nothing to parse.
if re.search(r'add_arguments*(', arg_line):
add_argument(t)
elif re.search(r'set_defaultss*(',arg_line):
set_defaults(t)
else :
# Nothing to parse.
continue
print('nclass Args:')
for i in argDct:
print(' ',i, '=', argDct[i])
print()
print('args=Args()')
def main():
if len(sys.argv) <2:
print('Usage : python arg2cls.py [target.py] [target2.py(optional)] ...')
sys.exit(0)
sys.argv.pop(0)
#handling multiple file input.
for fname in sys.argv:
transform(fname)
if(__name__ == "__main__"):
main()
add a comment |
sys.argv
yields a list
, so I used
sys.argv.append('hello')
in a jupyter notebook, which allowed me to append extra members and pretend like I'm passing in arguments from the command line.
add a comment |
you can use Jupyter build-in magic command %run
within the notebook.
From this link, you can use:
%run -p [prof_opts] filename.py [args to program]
Or something like %run -i script.py False
Or if you are parsing the arguments %run -i script.py --flag1 False --flag2 True
5
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37534440%2fpassing-command-line-arguments-to-argv-in-jupyter-ipython-notebook%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
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 test_args.py (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__':
main(sys.argv)
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 = f.read().split()
else:
sys.argv = ['test_args.py', '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
print(args.input_file,p)
and I can run the python notebook with arguments parsed as usual:
python test_args.py 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.
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
add a comment |
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 test_args.py (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__':
main(sys.argv)
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 = f.read().split()
else:
sys.argv = ['test_args.py', '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
print(args.input_file,p)
and I can run the python notebook with arguments parsed as usual:
python test_args.py 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.
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
add a comment |
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 test_args.py (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__':
main(sys.argv)
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 = f.read().split()
else:
sys.argv = ['test_args.py', '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
print(args.input_file,p)
and I can run the python notebook with arguments parsed as usual:
python test_args.py 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.
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 test_args.py (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__':
main(sys.argv)
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 = f.read().split()
else:
sys.argv = ['test_args.py', '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
print(args.input_file,p)
and I can run the python notebook with arguments parsed as usual:
python test_args.py 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.
answered Jan 24 '18 at 3:06
Steve MollySteve Molly
8611
8611
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
add a comment |
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
Hey, cool! Thanks for stopping by. I had long since moved on to other projects and I'm sure I found some easy way around my problem back then, or else employed one of the cumbersome libraries you mention. But this is a neat little fix and I'll mark it as the answer for any future enquirers.
– justadampaul
Feb 1 '18 at 6:57
add a comment |
I think this Gist may help you : https://gist.github.com/gbishop/acf40b86a9bca2d571fa
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.
1
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
add a comment |
I think this Gist may help you : https://gist.github.com/gbishop/acf40b86a9bca2d571fa
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.
1
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
add a comment |
I think this Gist may help you : https://gist.github.com/gbishop/acf40b86a9bca2d571fa
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.
I think this Gist may help you : https://gist.github.com/gbishop/acf40b86a9bca2d571fa
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.
answered Jul 6 '16 at 9:04
SpawnriderSpawnrider
1,43311729
1,43311729
1
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
add a comment |
1
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
1
1
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
A link to a solution is welcome, but your answer must be self-contained and useful even with the link: please quote or summarize the relevant information from the page you're linking to, in case that page becomes unavailable.
– Cody Gray♦
Sep 29 '17 at 15:13
add a comment |
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 haveparameters
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: https://github.com/jupyter/help/issues/218
1
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
add a comment |
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 haveparameters
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: https://github.com/jupyter/help/issues/218
1
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
add a comment |
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 haveparameters
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: https://github.com/jupyter/help/issues/218
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 haveparameters
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: https://github.com/jupyter/help/issues/218
answered Nov 14 '18 at 21:37
Piotr CzaplaPiotr Czapla
14.7k2179107
14.7k2179107
1
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
add a comment |
1
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
1
1
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
Papermill looks excellent. Thanks for the updated information.
– justadampaul
Nov 15 '18 at 20:30
add a comment |
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
args=Args()
Github page
offers web transformation service. http://35.192.144.192:8000/arg2cls.html
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 [arg2cls.py] [argparse_script.py]
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,s0,')
RpRegex = re.compile(r's0,)1,')
PrRegex = re.compile(r'((.*)())(?!.*))') # from ( to last ).
CmRegex = re.compile(r's0,,s0,')
StrRegex = re.compile(r''(.*?)'')
# Argument dict : arg_name : value
argDct=OrderedDict()
# process 'default=' value.
def default_value(tval, dtype=''):
# string pattern.
regres = StrRegex.match(tval)
if regres and not re.search('int|float|long|bool|complex', dtype):
if DBG:
print('default_value: str patt found')
tval = regres.group(0)
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 = ListPatt.search(tval)
if lres:
tval = lres.group(1)
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 (re.search('int|float|long|bool|complex', ires) and re.search(r'[a-z]+(',ires)):
if DBG:
print('not int("inf") format. Rp removed tval : ', tval)
tval = re.split(r's0,)1,',tval)[0]
gbg = GbgPatt2.search(tval)
if gbg:
tval = gbg.group(1)
if DBG:
print('garbage exist & removed. tval : ', tval)
# int('inf') patt.
else:
if DBG:
print('type("inf") value garbaging!')
gbg = GbgPatt.search(tval)
if gbg:
if DBG:
print('garbage found, extract!')
tval = gbg.group(1)
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 = re.search(''--(.*?)'', arg_line)
if not argname:
argname = re.search(''-+(.*?)'', arg_line)
# dest= keyword handling.
dest = re.search(r',s*dests*=(.*)', arg_line)
if dest:
dval = dest.group(1)
dval = default_value(dval)
argname = StrRegex.search(dval)
# hyphen(-) to underscore(_)
if argname:
argname = argname.group(1).replace('-', '_')
else :
# naive str argname.
sres = StrRegex.match(arg_line)
if sres:
argname = sres.group(1)
if not argname:
return # no argument name
'''
check for syntaxes (type=, default=, required=, action=, help=, choices=)
'''
dtype = ''
dres = re.search(r',s*types*=s*(.*)', arg_line)
if dres:
dtype = dres.group(1)
dtype = CmRegex.split(dtype)[0]
dfult = re.search(r',s*defaults*=s*(.*)', arg_line)
rquird = re.search(r',s*requireds*=s*(.*)', arg_line)
action = re.search(r',s*actions*=s*(.*)', arg_line)
hlp = re.search(r',s*helps*=s*(.*)', arg_line)
chice = re.search(r',s*choicess*=s*(.*)', arg_line)
# help message
hlp_msg = ''
if hlp:
thl = hlp.group(1)
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 = chice.group(1)
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 = dfult.group(1)
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 = action.group(1)
msg_str = 'action'
elif rquird:
tval = rquird.group(1)
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.
tv=''
# arguments of set_default()
SetPatt = re.compile(r'(.+=.+)?)')
sres = SetPatt.match(arg_line)
if sres:
tv = sres.group(1)
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:
tname=''
tval =''
tnv=''
# func closed.
if re.match(r',*).*',tv):
tv=''
break
if DBG:
print('set_default remaining: ', tv)
nres = SetArgPatt.match(tv)
if nres:
tname = nres.group(1)
if len(tv.split(tname, 1)) > 1:
tval = tv.split(tname,1)[1]
tval = default_value(tval)
tnv=tname+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
else:
break
# no arg=value pattern found.
else:
break
# Remove empty line & Concatenate line-separated syntax.
def preprocess(fname):
try :
with open(fname, 'r', encoding='UTF8') as f:
txt = f.read()
t = txt.splitlines(True)
t = list( filter(None, t) )
# remove empty line
t = [x for x in t if not re.match(r's0,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 re.search('add_argument|set_defaults', t[i]):
t[i-1] += t[i]
t[i-1]=re.sub(r'n0,','',t[i-1])
t[i-1]=re.sub(r's1,',' ',t[i-1])
empl.append(t[i])
for d in empl:
t.remove(d)
for i, line in enumerate(t):
t[i] = line.replace('"', ''').split('parse_args()')[0]
return t
except IOError:
print('IOError : no such file.', fname)
sys.exit()
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 = PrRegex.search(arg_line)
if t:
t = t.group(1) # t: content of add_argument Parentheses.
else :
continue # nothing to parse.
if re.search(r'add_arguments*(', arg_line):
add_argument(t)
elif re.search(r'set_defaultss*(',arg_line):
set_defaults(t)
else :
# Nothing to parse.
continue
print('nclass Args:')
for i in argDct:
print(' ',i, '=', argDct[i])
print()
print('args=Args()')
def main():
if len(sys.argv) <2:
print('Usage : python arg2cls.py [target.py] [target2.py(optional)] ...')
sys.exit(0)
sys.argv.pop(0)
#handling multiple file input.
for fname in sys.argv:
transform(fname)
if(__name__ == "__main__"):
main()
add a comment |
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
args=Args()
Github page
offers web transformation service. http://35.192.144.192:8000/arg2cls.html
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 [arg2cls.py] [argparse_script.py]
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,s0,')
RpRegex = re.compile(r's0,)1,')
PrRegex = re.compile(r'((.*)())(?!.*))') # from ( to last ).
CmRegex = re.compile(r's0,,s0,')
StrRegex = re.compile(r''(.*?)'')
# Argument dict : arg_name : value
argDct=OrderedDict()
# process 'default=' value.
def default_value(tval, dtype=''):
# string pattern.
regres = StrRegex.match(tval)
if regres and not re.search('int|float|long|bool|complex', dtype):
if DBG:
print('default_value: str patt found')
tval = regres.group(0)
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 = ListPatt.search(tval)
if lres:
tval = lres.group(1)
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 (re.search('int|float|long|bool|complex', ires) and re.search(r'[a-z]+(',ires)):
if DBG:
print('not int("inf") format. Rp removed tval : ', tval)
tval = re.split(r's0,)1,',tval)[0]
gbg = GbgPatt2.search(tval)
if gbg:
tval = gbg.group(1)
if DBG:
print('garbage exist & removed. tval : ', tval)
# int('inf') patt.
else:
if DBG:
print('type("inf") value garbaging!')
gbg = GbgPatt.search(tval)
if gbg:
if DBG:
print('garbage found, extract!')
tval = gbg.group(1)
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 = re.search(''--(.*?)'', arg_line)
if not argname:
argname = re.search(''-+(.*?)'', arg_line)
# dest= keyword handling.
dest = re.search(r',s*dests*=(.*)', arg_line)
if dest:
dval = dest.group(1)
dval = default_value(dval)
argname = StrRegex.search(dval)
# hyphen(-) to underscore(_)
if argname:
argname = argname.group(1).replace('-', '_')
else :
# naive str argname.
sres = StrRegex.match(arg_line)
if sres:
argname = sres.group(1)
if not argname:
return # no argument name
'''
check for syntaxes (type=, default=, required=, action=, help=, choices=)
'''
dtype = ''
dres = re.search(r',s*types*=s*(.*)', arg_line)
if dres:
dtype = dres.group(1)
dtype = CmRegex.split(dtype)[0]
dfult = re.search(r',s*defaults*=s*(.*)', arg_line)
rquird = re.search(r',s*requireds*=s*(.*)', arg_line)
action = re.search(r',s*actions*=s*(.*)', arg_line)
hlp = re.search(r',s*helps*=s*(.*)', arg_line)
chice = re.search(r',s*choicess*=s*(.*)', arg_line)
# help message
hlp_msg = ''
if hlp:
thl = hlp.group(1)
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 = chice.group(1)
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 = dfult.group(1)
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 = action.group(1)
msg_str = 'action'
elif rquird:
tval = rquird.group(1)
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.
tv=''
# arguments of set_default()
SetPatt = re.compile(r'(.+=.+)?)')
sres = SetPatt.match(arg_line)
if sres:
tv = sres.group(1)
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:
tname=''
tval =''
tnv=''
# func closed.
if re.match(r',*).*',tv):
tv=''
break
if DBG:
print('set_default remaining: ', tv)
nres = SetArgPatt.match(tv)
if nres:
tname = nres.group(1)
if len(tv.split(tname, 1)) > 1:
tval = tv.split(tname,1)[1]
tval = default_value(tval)
tnv=tname+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
else:
break
# no arg=value pattern found.
else:
break
# Remove empty line & Concatenate line-separated syntax.
def preprocess(fname):
try :
with open(fname, 'r', encoding='UTF8') as f:
txt = f.read()
t = txt.splitlines(True)
t = list( filter(None, t) )
# remove empty line
t = [x for x in t if not re.match(r's0,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 re.search('add_argument|set_defaults', t[i]):
t[i-1] += t[i]
t[i-1]=re.sub(r'n0,','',t[i-1])
t[i-1]=re.sub(r's1,',' ',t[i-1])
empl.append(t[i])
for d in empl:
t.remove(d)
for i, line in enumerate(t):
t[i] = line.replace('"', ''').split('parse_args()')[0]
return t
except IOError:
print('IOError : no such file.', fname)
sys.exit()
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 = PrRegex.search(arg_line)
if t:
t = t.group(1) # t: content of add_argument Parentheses.
else :
continue # nothing to parse.
if re.search(r'add_arguments*(', arg_line):
add_argument(t)
elif re.search(r'set_defaultss*(',arg_line):
set_defaults(t)
else :
# Nothing to parse.
continue
print('nclass Args:')
for i in argDct:
print(' ',i, '=', argDct[i])
print()
print('args=Args()')
def main():
if len(sys.argv) <2:
print('Usage : python arg2cls.py [target.py] [target2.py(optional)] ...')
sys.exit(0)
sys.argv.pop(0)
#handling multiple file input.
for fname in sys.argv:
transform(fname)
if(__name__ == "__main__"):
main()
add a comment |
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
args=Args()
Github page
offers web transformation service. http://35.192.144.192:8000/arg2cls.html
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 [arg2cls.py] [argparse_script.py]
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,s0,')
RpRegex = re.compile(r's0,)1,')
PrRegex = re.compile(r'((.*)())(?!.*))') # from ( to last ).
CmRegex = re.compile(r's0,,s0,')
StrRegex = re.compile(r''(.*?)'')
# Argument dict : arg_name : value
argDct=OrderedDict()
# process 'default=' value.
def default_value(tval, dtype=''):
# string pattern.
regres = StrRegex.match(tval)
if regres and not re.search('int|float|long|bool|complex', dtype):
if DBG:
print('default_value: str patt found')
tval = regres.group(0)
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 = ListPatt.search(tval)
if lres:
tval = lres.group(1)
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 (re.search('int|float|long|bool|complex', ires) and re.search(r'[a-z]+(',ires)):
if DBG:
print('not int("inf") format. Rp removed tval : ', tval)
tval = re.split(r's0,)1,',tval)[0]
gbg = GbgPatt2.search(tval)
if gbg:
tval = gbg.group(1)
if DBG:
print('garbage exist & removed. tval : ', tval)
# int('inf') patt.
else:
if DBG:
print('type("inf") value garbaging!')
gbg = GbgPatt.search(tval)
if gbg:
if DBG:
print('garbage found, extract!')
tval = gbg.group(1)
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 = re.search(''--(.*?)'', arg_line)
if not argname:
argname = re.search(''-+(.*?)'', arg_line)
# dest= keyword handling.
dest = re.search(r',s*dests*=(.*)', arg_line)
if dest:
dval = dest.group(1)
dval = default_value(dval)
argname = StrRegex.search(dval)
# hyphen(-) to underscore(_)
if argname:
argname = argname.group(1).replace('-', '_')
else :
# naive str argname.
sres = StrRegex.match(arg_line)
if sres:
argname = sres.group(1)
if not argname:
return # no argument name
'''
check for syntaxes (type=, default=, required=, action=, help=, choices=)
'''
dtype = ''
dres = re.search(r',s*types*=s*(.*)', arg_line)
if dres:
dtype = dres.group(1)
dtype = CmRegex.split(dtype)[0]
dfult = re.search(r',s*defaults*=s*(.*)', arg_line)
rquird = re.search(r',s*requireds*=s*(.*)', arg_line)
action = re.search(r',s*actions*=s*(.*)', arg_line)
hlp = re.search(r',s*helps*=s*(.*)', arg_line)
chice = re.search(r',s*choicess*=s*(.*)', arg_line)
# help message
hlp_msg = ''
if hlp:
thl = hlp.group(1)
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 = chice.group(1)
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 = dfult.group(1)
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 = action.group(1)
msg_str = 'action'
elif rquird:
tval = rquird.group(1)
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.
tv=''
# arguments of set_default()
SetPatt = re.compile(r'(.+=.+)?)')
sres = SetPatt.match(arg_line)
if sres:
tv = sres.group(1)
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:
tname=''
tval =''
tnv=''
# func closed.
if re.match(r',*).*',tv):
tv=''
break
if DBG:
print('set_default remaining: ', tv)
nres = SetArgPatt.match(tv)
if nres:
tname = nres.group(1)
if len(tv.split(tname, 1)) > 1:
tval = tv.split(tname,1)[1]
tval = default_value(tval)
tnv=tname+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
else:
break
# no arg=value pattern found.
else:
break
# Remove empty line & Concatenate line-separated syntax.
def preprocess(fname):
try :
with open(fname, 'r', encoding='UTF8') as f:
txt = f.read()
t = txt.splitlines(True)
t = list( filter(None, t) )
# remove empty line
t = [x for x in t if not re.match(r's0,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 re.search('add_argument|set_defaults', t[i]):
t[i-1] += t[i]
t[i-1]=re.sub(r'n0,','',t[i-1])
t[i-1]=re.sub(r's1,',' ',t[i-1])
empl.append(t[i])
for d in empl:
t.remove(d)
for i, line in enumerate(t):
t[i] = line.replace('"', ''').split('parse_args()')[0]
return t
except IOError:
print('IOError : no such file.', fname)
sys.exit()
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 = PrRegex.search(arg_line)
if t:
t = t.group(1) # t: content of add_argument Parentheses.
else :
continue # nothing to parse.
if re.search(r'add_arguments*(', arg_line):
add_argument(t)
elif re.search(r'set_defaultss*(',arg_line):
set_defaults(t)
else :
# Nothing to parse.
continue
print('nclass Args:')
for i in argDct:
print(' ',i, '=', argDct[i])
print()
print('args=Args()')
def main():
if len(sys.argv) <2:
print('Usage : python arg2cls.py [target.py] [target2.py(optional)] ...')
sys.exit(0)
sys.argv.pop(0)
#handling multiple file input.
for fname in sys.argv:
transform(fname)
if(__name__ == "__main__"):
main()
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
args=Args()
Github page
offers web transformation service. http://35.192.144.192:8000/arg2cls.html
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 [arg2cls.py] [argparse_script.py]
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,s0,')
RpRegex = re.compile(r's0,)1,')
PrRegex = re.compile(r'((.*)())(?!.*))') # from ( to last ).
CmRegex = re.compile(r's0,,s0,')
StrRegex = re.compile(r''(.*?)'')
# Argument dict : arg_name : value
argDct=OrderedDict()
# process 'default=' value.
def default_value(tval, dtype=''):
# string pattern.
regres = StrRegex.match(tval)
if regres and not re.search('int|float|long|bool|complex', dtype):
if DBG:
print('default_value: str patt found')
tval = regres.group(0)
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 = ListPatt.search(tval)
if lres:
tval = lres.group(1)
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 (re.search('int|float|long|bool|complex', ires) and re.search(r'[a-z]+(',ires)):
if DBG:
print('not int("inf") format. Rp removed tval : ', tval)
tval = re.split(r's0,)1,',tval)[0]
gbg = GbgPatt2.search(tval)
if gbg:
tval = gbg.group(1)
if DBG:
print('garbage exist & removed. tval : ', tval)
# int('inf') patt.
else:
if DBG:
print('type("inf") value garbaging!')
gbg = GbgPatt.search(tval)
if gbg:
if DBG:
print('garbage found, extract!')
tval = gbg.group(1)
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 = re.search(''--(.*?)'', arg_line)
if not argname:
argname = re.search(''-+(.*?)'', arg_line)
# dest= keyword handling.
dest = re.search(r',s*dests*=(.*)', arg_line)
if dest:
dval = dest.group(1)
dval = default_value(dval)
argname = StrRegex.search(dval)
# hyphen(-) to underscore(_)
if argname:
argname = argname.group(1).replace('-', '_')
else :
# naive str argname.
sres = StrRegex.match(arg_line)
if sres:
argname = sres.group(1)
if not argname:
return # no argument name
'''
check for syntaxes (type=, default=, required=, action=, help=, choices=)
'''
dtype = ''
dres = re.search(r',s*types*=s*(.*)', arg_line)
if dres:
dtype = dres.group(1)
dtype = CmRegex.split(dtype)[0]
dfult = re.search(r',s*defaults*=s*(.*)', arg_line)
rquird = re.search(r',s*requireds*=s*(.*)', arg_line)
action = re.search(r',s*actions*=s*(.*)', arg_line)
hlp = re.search(r',s*helps*=s*(.*)', arg_line)
chice = re.search(r',s*choicess*=s*(.*)', arg_line)
# help message
hlp_msg = ''
if hlp:
thl = hlp.group(1)
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 = chice.group(1)
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 = dfult.group(1)
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 = action.group(1)
msg_str = 'action'
elif rquird:
tval = rquird.group(1)
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.
tv=''
# arguments of set_default()
SetPatt = re.compile(r'(.+=.+)?)')
sres = SetPatt.match(arg_line)
if sres:
tv = sres.group(1)
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:
tname=''
tval =''
tnv=''
# func closed.
if re.match(r',*).*',tv):
tv=''
break
if DBG:
print('set_default remaining: ', tv)
nres = SetArgPatt.match(tv)
if nres:
tname = nres.group(1)
if len(tv.split(tname, 1)) > 1:
tval = tv.split(tname,1)[1]
tval = default_value(tval)
tnv=tname+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
else:
break
# no arg=value pattern found.
else:
break
# Remove empty line & Concatenate line-separated syntax.
def preprocess(fname):
try :
with open(fname, 'r', encoding='UTF8') as f:
txt = f.read()
t = txt.splitlines(True)
t = list( filter(None, t) )
# remove empty line
t = [x for x in t if not re.match(r's0,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 re.search('add_argument|set_defaults', t[i]):
t[i-1] += t[i]
t[i-1]=re.sub(r'n0,','',t[i-1])
t[i-1]=re.sub(r's1,',' ',t[i-1])
empl.append(t[i])
for d in empl:
t.remove(d)
for i, line in enumerate(t):
t[i] = line.replace('"', ''').split('parse_args()')[0]
return t
except IOError:
print('IOError : no such file.', fname)
sys.exit()
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 = PrRegex.search(arg_line)
if t:
t = t.group(1) # t: content of add_argument Parentheses.
else :
continue # nothing to parse.
if re.search(r'add_arguments*(', arg_line):
add_argument(t)
elif re.search(r'set_defaultss*(',arg_line):
set_defaults(t)
else :
# Nothing to parse.
continue
print('nclass Args:')
for i in argDct:
print(' ',i, '=', argDct[i])
print()
print('args=Args()')
def main():
if len(sys.argv) <2:
print('Usage : python arg2cls.py [target.py] [target2.py(optional)] ...')
sys.exit(0)
sys.argv.pop(0)
#handling multiple file input.
for fname in sys.argv:
transform(fname)
if(__name__ == "__main__"):
main()
edited Apr 2 at 5:15
answered Oct 2 '18 at 15:09
sngjuksngjuk
75110
75110
add a comment |
add a comment |
sys.argv
yields a list
, so I used
sys.argv.append('hello')
in a jupyter notebook, which allowed me to append extra members and pretend like I'm passing in arguments from the command line.
add a comment |
sys.argv
yields a list
, so I used
sys.argv.append('hello')
in a jupyter notebook, which allowed me to append extra members and pretend like I'm passing in arguments from the command line.
add a comment |
sys.argv
yields a list
, so I used
sys.argv.append('hello')
in a jupyter notebook, which allowed me to append extra members and pretend like I'm passing in arguments from the command line.
sys.argv
yields a list
, so I used
sys.argv.append('hello')
in a jupyter notebook, which allowed me to append extra members and pretend like I'm passing in arguments from the command line.
answered Mar 23 at 2:39
cryttingcrytting
6618
6618
add a comment |
add a comment |
you can use Jupyter build-in magic command %run
within the notebook.
From this link, you can use:
%run -p [prof_opts] filename.py [args to program]
Or something like %run -i script.py False
Or if you are parsing the arguments %run -i script.py --flag1 False --flag2 True
5
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
add a comment |
you can use Jupyter build-in magic command %run
within the notebook.
From this link, you can use:
%run -p [prof_opts] filename.py [args to program]
Or something like %run -i script.py False
Or if you are parsing the arguments %run -i script.py --flag1 False --flag2 True
5
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
add a comment |
you can use Jupyter build-in magic command %run
within the notebook.
From this link, you can use:
%run -p [prof_opts] filename.py [args to program]
Or something like %run -i script.py False
Or if you are parsing the arguments %run -i script.py --flag1 False --flag2 True
you can use Jupyter build-in magic command %run
within the notebook.
From this link, you can use:
%run -p [prof_opts] filename.py [args to program]
Or something like %run -i script.py False
Or if you are parsing the arguments %run -i script.py --flag1 False --flag2 True
answered Aug 8 '17 at 6:39
mataneymataney
722
722
5
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
add a comment |
5
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
5
5
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
This is an answer to a different question. This answers the question "How do I run a python script from a Jupyter notebook". The original question is "How do I run a Jupyter notebook as a script with the ability to pass command line options"
– Kaushik Ghose
Sep 21 '17 at 13:45
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37534440%2fpassing-command-line-arguments-to-argv-in-jupyter-ipython-notebook%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
No. Notebooks are often loaded from the notebook dashboard, so it wouldn't make much sense for them to rely on command line arguments. If you're interested in passing input variables into a notebook, have a look at nbparameterise, which has a different take on how to do it.
– Thomas K
Jun 2 '16 at 16:09