Search code examples
pythonpython-3.xcommand-line-argumentsmultilineargs

Split long arguments up in Python command line arguments


How do you split up long arguments for a Python script using argparse?

Currently you would have to call a script with arguments, like this:

python myscript.py --argument1 "Value1" --argument2 "Value2" --argument3 "Value3" --argument4 "Value4" --argument5 "Value5" --argument6 "Value6"

However this can be write hard to read especially when you have a long list of arguments. Something like below would be much easier to read in my opinion. But when I try below I recieve the following error: unrecognized arguments: \

python myscript.py \
  --argument1 "Value1" \
  --argument2 "Value2" \
  --argument3 "Value3" \
  --argument4 "Value4" \
  --argument5 "Value5" \
  --argument6 "Value6"

Does anyone know how to do this? Or is this not possible at all?

In case anyone needs it; here is an example of my code:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--argument1')
parser.add_argument('--argument2')
parser.add_argument('--argument3')
parser.add_argument('--argument4')
parser.add_argument('--argument5')
parser.add_argument('--argument6')

args = parser.parse_args()

Solution

  • Use the following keys for writing multi-line commands according to your system.

    \ works for Unix based systems.

    ^ works for Windows command prompt.

    ` works for Windows Powershell.

    So, in your case, the command can be written as:

    For Windows command prompt

    python myscript.py ^
      --argument1 "Value1 is very very very ^
    long long long string" ^
      --argument2 "Value2" ^
      --argument3 "Value3" ^
      --argument4 "Value4" ^
      --argument5 "Value5" ^
      --argument6 "Value6"
    

    For Windows Powershell

    python myscript.py `
      --argument1 "Value1 is very very very `
    long long long string" `
      --argument2 "Value2" `
      --argument3 "Value3" `
      --argument4 "Value4" `
      --argument5 "Value5" `
      --argument6 "Value6"
    

    For Unix based systems

    python myscript.py \
      --argument1 "Value1" \
      --argument2 "Value2" \
      --argument3 "Value3" \
      --argument4 "Value4" \
      --argument5 "Value5" \
      --argument6 "Value6"
    

    TL;DR: Use the ^ on windows cmd, ` on windows powershell & \ on Unix/Linux systems.