Home > front end >  How to call a python script with parsing arguments on jupyter notebook
How to call a python script with parsing arguments on jupyter notebook

Time:03-16

I have a python script that I defined:

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--task', type=str)
    parser.add_argument('--scale', type=int)
    args = parser.parse_args()
    ... # Do things with my arguments

if __name__ == '__main__':
        main()

And I call this script on command line doing:

python myscript.py --task mytask --scale 1

I would like to call this script in a jupyter notebook. Is there a way to do this parsing the arguments and not modifying my script at all? I.e., doing something that looks like to this:

import myscript    
myscript.main(--task=mytask,scale=1)

P.S.: I tried using magic line such as %run (that probably could work in my case as well) but I had trouble collecting the returns of my script.

CodePudding user response:

You can pass args to parser.parse_args:

# myscript.py
import argparse

def main(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('--task', type=str)
    parser.add_argument('--scale', type=int)
    args = parser.parse_args(args=args)
    print("task is: ", args.task)
    print("scale is: ", args.scale)

if __name__ == "__main__":
    main()

Output from cli:

python3 myscript.py --task aaa --scale 10
# task is:  aaa
# scale is:  10

Output from python

import myscript

myscript.main("--task aaa --scale 10".split())

# task is:  aaa
# scale is:  10
  • Related