Package: commandlines
commandlinesSource Repository:chrissimpkins/commandlinesDocumentation:commandlines.github.ioWhat is Commandlines?Commandlinesis a Python library for command line application
development that supports command line argument parsing, command string
validation testing, & application logic. It has no external dependencies
and provides broad Python interpreter support for Python 2.6+, Python
3.3+, pypy, and pypy3 across OS X, Linux, and Windows platforms.The library supports application development withPOSIX guideline compliant[*]command argument styles, theGNU argument style extensions
to the POSIX guidelines(including long option syntax and variable position of options among arguments), and command suite style application arguments that include one or more sub-commands to the executable.[*]with the exception of the short single option-argument definition syntax that does not include an intervening space character (e.g.-ofile)How Do I Use It?The command line string to your executable script is parsed to multiple
objects that are derived from builtin Python types.The Command ObjectInstantiate acommandlinesCommand object:fromcommandlinesimportCommandc=Command()and use the following instance attributes and methods to develop your application:ArgumentsCommand Line
ArgumentsCommand ExampleAccessed/Tested
WithLength of arg
list$ spam eggs-t--outfilec.argc == 4Command suite
sub-commands$ spam eggsc.subcmd == "eggs"Command suite
sub-sub-commands$ spam eggs overeasyc.subsubcmd == "overeasy"Short switch
syntax$ spam-ec.contains_switches('e')Long switch
syntax$ spam--eggsc.contains_switches('eggs')Multiple
switches$ spam-e--eggsc.contains_switches('e','eggs')Short opt-arg
definition
syntax$ spam-oeggsc.get_definition('o')Long opt-arg
definition
syntax$ spam--outeggsc.get_definition('out')Alt long
opt-arg
definition
syntax$ spam--out=eggsc.get_definition('out')Multiple same
option
definitions$ spam-oeggs-oomeletsc.get_multiple_definitions('o')Multi-option
short syntax
switches$ spam-mpnseggsc.contains_mops('m')Next positional
argument$ spam eggs test/pathc.get_arg_after('eggs')Positional ArgumentsPositional arguments use a 0 based index starting at the first argument
to the executable (i.e.sys.argv[1:]) and are maintained as
attributes in the Command object. Individual attribute support is
provided for the first five positional arguments and the last positional
argument. An ordered list of all positional arguments is available in
theargumentsattribute.Positional
ArgumentCommand ExampleAccessed/Tested
WithPositional
argument at
index 0$ spam eggsc.arg0Positional
argument at
index 1$ spam eggs baconc.arg1Positional
argument at
index 2$ spam eggs bacon toastc.arg2Positional
argument at
index 3$ spam eggs bacon toast cerealc.arg3Positional
argument at
index 4$ spam eggs bacon toast cereal milkc.arg4Last positional
argument$ spam eggs-b--toastfilepathc.arglpAll positional
arguments$ spam eggs-b--toastfilepathc.argumentsDefault Option-Argument DefinitionsDefine option-argument defaults in adefaultsCommand instance
attribute. This attribute is defined as an empty Python dictionary upon
instantiation of the Command object. Use standard key index-based Python
dictionary assignments or theset_defaultsassignment method in the
Command class to define default values. Default values can take any type
that is permissible as a Python dictionary value.Here are examples of each approach that define defaults foroutputandleveloptions:Key Index-Based Default AssignmentsfromcommandlinesimportCommandc=Command()c.defaults['output']="test.txt"c.defaults['level']=10Method-Based Default AssignmentsfromcommandlinesimportCommandc=Command()default_options={'output':'test.txt','level':10}c.set_defaults(default_options)To test for the presence of a default option definition and obtain its
value, use thecontains_defaultsandget_defaultmethods,
respectively:# continued from code examples aboveifc.contains_definitions('output'):dosomething(c.get_definition('output'))elifc.contains_defaults('output'):dosomething(c.get_default('output'))else:dosomethingelse()Help, Usage, and Version Request Testing MethodsHelp, usage, and version command line requests are tested with methods:Test TypeCommand ExampleTested WithHelp request, short$ spam-hc.is_help_request()Help request, long$ spam--helpc.is_help_request()Usage request$ spam--usagec.is_usage_request()Version request, short$ spam-vc.is_version_request()Version request, long$ spam--versionc.is_version_request()Testing Methods for Other Commonly Used SwitchesTest TypeCommand ExampleTested WithVerbose standard output$ spam eggs--verbosec.is_verbose_request()Quiet standard output$ spam eggs--quietc.is_quiet_request()Special Command Line IdiomsThe double dash idiom escapes all subsequent tokens from option/argument
parsing. Methods are available to determine whether a double dash token
is present in a command and obtain an ordered list of all command line
arguments that follow this idiom:Command Line
IdiomsCommand ExampleAccessed/Tested
WithDouble dash
idiom$ spam eggs---badfilec.has_double_dash()Double dash
arguments$ spam eggs---badfile-badfile2c.get_double_dash_args()Application Logic Testing MethodsTest TypeCommand ExampleTested WithPositional
command
sequence$ spam eggs doitc.has_command_sequence('eggs','doit')Single switch$ spam-sc.contains_switches('s')Multiple switch$ spam-s--eggsc.contains_switches('s','eggs')Single
definition$ spam-oeggsc.contains_definitions('o')Multiple
different
definitions$ spam-oeggs--withbaconc.contains_definitions('o','with')Multiple same
definitions$ spam-oeggs-obaconc.contains_multi_definitions('o')Positional
argument$ spam eggs--coffeec.has_args_after('eggs')Acceptable
positional arg$ spam eggs toasterc.next_arg_is_in('eggs',['toaster','coffeepot'])Command String Validation MethodsTest TypeFailure ExampleTested WithMissing
arguments$ spamc.does_not_validate_missing_args()Expected
argument number$ spam eggsc.does_not_validate_n_args(2)Missing opt-arg
definitions$ spam-o--eggsc.does_not_validate_missing_defs()Missing
switches$ spam eggsc.does_not_validate_missing_switches()Missing
multi-option
short syntax
switches$ spam-oeggsc.does_not_validate_missing_mops()Development with CommandlinesTo facilitate development with Commandlines, you can print the string
returned by the Commandobj_string()method to view a list of the
parsed arguments from example commands:fromcommandlinesimportCommandc=Command()print(c.obj_string())sys.exit(0)For example, if you execute your script with the commandspam eggs--toast-b--drink=milkfilepathand include the above
print statement in your source, you will see the following in your
terminal emulator:$spameggs--toast-b--drink=milkfilepathobj.argc=5obj.arguments=['eggs','--toast','-b','--drink=milk','filepath']obj.defaults={}obj.switches={'toast','b'}obj.defs={'drink':'milk'}obj.mdefs={}obj.mops={}obj.arg0='eggs'obj.arg1='--toast'obj.arg2='-b'obj.arg3='--drink=milk'obj.arg4='filepath'obj.arglp='filepath'obj.subcmd='eggs'obj.subsubcmd='--toast'API DocumentationYou can view full documentation of the Command classhere.If you would like to dig into lower level objects in the commandlines
package, you can view thelibrary API
documentation.Exceptions that are used in the commandlines package are documentedhere.How to Include Commandlines in Your ProjectFor Projects That Will Be Distributed to OthersAdd thecommandlinespackage dependency to your projectsetup.pyfile in theinstall_requiresfield like so:setup(...install_requires=["commandlines"],...)Then, enter the following command to test your project locally:$ python setup.py developImport thecommandlinespackage in your project and instantiate a
Command object by adding the following lines to your Python script:fromcommandlinesimportCommandc=Command()And away you go…The Commandlines package will be installed automatically for users who
install your releases viapipor your projectsetup.pyfile
(i.e. with the command$ python setup.py install).For Local Projects That Are Not Intended for RedistributionInstall the Commandlines package with the command:$ pip install commandlinesImport thecommandlinespackage in your project and instantiate a
Command object by adding the following lines to your Python script:fromcommandlinesimportCommandc=Command()LicenseCommandlines is licensed under theMIT license.