How do I access command line arguments?

PythonCommand LineCommand Line-Arguments

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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']

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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 

Solution 5 - Python

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.

Solution 6 - Python

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.

Solution 7 - Python

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

Solution 8 - Python

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.

Solution 9 - Python

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_i, we need to declare it first 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

Solution 10 - Python

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
'''

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParisNakitaKejserView Question on Stackoverflow
Solution 1 - PythonSilentGhostView Answer on Stackoverflow
Solution 2 - PythonRyan MView Answer on Stackoverflow
Solution 3 - PythonMichael DornerView Answer on Stackoverflow
Solution 4 - PythonCharles P.View Answer on Stackoverflow
Solution 5 - PythonALLSYEDView Answer on Stackoverflow
Solution 6 - Pythonlvadim01View Answer on Stackoverflow
Solution 7 - PythonRohanView Answer on Stackoverflow
Solution 8 - Pythonuser14124037View Answer on Stackoverflow
Solution 9 - PythonMohamad HamoudayView Answer on Stackoverflow
Solution 10 - Pythonuser15049586View Answer on Stackoverflow