python script envoke -h or --help if no options are chosen

1.9k views Asked by At

Trying to make my script more generic so I added some flags. My problem is the help only works if you type -h , obviously. I want to envoke -h when no flags are selected.

For example:

python 0_log_cleaner.py

Traceback (most recent call last):
      File "0_log_cleaner.py", line 51, in <module>
    getFiles(options.path,options.org_phrase,options.new_phrase,options.org_AN,options.new_AN,options.dst_path)
  File "0_log_cleaner.py", line 37, in getFiles
    for filename in os.listdir(path):
TypeError: coercing to Unicode: need string or buffer, NoneType found

but if I add -h I get:

python 0_log_cleaner.py -h

Usage: Example:

python  0_log_cleaner.py --sp original_logs/ --dp clean_logs/ --od CNAME --nd New_CNAME --oan 10208 --nan NewAN

Options:
  -h, --help       show this help message and exit
  --sp=PATH        Path to the source logs ie original_logs/
  --dp=DST_PATH    Path to where sanitized logs will be written to ie
                   clean_logs
  --od=ORG_PHRASE  original domain name ie www.clientName.com, use the command
                   -od clientName
  --nd=NEW_PHRASE  domain name to replace -od. ie -od clientName -nd domain
                   makes all log that use to be www.clientName.com into
                   www.domain.com
  --oan=ORG_AN     original AN number
  --nan=NEW_AN     AN number to replace original. ie -oan 12345 -nan AAAA1
                   replaces all instances of the AN number 12345 with AAAA1

EDIT 3 ANSWER sample of my code to produce ^

import argparse
import sys

usage = "Description of function"
parser = argparse.ArgumentParser(description=usage)

parser.add_argument("--sp", dest="path", help='Path to the source logs ie logs/')
...
...(additional add arugments)

args = parser.parse_args()


def getFiles(path,org_phrase,new_phrase,org_AN,new_AN,dst_path):
    if not len(sys.argv) > 1:
        parser.print_help()
    else:
        run your logic
3

There are 3 answers

6
John Moutafis On BEST ANSWER

Without knowing the method you are parsing with, I will assume the following (comment me if I am wrong or edit your question with some code on how you handle your parsing):

  1. You are parsing everything and putting it in a variable. let parsed be that variable.
  2. You are checking parsed for the existence of any of your option flags.

You probably not checking for the non-existence of arguments:

parsed = '' <- empty string
# or if you are using a list:
# parsed = []

if parsed: <- if parsed is not empty ("" or []) returns true
    Do your stuff here, because you have options now
else: <- Differently options were not provided
    Invoke the same method that you invoke when the option is -h

Also as @dhke suggests, consider using argparse if you are not using it already!

EDIT #1: Translated for your specific case:

args = parser.parse_args() <-- ending line of your provided code

if not args:
    parser.print_help()
else:
    Do your stuff
0
chowpay On

borrowed from here : Argparse: Check if any arguments have been passed

Here's how the final code looks like:

import argparse
import sys

usage = "Description of function"
parser = argparse.ArgumentParser(description=usage)

parser.add_argument("--sp", dest="path", help='Path to the source logs ie logs/')
...
...(additional add arugments)

args = parser.parse_args()


def getFiles(path,org_phrase,new_phrase,org_AN,new_AN,dst_path):
    if not len(sys.argv) > 1:
        parser.print_help()
    else:
        run your logic
1
Julianos On

If someone is still interested in a (very simple) solution:

parser = argparse.ArgumentParser()
parser.add_argument("jfile", type=str, help="Give the JSON file name.")
parser.add_argument("--output", type=str, help="Type in the final excel files name.")
try:
    args = parser.parse_args()
    return args
except:
    parser.print_help()

My professor wanted the script to force the -h / --help page even when there are too few arguments. Instead of going like "python SCRIPT.py -h". So what I did here was like: "Try to parse the arguments. And if it works, give them back to the main methode. Otherwise, if you fail (except), print the help(). Okay? Nice". ;)