Search code examples
pythoncommand-line-arguments

Why can I omit the space after -m when executing python scripts at the command line?


If I make a file like

# test.py

print('Hello World')

and I run

python -m test

then the python script runs. But if I run

python -mtest

the program ALSO runs.

I would expect omitting that space causes some kind of error. Is this expected behavior? Is this typical behavior when running commands at the command line?


Solution

  • This is a common convention for Unix command line arguments. It follows from the CLI argument conventions of POSIX utilities:

    If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument (as with [ -c option_argument] in the example), a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.

    This syntax is particularly common for flags like -W, where you'll almost always see -W error shortened to -Werror.

    To emphasize the this is the expected convention, note that Python's argparse supports the same syntax:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-m")
    
    >>> parser.parse_args(["-mtest"])
    Namespace(m='test')
    

    See also these related questions from Unix & Linux SE: