1

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking if it would be possible do something letting def main():. But this clearly solves my problem completely.
OP mentioned %run in the 'P.S.' of the post. This script would work fine in a notebook being called with %run myscript.py --task mytask --scale 1 as well. Adding this here more for others looking how to generally run a Python script in a notebook given the title of this post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.