How do I access command line arguments?

Viewed 479414

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.

10 Answers

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

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.

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