Please find the below script
from sys import argv
script, contact_name, contact_no = argv
def operation()
some code goes here
Since i run this script from command line, How do i pass contact_name and contact_no to operation function? I am using python 2.7
Command line arguments are passed as an array to the program, with the first being usually the program's location. So we skip argv[0]
and move on to the other arguments.
This example doesn't include error checking.
from sys import argv
def operation(name, number):
...
contact_name = argv[1]
contact_no = argv[2]
operation(contact_name, contact_no)
Calling from command line:
python myscript.py John 5
You can use argparse
to write user-friendly command-line interfaces.
import argparse
parser = argparse.ArgumentParser(description='You can add a description here')
parser.add_argument('-n','--name', help='Your name',required=True)
args = parser.parse_args()
print args.name
To call the script use:
python script.py -n a_name
Allowing any no of arguments
from sys import argv
def operation(name, number, *args):
print(name , number)
operation(*argv[1:])
Calling from command line:
python myscript.py Om 27
first and second argv ("Om" and 27 will pass to the name and number respectively) additional argv(if any) will to *args tupple variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.