API Guide > Maya Python Plug-in Learning Path > Command Plug-in Basics >

# Command Arguments and Flags

In this topic, we present the use of arguments and flags within a command.

## "Flags" and "Command Arguments"

In the context of the Maya API documentation, the terms "flag" and "command argument" carry specific meanings, which we clarify as follows:

- "Flag" - Flags are optional to the normal functioning of a command. Each flag has a long and short name. When used in a MEL command, a flag is prefixed by a hyphen ('-'). In Python, flags appear as named function arguments without the hyphen. In the following example, the 'sx', 'sy', 'sz', and 'h' flags specify the number of subdivisions along each axis, as well as the height of the cube created with cmds.polyCube():

      import maya.cmds as cmds
      cmds.polyCube( sx=10, sy=15, sz=5, h=20 )

  NoteA single flag can also accept a tuple of values, for example the (r,g,b) value of a color. Each item in a tuple is referred to as a flag parameter. We expand on parsing multiple flag parameters below.
- "Command Argument" - Command arguments do not have associated names. When they are used in a MEL command, they appear at the end of the call. By contrast, due to the language design of Python, command arguments appear at the beginning of maya.cmds function calls. The example below illustrates the difference between command arguments and flags:

      import maya.cmds as cmds
      cmds.group( 'circle1', 'sphere1', n='group1' )

  Here, 'circle1' and 'sphere1' are the command arguments of cmds.group(). They are placed before the optional 'n' flag, which is used to specify the name of the resulting group.

It is also possible to use the currently selected Maya objects as arguments to your command. In this case, command arguments and objects are incompatible and must not be combined in the syntax definition of your command. For more information, consult the MSyntax class documentation.

## Sample Command Plug-in: Creating a Flag

In the plug-in code below, we create a command which prints the value associated with the passed flag. The MSyntax and MArgParser class documentation contains additional information about using flags, arguments, and selected objects in your commands.

    # sampleCommandFlag.py

    import sys
    import maya.OpenMayaMPx as OpenMayaMPx
    import maya.OpenMaya as OpenMaya
    # ... additional imports here ...

    kPluginCmdName = 'myCommandWithFlag'

    kShortFlagName = '-mf'
    kLongFlagName = '-myFlag'

    ##########################################################
    # Plug-in
    ##########################################################
    class MyCommandWithFlagClass( OpenMayaMPx.MPxCommand ):

        def __init__(self):
            ''' Constructor. '''
            OpenMayaMPx.MPxCommand.__init__(self)

        def doIt(self, args):
            ''' Command execution. '''

            # We recommend parsing your arguments first.
            self.parseArguments( args )

            # Remove the following 'pass' keyword and replace it with the code you want to run.
            pass

        def parseArguments(self, args):
            '''
            The presence of this function is not enforced,
            but helps separate argument parsing code from other
            command code.
            '''

            # The following MArgParser object allows you to check if specific flags are set.
            argData = OpenMaya.MArgParser( self.syntax(), args )

            if argData.isFlagSet( kShortFlagName ):

                # In this case, we print the passed flag's value as an integer.
                # We use the '0' to index the flag's first and only parameter.
                flagValue = argData.flagArgumentInt( kShortFlagName, 0 )
                print kLongFlagName + ': ' + str( flagValue )

            # ... If there are more flags, process them here ...

    ##########################################################
    # Plug-in initialization.
    ##########################################################
    def cmdCreator():
        ''' Create an instance of our command. '''
        return OpenMayaMPx.asMPxPtr( MyCommandWithFlagClass() )

    def syntaxCreator():
        ''' Defines the argument and flag syntax for this command. '''
        syntax = OpenMaya.MSyntax()

        # In this example, our flag will be expecting a numeric value, denoted by OpenMaya.MSyntax.kDouble.
        syntax.addFlag( kShortFlagName, kLongFlagName, OpenMaya.MSyntax.kDouble )

        # ... Add more flags here ...

        return syntax

    def initializePlugin( mobject ):
        ''' Initialize the plug-in when Maya loads it. '''
        mplugin = OpenMayaMPx.MFnPlugin( mobject )
        try:
            mplugin.registerCommand( kPluginCmdName, cmdCreator, syntaxCreator )
        except:
            sys.stderr.write( 'Failed to register command: ' + kPluginCmdName )

    def uninitializePlugin( mobject ):
        ''' Uninitialize the plug-in when Maya un-loads it. '''
        mplugin = OpenMayaMPx.MFnPlugin( mobject )
        try:
            mplugin.deregisterCommand( kPluginCmdName )
        except:
            sys.stderr.write( 'Failed to unregister command: ' + kPluginCmdName )

    ##########################################################
    # Sample usage.
    ##########################################################
    '''
    # Copy the following lines and run them in Maya's Python Script Editor:

    import maya.cmds as cmds
    cmds.loadPlugin( 'sampleCommandFlag.py' )
    cmds.myCommandWithFlag( myFlag = 4 )

    '''

NoteFor a more practical example of using command arguments, see Example: Creating an IK Joint Chain.

## Maya Plug-in Entry and Exit Points - Registering the Argument Syntax

Compared to commands which do not process arguments or flags, the initializePlugin() entry point needs to be modified to include the command's argument syntax.

    def initializePlugin( mobject ):
        ''' Initialize the plug-in when Maya loads it. '''
        mplugin = OpenMayaMPx.MFnPlugin( mobject )
        try:
            mplugin.registerCommand( kPluginCmdName, cmdCreator, syntaxCreator )
        except:
            sys.stderr.write( 'Failed to register command: ' + kPluginCmdName )

    def uninitializePlugin( mobject ):
        ''' Uninitialize the plug-in when Maya un-loads it. '''
        mplugin = OpenMayaMPx.MFnPlugin( mobject )
        try:
            mplugin.deregisterCommand( kPluginCmdName )
        except:
            sys.stderr.write( 'Failed to unregister command: ' + kPluginCmdName )

In particular, the call to MFnPlugin.registerCommand() must have a third parameter: syntaxCreator. We list the function parameters of MFnPlugin.registerCommand() as follows:

1. Command Name - The name of the command: 'myCommandWithFlag'. This determines how the command is executed either through MEL or using the Python maya.cmds module.
2. Command Creation Function Reference - A reference to the function which creates an instance of our command: cmdCreator.

3. Syntax Creation Function - A reference to the function which returns an MSyntax object: syntaxCreator. This returned MSyntax object defines the long and short names of each flag, as well as the expected type(s) of each flag. The short flag name (kShortFlagName) should be a one or two letter string prefixed by a hyphen: '-mf'. The long flag name (kLongFlagName) is generally more descriptive and should also be prefixed by a hyphen: '-myFlag'.

       kShortFlagName = '-mf'
       kLongFlagName = '-myFlag'

       # ...

       def syntaxCreator():
           ''' Defines the argument and flag syntax for this command. '''
           syntax = OpenMaya.MSyntax()

           # In this example, our flag will be expecting a numeric value, denoted by OpenMaya.MSyntax.kDouble.
           syntax.addFlag( kShortFlagName, kLongFlagName, OpenMaya.MSyntax.kDouble )

           # ... Add more flags here ...

           return syntax

   NoteTo add a command argument, the MSyntax.addArg() function can be used. Consult the MSyntax class documentation for more details.

## Command Behavior - Parsing Flags

The doIt() method of our command should have some code dedicated to parsing its passed arguments and flags. In parseArguments(), we instantiate an MArgParser object using an MSyntax object (obtained from self.syntax()), and the MArgList object (args). We check for the existence of specific flags using MArgParser.isFlagSet(). The call to MArgParser.flagArgumentInt() extracts the value associated with a specific flag as an integer.

        def doIt(self, args):
            ''' Command execution. '''

            # We recommend parsing your arguments first.
            self.parseArguments( args )

            # Remove the following 'pass' keyword and replace it with the code you want to run.
            pass

        def parseArguments(self, args):
            '''
            The presence of this function is not enforced,
            but helps separate argument parsing code from other
            command code.
            '''

            # The following MArgParser object allows you to check if specific flags are set.
            argData = OpenMaya.MArgParser( self.syntax(), args )

            if argData.isFlagSet( kShortFlagName ):

                # In this case, we print the passed flag's value as an integer.
                # We use the '0' to index the flag's first and only parameter.
                flagValue = argData.flagArgumentInt( kShortFlagName, 0 )
                print kLongFlagName + ': ' + str( flagValue )

            # ... If there are more flags, process them here ...

NoteTo parse a command argument, the MArgParser.commandArgument*() functions can be used. Consult the MArgParser class documentation for more details.

## Parsing Flags with Multiple Parameters

Suppose we wanted to parse a flag which contained multiple parameters, for example a three-dimensional vector, similarly to the following use case:

    import maya.cmds as cmds
    cmds.loadPlugin( 'sampleCommandFlagTuple.py' )
    cmds.myCommandWithTupleFlag( myTupleFlag = (10, 20, 30) )

To achieve this, we must modify two sections of our code:

1. Syntax Creation Function - The syntax creation function would require three OpenMaya.MSyntax.kDouble parameters in the call to MSyntax.addFlag(). This new flag syntax definition would tell Maya to expect a tuple of three numbers, instead of just a single number for that flag.

       def syntaxCreator():
           ''' Defines the argument and flag syntax for this command. '''
           syntax = OpenMaya.MSyntax()

           # In this example, our flag will be expecting three OpenMaya.MSyntax.kDouble parameters.
           syntax.addFlag( kShortFlagName, kLongFlagName, OpenMaya.MSyntax.kDouble, OpenMaya.MSyntax.kDouble, OpenMaya.MSyntax.kDouble )

           # ... Add more flags here ...

           return syntax

2. Argument Parsing - In the method body of parseArguments(), we parse the flag's three parameters using indexes 0 to 2 in three separate calls to MArgParser.flagArgumentInt():

           def doIt(self, args):
               ''' Command execution. '''

               # We recommend parsing your arguments first.
               self.parseArguments( args )

               # Remove the following 'pass' keyword and replace it with the code you want to run.
               pass

           def parseArguments(self, args):
               '''
               The presence of this function is not enforced,
               but helps separate argument parsing code from other
               command code.
               '''

               # The following MArgParser object allows you to check if specific flags are set.
               argData = OpenMaya.MArgParser( self.syntax(), args )

               if argData.isFlagSet( kShortFlagName ):

                   # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
                   flagParam0 = argData.flagArgumentInt( kShortFlagName, 0 )
                   flagParam1 = argData.flagArgumentInt( kShortFlagName, 1 )
                   flagParam2 = argData.flagArgumentInt( kShortFlagName, 2 )

                   print kLongFlagName + '[0]: ' + str( flagParam0 )
                   print kLongFlagName + '[1]: ' + str( flagParam1 )
                   print kLongFlagName + '[2]: ' + str( flagParam2 )

## Sample Command Plug-in: One Flag with Multiple Parameters

The following Python code creates a command which prints the three parameters passed with the given flag.

    # sampleCommandFlagTuple.py

    import sys
    import maya.OpenMayaMPx as OpenMayaMPx
    import maya.OpenMaya as OpenMaya
    # ... additional imports here ...

    kPluginCmdName = 'myCommandWithTupleFlag'

    kShortFlagName = '-tf'
    kLongFlagName = '-myTupleFlag'

    ##########################################################
    # Plug-in
    ##########################################################
    class MyCommandWithFlagTupleClass( OpenMayaMPx.MPxCommand ):

        def __init__(self):
            ''' Constructor. '''
            OpenMayaMPx.MPxCommand.__init__(self)

        def doIt(self, args):
            ''' Command execution. '''

            # We recommend parsing your arguments first.
            self.parseArguments( args )

            # Remove the following 'pass' keyword and replace it with the code you want to run.
            pass

        def parseArguments(self, args):
            '''
            The presence of this function is not enforced,
            but helps separate argument parsing code from other
            command code.
            '''

            # The following MArgParser object allows you to check if specific flags are set.
            argData = OpenMaya.MArgParser( self.syntax(), args )

            if argData.isFlagSet( kShortFlagName ):

                # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
                flagParam0 = argData.flagArgumentInt( kShortFlagName, 0 )
                flagParam1 = argData.flagArgumentInt( kShortFlagName, 1 )
                flagParam2 = argData.flagArgumentInt( kShortFlagName, 2 )

                print kLongFlagName + '[0]: ' + str( flagParam0 )
                print kLongFlagName + '[1]: ' + str( flagParam1 )
                print kLongFlagName + '[2]: ' + str( flagParam2 )

            # ... If there are more flags, process them here ...

    ##########################################################
    # Plug-in initialization.
    ##########################################################
    def cmdCreator():
        ''' Create an instance of our command. '''
        return OpenMayaMPx.asMPxPtr( MyCommandWithFlagTupleClass() )

    def syntaxCreator():
        ''' Defines the argument and flag syntax for this command. '''
        syntax = OpenMaya.MSyntax()

        # In this example, our flag will be expecting three OpenMaya.MSyntax.kDouble parameters.
        syntax.addFlag( kShortFlagName, kLongFlagName, OpenMaya.MSyntax.kDouble, OpenMaya.MSyntax.kDouble, OpenMaya.MSyntax.kDouble )

        # ... Add more flags here ...

        return syntax

    def initializePlugin( mobject ):
        ''' Initialize the plug-in when Maya loads it. '''
        mplugin = OpenMayaMPx.MFnPlugin( mobject )
        try:
            mplugin.registerCommand( kPluginCmdName, cmdCreator, syntaxCreator )
        except:
            sys.stderr.write( 'Failed to register command: ' + kPluginCmdName )

    def uninitializePlugin( mobject ):
        ''' Uninitialize the plug-in when Maya un-loads it. '''
        mplugin = OpenMayaMPx.MFnPlugin( mobject )
        try:
            mplugin.deregisterCommand( kPluginCmdName )
        except:
            sys.stderr.write( 'Failed to unregister command: ' + kPluginCmdName )

    ##########################################################
    # Sample usage.
    ##########################################################
    '''
    # Copy the following lines and run them in Maya's Python Script Editor:

    import maya.cmds as cmds
    cmds.loadPlugin( 'sampleCommandFlagTuple.py' )
    cmds.myCommandWithTupleFlag( myTupleFlag = (10, 20, 30) )

    '''