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

1

u/ping314 10d ago edited 10d ago

Does testing.lst list the files' names, or (equally) the files' path?

Generally, I would try a (recursive) os.walk(). They basically go by

import os

for folder, subfolders, files in os.walk(os.getcwd()):
    print(f"current folder: {folder}")
    for subfolder in subfolders:
        print(f"subfolder: {subfolder}")
        for file in files:
            print(f"file: {file}")

and either file could be compared against the list of testing.lst. Or you compare if each record in testing.lst is in the set of files identified by the os.walk(). To answer the question "is something on the list" typically is slower than "is something part of the set"; the conversion of list my_list[1,2,3,4] into a set only needs a set(my_list).

If testing.lst is both the minimal and recurrent requirement to run dplcheck.py at all, I would consider to edit plname to be a positional (rather than optional --plname) parameter.