We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Want to run Python scripts with command-line arguments?

python-command-line-arguments-1

Learn how to parse command-line arguments using sys, getopt, and argparse modules in Python.

In Python, when you want to read in user input, youll use theinput()function.

In this tutorial, well learn how to run aPython scriptwith options and arguments at the command line.

python-command-line-arguments-2

Well then learn how to use Pythons built-in modules to parse such options and arguments.

And subsequent arguments start at index 1.

This is a minimal working program that accepts and processes command-line arguments.

However, we see some issues:

This is not very clear.

To address this, you’re free to use either the getopt or the argparse modules.

And well learn that in the next sections.

We need to parse all arguments starting at index 1 insys.argv.

So the slice to parse issys.argv[1:].

Here, well need amessagestring andfilename.

Lets usemandfas short options andmessageandfileas long options.

But how do we ensure that a specific option requires an argument?

Any other positional argument that we pass in will be collected inargsvariable.

As we havent passed in any positional argument,argsis an empty list.

For example, youll usepython3 -m unittest main.pyto run unittest as the main module when running main.py.

We mentioned that all other positional arguments that we pass in will be collected in theargsvariable.

Heres an example:

Theargslist contains the positional argument another_argument.

Here,optsis a list of tuples.

But what do we do with the filename and the message after we have processed these arguments?

Lets run main.py with the short options and command-line arguments.

After running main.py, we can see thisfile.txt in our working directory.

It contains the string hello converted to uppercase (HELLO).

To parse command-line arguments, let us import theArgumentParserclass from the argparse module.

So far, weve instantiatedarg_parserand added the command-line arguments.

Here, we capture the argument namespace in the variableargs.

So you’re free to useargs.argument_nameto get the values of the arguments.

So if you do not pass in one or more of these arguments, youll run into errors.

And we get an error stating that thefileargument is required.

Lets modify main.py to make both themessageand thefilearguments optional.

As the command-line arguments are both optional, we can set default values for these arguments.

Meaning you’ve got the option to now run main.pywithoutboth of these arguments.

In the argument namespace, bothfileandmessageareNone.

We see that the defaultfilename andmessagemyfile.txt and Python3 are used.

We see the file2.txt in the working directory:

And it contains the string cODING as expected.