简体   繁体   English

使用argv将参数传递给python中的函数

[英]passing arguments to functions in python using argv

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? 由于我从命令行运行此脚本,如何将contact_name和contact_no传递给操作函数? I am using python 2.7 我正在使用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. 所以我们跳过argv[0]并转到其他参数。

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. 您可以使用argparse编写用户友好的命令行界面。

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. 第一个和第二个argv(“Om”和27将分别传递给名称和数字)额外的argv(如果有的话)将* args tupple变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM