7

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

1
  • Did you try your code? What didn't work? Commented Jan 28, 2016 at 7:14

3 Answers 3

11

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
Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

8

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.

1 Comment

You shouldn't introduce the star syntax without explaining it. Explaining it well to someone new to Python is not easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.