argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。
使用示例:
# coding: utf-8
import requests
import argparse
def op_interface(host, su, code):
"""调用控制机器流量接口"""
url = "http://chegva.com/auth/v3/xxx"
payload = "su={}&status_code={}&hostnames={}".format(su,code,host)
print(payload)
headers = { 'Cookie': "xxx" }
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
def main():
parser = argparse.ArgumentParser(description='op interface created by anzhihe')
parser.add_argument('host', type=str, help='输入机器主机名')
parser.add_argument('su', type=str, help='输入机器所在节点su')
parser.add_argument('code', type=int, help='机器接流输入1,禁用输入0')
args = parser.parse_args()
host, su, code = args.host, args.su, args.code
op_interface(host, su, code)
if __name__ == '__main__':
main()
# 使用
$ opi -h
usage: opi [-h] host su code
op interface created by anzhihe
positional arguments:
host 输入机器主机名
su 输入机器所在节点su
code 机器接流输入1,禁用输入0
optional arguments:
-h, --help show this help message and exitargparse模块使用: