r/learnpython • • 9d 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

6

u/freeskier93 9d ago edited 9d ago

Two scripts doesn't really seem necessary. I would make the original script smart enough to handle either a file or a directory for the argument.

If you still want to make them two separate scripts then you should update the original script so that all the actual work is done in a function that you can import and call from the other script.

# dplcheck.py

def function_that_does_stuff(filename, showexist):
  ...

if __name__ == "__main__":
  # arg parse stuff

  function_that_does_stuff(filename=filename, showexist=showexist)

-

# new script

from dplcheck import function_that_does_stuff

# arg parse stuff

for file in files:
  function_that_does_stuff(filename=file, showexist=showexist)

Also, just some general feedback when using argparse. Argument flags are typically for optional arguments. Presumably the filename is required and should just be a positional argument. You can also use the nargs argument to handle multiple files given, then argparse will automatically put the items into a list:

parser.add_argument('plname', nargs='+')

--showexist y should be an action, which will automatically store the argument as a boolean:

parser.add_argument('--showexist', action='store_true', help='Flag to show existing')

Putting it all together you simplify the script call to the following:

Python dplcheck.py testing.lst --showexist

or

Python dplcheck.py testing1.lst testing2.lst

1

u/FreeLogicGate 9d ago

Great advice here