Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling a python argparse interface from python without Subprocess

Consider the following toy python application, which only have argparse CLI argparse interface.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Printer")
    parser.add_argument("message")
    args = parser.parse_args()
    print(args.message)

if __name__ == "__main__":
    main()

I want to use it from another python script,

  • without having to refactor the toy example (because it might be laborious, or maybe I do not have permission to modify it)
  • without calling a python Subprocess (because it breaks the call stack, sometimes break pycharm debugger, and make debugging harder in general).

Any way to achieve this ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can manipulate the sys.argv list to get your intended behavior.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Printer")
    parser.add_argument("message")
    args = parser.parse_args()
    print(args.message)

if __name__ == "__main__":
    import sys
    sys.argv = [sys.argv[0]]  # remove original arguments except the path
    sys.argv.append('hello')
    main()
hello

make sure to save sys.argv.copy() somewhere to reset it once your function is done.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading