文章内容

2020/9/25 16:45:20,作 者: 黄兵

Python命令行参数

最近在Python中需要根据在命令行中不同参数,运行不同程序,参考了这篇文章:Command Line Arguments in Python,写了一个Python命令行参数程序,具体代码如下:

# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
将所有IPv4地址增加到数据库,同时host所有IP地址,获得主机名
获取所有IP地址地理位置等功能
"""

import getopt
import sys

from comm import ip_range
from config import LoggingConfig


class IPMain:
    def __init__(self):
        self._ip_range = ip_range.IPRange()
        logger_name = 'restore ip'
        self._logger = LoggingConfig.init_logging(logger_name)

    def select_run_program(self, argv):
        # Remove 1st argument from the
        # list of command line arguments
        argumentList = argv
        # Options
        options = "hr:"

        # Long options
        long_options = ["Help", "restore_ip", "current_network="]

        try:
            # Parsing argument
            arguments, values = getopt.getopt(argumentList, options, long_options)

            # checking each argument
            for currentArgument, currentValue in arguments:

                if currentArgument in ("-h", "--Help"):
                    print("请输入需要运行的程序名,例如:restore_ip,直接输入:-r restore_ip,或者 --restore_ip")
                    print("下面是主要的程序名称及作用:")
                    print("restore_ip:主要是枚举IPv4的ABC类所有的IP地址,并保存到数据库")
                    print("current_network:枚举所有保留IP地址,并保存到数据库")

                elif currentArgument in ("-r", "--restore_ip"):
                    if currentValue == 'restore_ip':
                        self._ip_range.restore_ip()
                    if currentValue == 'current_network':
                        self._ip_range.current_network()
                elif currentArgument in ("-r", "--current_network"):
                    if currentValue == 'restore_ip':
                        self._ip_range.restore_ip()
                    if currentValue == 'current_network':
                        self._ip_range.current_network()

        except getopt.error as err:
            # output error, and return with an error code
            self._logger.error(f'程序执行错误,具体错误内容: {err}')


if __name__ == '__main__':
    IPMain().select_run_program(sys.argv[1:])

这里主要说一下options这个参数:

options:脚本要识别的选项字母的字符串。需要自变量的选项应后跟冒号(:)。

上面程序主要是h和r参数,所以这里是options='hr:'

同时这里long_options=['Help','restore_ip','current_network='],最后一个参数最主要是当输入:-r current_network的时候,会使用判断的方式运行相应程序。


参考资料:

1、Command Line Arguments in Python


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Python命令行参数

分享到:

发表评论

评论列表

user-ico

NotMeBug on 回复 有用(0

有讨论群吗?关于博客/云短信

游客83Zh on 2020-09-29 10:58:24

博主回复:现在没有讨论群。