641

I use python to create my project settings setup, but I need help getting the command line arguments.

I tried this on the terminal:

$python myfile.py var1 var2 var3

In my Python file, I want to use all variables that are input.

1

11 Answers 11

835

Python tutorial explains it:

import sys

print(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
0
249

I highly recommend argparse which comes with Python 2.7 and later.

The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).

Here a small example:

import argparse

parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)

and the output for python prog.py -h

usage: simple_example [-h] counter
    
positional arguments:
  counter     counter will be increased by 1 and printed.
    
optional arguments:
  -h, --help  show this help message and exit

and the output for python prog.py 1 As one would expect:

2
8
  • 29
    Quality answer, not really sure why anyone here would use any of the other approaches given here. Especially since it's built in! Don't you guys have better things to do than parsing?
    – Bassinator
    Sep 23, 2018 at 0:00
  • 6
    Just to mention how you should access the specific argument in args namespace: args.counter
    – MikeL
    Jun 25, 2019 at 6:53
  • 5
    @Bassinator In cases when no parsing of arguments is needed. Oct 29, 2019 at 15:12
  • 5
    to use default value, without specific value in the command line, you can use something like: parser.add_argument('var3', nargs='?', type=int, default=3) var3 is a optional param, if you don't specify a value in the command line you can access to var3 in your code, default value for var3=3
    – Albicocco
    Apr 23, 2020 at 7:33
  • Can type be int or float?
    – alper
    Jan 23, 2021 at 12:05
233

To get only the command line arguments

(not including the name of the Python file)

import sys

sys.argv[1:]

The [1:] is a slice starting from the second element (index 1) and going to the end of the arguments list. This is because the first element is the name of the Python file, and we want to remove that.

3
  • Do we really need to import all of sys?
    – einpoklum
    Aug 23 at 14:19
  • @einpoklum I'm open to input because I don't write a lot of Python code these days, but my employer's Python style guide does indeed recommend using imports in this manner.
    – Ryan M
    Aug 23 at 18:14
  • Ok, so, I checked, and - it turns out there is little cost to "importing sys". It's mostly about the set of identifiers to search rather than the loading of libraries.
    – einpoklum
    Aug 23 at 19:20
95

Python code:

import sys

# main
param_1= sys.argv[1] 
param_2= sys.argv[2] 
param_3= sys.argv[3]  
print 'Params=', param_1, param_2, param_3

Invocation:

$python myfile.py var1 var2 var3

Output:

Params= var1 var2 var3 
30

You can use sys.argv to get the arguments as a list.

If you need to access individual elements, you can use

sys.argv[i]  

where i is index, 0 will give you the python filename being executed. Any index after that are the arguments passed.

19

You can access arguments by key using "argparse".

Let's say that we have this command:

python main.py --product_id 1001028

To access the argument product_id, we need to declare it first and then get it:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument('--product_id', dest='product_id', type=str, help='Add product_id')
args = parser.parse_args()

print (args.product_id)

Output:

1001028
8

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.

1
  • 9
    sys.argv[0] is not the current working directory. It is the name of the file that is executing.
    – look
    Mar 20, 2019 at 17:33
6

Some additional things that I can think of.

As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.

Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html

6

First, You will need to import sys

sys - System-specific parameters and functions

This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.

And then, you can print the numbers of arguments or what you want here, the list of arguments.

Follow the script below :

#!/usr/bin/python

import sys

print 'Number of arguments entered :' len(sys.argv)

print 'Your argument list :' str(sys.argv)

Then, run your python script :

$ python arguments_List.py chocolate milk hot_Chocolate

And you will have the result that you were asking :

Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']

Hope that helped someone.

1

Using the following code, you can check whether the arguments are entered. If it is the case, the arguments are printed; otherwise, a message stating that the arguments are not entered is printed.

import sys

if len(sys.argv) <= 1:
   print("No arguments were given")
else:
   for arg in sys.argv:
      print(arg)
3
  • 4
    This is wrong `AttributeError: module 'sys' has no attribute 'args'`` Jan 10 at 11:35
  • 1
    @BrenoLeitão it is actually sys.argv
    – smunteanu
    May 27 at 19:02
  • @smunteanu Thanks I've fixed the code.
    – Rolf
    Sep 2 at 7:51
0

should use of sys ( system ) module . the arguments has str type and are in an array

NOTICE : argv is not function or class and is variable & can change

NOTICE : argv[0] is file name

NOTICE : because python written in c , C have main(int argc , char *argv[]); but argc in sys module does not exits

NOTICE : sys module is named System and written in C that NOT A SOURCE BASED MODULE

from sys import argv # or
from sys import * # or
import sys 

# code
print("is list") if type(sys.argv) == list else pass #  is list ,or
print("is list") if type(argv) == list else pass # is list
# arguments are str ( string )
print(type(sys.argv[1])) # str
# command : python filename.py 1 2 3
print(len(sys.argv)) # 3
print(sys.argv[1],'\n',sys.argv[2]'\n',sys.argv[3]) # following
'''
1
2
3
'''
# command : python filename.py 123
print(len(sys.argv)) # 1
print(sys.argv[1]) # following
'''
123
'''

Not the answer you're looking for? Browse other questions tagged or ask your own question.