Make This Tech Work (Archive)

Add a usage section to your python script

2018-11-12 12:35:41

scriptUsage python script output

Description

I usually like to have a "usage" section for any script that I'm writing whether it's in python or something else. This script gives users an understanding of what the script does and what parameters it takes. It also allows the user to possibly execute a script but have the script tell you what it "would" do instead of actually making real changes. And finally, it lets the user know if they have used invalid parameters, for instance when there are conflicts between certain parameters.

On GitHub

https://github.com/martyh1/pythonusage [code language="python" wraplines="false" collapse="false" highlight="5,11,26,32"] #sys for command line parms and 'quit' import sys def printUsage(): print("usage: fileOrganize [-y][-t][-v]\n\t-y make changes\n\t-t show changes that *would* be made.\n\t-v verbose") # tell user must use parms (so this doesn't just make changes to file system right away) if (len(sys.argv) == 1) or (len(sys.argv) > 4): print("Invalid number of arguments") printUsage() quit() # save args in readable var names makeChanges = showChangesOnly = verbose = False for arg in sys.argv: if arg == '-y': makeChanges = True elif arg == '-t': showChangesOnly = True elif arg == '-v': verbose = True if not makeChanges and not showChangesOnly: print("invalid arguments. Must use either -t or -y") printUsage() quit() #check for conflicting args if makeChanges and showChangesOnly: print("Cannot use -y and -t together.") printUsage() quit() #print selections if verbose if verbose: print('Your selections:') [print(arg) for arg in sys.argv if arg != sys.argv[0]] [/code]