2

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
chowpay
  • 1,515
  • 6
  • 22
  • 44
  • And you parse your options how? In case you are still using [`optparse`](https://docs.python.org/2/library/optparse.html): Switch to the (not-deprecated) [argparse](https://docs.python.org/2.7/library/argparse.html) and [override `.error()`](http://stackoverflow.com/questions/3636967/python-argparse-how-can-i-display-help-automatically-on-error). – dhke Apr 07 '17 at 22:11
  • @dhke just siwtched over to argparse – chowpay Apr 07 '17 at 22:57

3 Answers3

2

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
Community
  • 1
  • 1
chowpay
  • 1,515
  • 6
  • 22
  • 44
1

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". ;)

Julianos
  • 11
  • 1
  • Oh and there should be an "exit()" after "parser.print_help()". Otherwise the script will generate - besides the butiful help page - different error messages (cause he is trying to go on working ofc). – Julianos Dec 13 '17 at 21:06
0

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
John Moutafis
  • 22,254
  • 11
  • 68
  • 112
  • yeah looks like I am using optionparser, as I asked dhke. What would I have to change to switch over? Thanks – chowpay Apr 07 '17 at 22:33
  • Not much, read those examples https://docs.python.org/2/library/argparse.html#example – John Moutafis Apr 07 '17 at 22:34
  • thanks! ok switched it over (see my edit) i'll add in your code now – chowpay Apr 07 '17 at 22:50
  • so a little confused. if you look at my code now. how do I do the `if parser..` (which is true only if there is an argument) if by default I have the line `parser = argparse.ArgumentParser(description=usage)` unless im using argparse incorrectly. Thanks – chowpay Apr 07 '17 at 23:05
  • I tried the code and had an issue, I didnt know how to paste it in this part of the text so I did an edit on your response. Basically im triggering the program running condition even if I don't have an arg. Thanks! – chowpay Apr 08 '17 at 01:25
  • worked it out, see my answer below. Thanks for pointing me in the right direction – chowpay Apr 08 '17 at 02:53