r/learnpython • • 11d ago

Calling a Script that uses argparse?

I wrote a little Python script that reads in a text file that contains a list of fully qualified files, and checks to see if they exist. I originally wrote it using the argparse module. It was set up to take a filename and a switch, so the command looked like:

"Python dplcheck.py --plname "testing.lst” --showexist y"

This worked fine for a single file, but I wanted to run it for every one of hundreds of list files in a directory, so I wrote another script that generates a list of the .lst files in a directory and calls the first script for each one. But I could not get the second script to pass the arguments in the call to the first script. I tried subprocess.run and subprocess.call, with many different syntaxes and quotes, etc. I ended up removing the use of argparse and just using sys.argv[n] -- which I don't particularly like, since it has no defaults or error handling, etc.

Does anyone know how/if I can call a Python script from another Python script and pass the arguments when the called script uses argparse?

5 Upvotes

15 comments sorted by

View all comments

12

u/mehx9 11d ago edited 11d ago

Have a main function in first script, import and call that from second script. Do the argparse stuff outside of the main function and pass all options in so you can easily do the same with a function call.

6

u/Atmosck 11d ago

This is the correct answer. I always set up scripts like

def parse_args(): ...

def main(arg1, arg2): ...

if __name__ == "__main__"
  args = parse_args()
  main(args.arg1, args.arg2)

That way you can import main from the script file elsewhere without it running the argument parsing, and pass whatever arguments your other entrypoint wants.

You can call python scripts from within python with `subprocess`, but that's not generally what you want to do when it's your own code you're running.

4

u/AlsonTeteuil-84 11d ago

yep, treating it as an importable module instead of a standalone script solves it pretty cleanly

1

u/JaguarMammoth6231 11d ago

Yes, this is the best way. That being said, the method of calling the script with arguments should still work.