Search code examples
pythoncommand-line-interfaceargparse

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 ?


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.