Get Command Line Arguments in Python

To get arguments from the command line, you have to use sys.argv list. It contains a list of arguments passed to the script via the command line.

To use command line arguments, you have to import the sys module.

Now, you can access the script name, and number of arguments, and display the list of arguments.

Let’s run this code:

If you run this code without any arguments, the interpreter will return this response:

Name of the script:  main.py
Number of arguments:  1
The list of arguments:  ['main.py']

Here, you can see:

  • Script name, which is main.py.
  • A number of arguments. There is 1 because there is only a script name counter as an argument.
  • List. Only one item on the list, which is only the script name.

Run the file from the command line

Now, open the command line. Move to the directory with the script and run the following line:

Now, the result is slightly different. We added an additional three arguments, and so far, we have 4 in total. All of them are stored inside the list that is displayed in the next line.

Name of the script:  main.py
Number of arguments:  4
The list of arguments:  ['main.py', 'one', 'two', '3']

If you want to display the list of arguments without a file name, you can add this line to your code.

print('The list of arguments without file name: ', sys.argv[1:])

This is the result:

The list of arguments without file name:  ['one', 'two', '3']