argparse

该模块的功能主要是从程序外部执行行,获取外部传递进来的参数

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--server', dest='server', help="ftp server ip")
parser.add_argument('-p', dest='port', help="ftp server port", type=int)
args = parser.parse_args()
print(args)

‘-s’,'--server' 是外部传递参数进来的书写方式

python xxx.py  -s 参数    或者  python xxx.py --server 参数

FTPclient\core>python test.py -s 127.0.0.1
FTPclient\core>python test.py -server 127.0.0.1

 

dest的作用是把传递进来的值赋值给该值

Namespace(port=None, server='127.0.0.1')

 

-h 是打印help里面的信息

FTPclient\core>python test.py -h
usage: test.py [-h] [-server SERVER] [-p PORT]

optional arguments:
  -h, --help      show this help message and exit
  -server SERVER  ftp server ip
  -p PORT         ftp server port

type 是指定传递进来的值的类型

FTPclient\core>python test.py -p asaS
usage: test.py [-h] [-server SERVER] [-p PORT]
test.py: error: argument -p: invalid int value: 'asaS'

 

当如果是这个的格式时,没有 -  参数,有dest  则是必须传递参数进来 

parser.add_argument(dest='server', help="ftp server ip")

 

posted on 2019-02-10 17:08  一群羊  阅读(191)  评论(0编辑  收藏  举报

导航