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

标签 python python-2.7

请找到下面的脚本

from sys import argv
script, contact_name, contact_no = argv

def operation()
    some code goes here

由于我从命令行运行此脚本,我如何将 contact_name 和 contact_no 传递给操作函数? 我正在使用 python 2.7

最佳答案

命令行参数作为数组传递给程序,第一个通常是程序的位置。所以我们跳过 argv[0] 并继续讨论其他参数。

此示例不包括错误检查。

from sys import argv

def operation(name, number):
    ...

contact_name = argv[1]
contact_no = argv[2]

operation(contact_name, contact_no)

从命令行调用:

python myscript.py John 5

关于python - 使用 argv 将参数传递给 python 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35054616/

相关文章:

python - matplotlib - 如何在添加新数据时保持坐标轴不变?

python - 比较两个恒星 x-y 坐标列表以查找匹配的物体

python-2.7 - 尝试在python中播放AudioSegment时权限被拒绝

python - Allcoin 签名的 POST 请求失败

python - 为什么我的插值在我的函数中不能正常工作?

python - 在 django-taggit 中,如何获取与特定用户关联的对象的标签?

python - 选择数据框的一个子集,每个变量都有 N 年的数据值(value)

Python Flask 应用程序在 TOTP 错误中前导零。 ( python 2.7)

python - 在递归函数中添加括号

python - MySQL插入字符串,python插入为单个字符