DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
0 votes

I want to be able to call this script with a single id, a list of ids, a url, or a csv file.

Is there a simple way to express it? Here I've only added options to call the script with nothing, a single id or a list of ids. But it already looks too messy for my taste.

def parse_args():
    try:
        if len(sys.argv) == 3:
            # List
            if sys.argv[2].startswith("[") and sys.argv[2].endswith("]"):
                work_ids = sys.argv[2].strip("[").strip("]").split(",")
                download_ao3_fics_and_import_tags(work_ids)
            else: # single work_id
                download_ao3_fic_and_import_tags(sys.argv[2])
        elif len(sys.argv) != 3:
            main()
        else:
            usage()
    except Exception:
        usage()
by
edited by
0

When you begin to have a lot of arguments you should consider using a parsing library like argparse, getopt, or docopt.

0
if len(sys.argv) == 3:

elif len(sys.argv) != 3:

else:
    usage() <<<  this will never be executed because the length is always == or != from 3

1 Answer

+1 vote
 
Best answer

With many inputs like that you should look at using a parsing library (argparse, getopt, or docopt). BUT, with a lot of constraints, if that's your only input, you can do it like this

script.py <mode> <id>

Examples:

script.py id 1
script.py ids 1 2 3 4 5 6 7 8 9
script.py url "https://example.org"
script.py csv filename.csv
by
selected by
Contributions licensed under CC0
...