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,
Subprocess
(because it breaks the call stack, sometimes break pycharm debugger, and make debugging harder in general).Any way to achieve this ?
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.