做ftp项目中使用命令行参数及 ----python 命令行 解析模块 optparse

Python: 使用 optparse 处理命令行参数

python optparse命令解析模块:https://www.cnblogs.com/pping/p/3989098.html
python optparse模块的简单用法:https://www.cnblogs.com/darkpig/p/5677153.html
Parser for command line options:https://docs.python.org/3/library/optparse.html

参考来源 https://blog.csdn.net/freeking101/article/details/52470744

使用 optparse 处理 命令行参数

 

Python 有两个内建的模块用于处理命令行参数:

  1. 一个是 getopt 只能简单处理 命令行参数;
  2. 另一个是 optparse,功能强大且易于使用,可以方便的生成标准的、符合 Unix/Posix 规范的命令行说明。

简单示例

下面是一个使用 optparse 的简单示例:

import optparse  # 使用 optparse 处理命令行参数


class FtpClient(object):
    """ftp客户端"""
    MSG_SIZE = 1024  # 消息最长1024

    def __init__(self):
        self.username = None
        parser = optparse.OptionParser()
        parser.add_option("-s","--server", dest="server", help="ftp server ip_addr")
        parser.add_option("-P","--port",type="int", dest="port", help="ftp server port")
        parser.add_option("-u","--username", dest="username", help="username info")
        parser.add_option("-p","--password", dest="password", help="password info")
        self.options , self.args = parser.parse_args()

        print(self.options,self.args,type(self.options),self.options.server)
client = FtpClient()

上面这些命令是相同效果的。除此之外, optparse 还为我们自动生成命令行的帮助信息:

  1. <yourscript> -h

  2. <yourscript> --help

 执行效果截图:做ftp项目中使用命令行参数及 ----python 命令行 解析模块 optparse