• Python中optparse模块使用小结


    自己总结的博客

    optparse模块解析命令行参数的说明及优化

    使用optparse模块根据不同的参数创建不同的csv文件

    涉及到的flask服务

    from flask import Flask
    
    app = Flask(__name__)
    
    
    @app.route("/hello_world")
    def hello_world():
        return "HelloWorld!!!"
    
    
    if __name__ == '__main__':
        app.run("127.0.0.1", 9001)

    add_option方法的参数说明

    import optparse
    
    
    class MyParse(object):
        def __init__(self):
            """
            -s 与 --server 的效果一样
            action表示后面需要需要带参数
            type表示后面的参数解析成什么类型
            dest表示获取到参数后用什么属性取值
            """
            # 初始化
            parser = optparse.OptionParser()
            # 设置参数
            # -s
            parser.add_option("-s", "--server", action="store", type=str, dest="server", help="server name")
            # -p
            parser.add_option("-p", "--port", action="store", type=str, dest="port", help="server port")
            # -u
            parser.add_option("-u", "--url", action="store", type=str, dest="url", help="server url")
            # -c
            parser.add_option("-c", "--console", action="store_true", dest="console", help="print to console or not")
            # -f
            parser.add_option("-f", "--file", action="store_true", dest="file", help="write to file or not")
            # 获取输入的参数
            self.options, self.args = parser.parse_args()
            # TODO 打印一下接收到的参数信息
            print("self.options>>> ", self.options)
            print("self.args>>> ", self.args)
    
        def handle_options(self):
            print("server: ", self.options.server)
            print("port: ", self.options.port)
    
    
    
    if __name__ == '__main__':
        my_parse = MyParse()
        my_parse.handle_options()

    ~~~

    class MyOpt(object):
        def __init__(self):
            # 初始化
            parser = optparse.OptionParser()
            # 设置参数
            # TODO -s 跟 --server 的效果一样
            # TODO dest其实就是后面options用来取值的属性;
            parser.add_option("-s", "--server", type=str, dest="server", help="the server host")
            # TODO 不指定type默认是str类型,也可以指定type
            # parser.add_option("-p", "--port", type=int, dest="port", help="the server port")
            parser.add_option("-u", "--url", type=str, dest="url", help="the server URL")
            # TODO action默认为"store",必须输入;为store_true时后面的参数默认时true;为store_false时后面的参数默认为false
            parser.add_option("-f", "--file", action="store_true", dest="file", help="write to file")
        
            # 解析参数
            self.options, self.args = parser.parse_args()
            # TODO 打印看看
            print("options: ", self.options)
            print("args: ", self.args)

    获取参数以及使用函数的demo

    import optparse
    
    import requests
    
    
    class MyOpt(object):
        def __init__(self):
            # 初始化
            parser = optparse.OptionParser()
            # 设置参数
            # TODO dest其实就是后面options用来取值的属性;
            parser.add_option("-s", "--server", type=str, dest="server", help="the server host")
            parser.add_option("-p", "--port", dest="port", help="the server port")
            # TODO 不指定type默认是str类型,也可以指定type
            # parser.add_option("-p", "--port", type=int, dest="port", help="the server port")
            parser.add_option("-u", "--url", type=str, dest="url", help="the server URL")
            # action默认为"store",必须输入;为store_true时后面的参数默认时true;为store_false时后面的参数默认为false
            parser.add_option("-f", "--file", action="store_true", dest="file", help="write to file")
            parser.add_option("-c", "--console", action="store_true", dest="console", help="print to console")
            # 解析参数
            self.options, self.args = parser.parse_args()
            # TODO 打印看看
            print("options: ", self.options)
            print("args: ", self.args)
    
        def verify(self):
            # TODO 必须输入: -s,-p,-u
            if not self.options.server or not self.options.port or not self.options.url:
                exit("\033[31m抱歉,您必须输入\033[32m完整的参数 \033[31m(输入\033[32m -h \033[31m查看帮助信息)")
    
    
    def get_hello_world(request_url: str):
        ret = requests.get(request_url)
        if ret.status_code == 200:
            print("ret_text: ", ret.text, type(ret.text))
        else:
            print("请求URL失败: ", ret.reason)
    
    
    if __name__ == '__main__':
        opt = MyOpt()
        opt.verify()
        # 至此我们获取到了用户输入的参数
        print("---------- 获取到的参数 -----------")
        print("server: ", opt.options.server)
        print("port: ", opt.options.port)
        print("url: ", opt.options.url)
        request_url = f"http://{opt.options.server}:{opt.options.port}{opt.options.url}"
        print("request_url: ", request_url)
        get_hello_world(request_url)

    实现完整需求的demo

    import optparse
    from datetime import datetime
    
    import requests
    
    
    class MyOpt(object):
        def __init__(self):
            # 初始化
            parser = optparse.OptionParser()
            # 设置参数
            # TODO dest其实就是后面options用来取值的属性;
            parser.add_option("-s", "--server", type=str, dest="server", help="the server host")
            parser.add_option("-p", "--port", dest="port", help="the server port")
            # TODO 不指定type默认是str类型,也可以指定type
            # parser.add_option("-p", "--port", type=int, dest="port", help="the server port")
            parser.add_option("-u", "--url", type=str, dest="url", help="the server URL")
            # action默认为"store",必须输入;为store_true时后面的参数默认时true;为store_false时后面的参数默认为false
            parser.add_option("-f", "--file", action="store_true", dest="file", help="write to file")
            parser.add_option("-c", "--console", action="store_true", dest="console", help="print to console")
            # 解析参数
            self.options, self.args = parser.parse_args()
            # TODO 打印看看
            print("---------- 初始化函数的参数 -----------")
            print("options: ", self.options)
            print("args: ", self.args)
    
        def verify(self):
            # TODO 必须输入: -s,-p,-u
            if not self.options.server or not self.options.port or not self.options.url:
                exit("\033[31m抱歉,您必须输入\033[32m完整的参数(-s -p -u) \033[31m(输入\033[32m -h \033[31m查看帮助信息)")
            # TODO -c或者-f需要输入至少一个
            if not (self.options.file or self.options.console):
                exit("\033[31m抱歉,您必须输入\033[32m -c或者-f其中之一 \033[31m(输入\033[32m -h \033[31m查看帮助信息)")
    
        def handle_hello_world(self):
            request_url = f"http://{self.options.server}:{self.options.port}{self.options.url}"
            ret = requests.get(request_url)
            if ret.status_code != 200:
                print("请求URL失败: ", ret.reason)
                return
            # 如果有-c就打印到终端
            if self.options.console is True:
                print("=====================================")
                print(f"{str(datetime.now())}---{ret.text}")
            # 如果有-f就写入到文件中
            if self.options.file is True:
                with open("./temp.txt", "a+") as f:
                    write_str = f"{str(datetime.now())}---{ret.text}" + "\n"
                    f.write(write_str)
    
    
    if __name__ == '__main__':
        opt = MyOpt()
        opt.verify()
        # 至此我们获取到了用户输入的参数
        print("---------- 获取到的参数 -----------")
        print("server: ", opt.options.server)
        print("port: ", opt.options.port)
        print("url: ", opt.options.url)
        request_url = f"http://{opt.options.server}:{opt.options.port}{opt.options.url}"
        print("request_url: ", request_url)
        opt.handle_hello_world()

    ~~~

  • 相关阅读:
    如何在eclipse+pydev运行scrapy项目
    QT下发布APP 文件(Mac)
    QT调用python脚本
    Python-Mac 安装 PyQt4-转
    <转载>在Sublime Text 2/3 中使用Git插件连接GitHub
    python+Eclipse+pydev环境搭建
    [codeforces1270G]Subset with Zero Sum 数学 建图
    [计算机网络]学习笔记
    [ubuntu] VMware Tools 安装详细过程与使用 ——主机和ubuntu虚拟机之间的文本和文件传递
    [codeforces1221D] Make The Fence Great Again dp
  • 原文地址:https://www.cnblogs.com/paulwhw/p/16130310.html
Copyright © 2020-2023  润新知