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 参数

FTPclientcore>python test.py -s 127.0.0.1
FTPclientcore>python test.py -server 127.0.0.1

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

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

-h 是打印help里面的信息

FTPclientcore>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 是指定传递进来的值的类型

FTPclientcore>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")
原文地址:https://www.cnblogs.com/zhengyiqun1992/p/10359530.html