在Python中的命令行选项程序中更改全局变量

时间:2016-10-17 11:54:06

标签: python-3.x command-line global-variables getopt verbose

我试图创建一个可以处理不同命令的命令行脚本。 到目前为止,我所做的代码如下所示:

#Globals
SILENT = False
VERBOSE = True
EXIT_SUCCESS = 0
EXIT_USAGE = 1
EXIT_FAILED = 2

def helpFunc():
    """
    This will print out a help text that describes the program to
    the user and how to use it
    """

    print("############################\n")
    print("Display help \n-h, --help\n")
    print("Current version \n-v, --version\n")
    print("Silent \n-s, --silent\n")
    print("Verbose\n --version\n")

def versionFunc():
    """
    This will show the current version of the program
    """
    print("Current version: \n" + str(sys.version))


def ping(url):
    """
    Will ping a page given the URL and print out the result
    """
    rTime = time.ctime(time.time())

    if VERBOSE == True:
        print(rTime)

    print(url)

def pingHistory(arg):
    """
    Will show the history saved from past pings
    """


def parseOptions():
    """
    Options
    """

    try:
        opt, arg = getopt.getopt(sys.argv[1:], "hvs", ['help', 'version', 'silent', 'verbose', "ping="])
        print("options: " + str(opt))
        print("arguments: " + str(arg))


        for opt, arg in opt:
            if opt in ("-h", "--help"):
                helpFunc()

            elif opt in ("-v", "--version"):
                versionFunc()

            elif opt in ("-s", "--silent"):
                VERBOSE = False
                SILENT = True

            elif opt in ("--verbose"):
                VERBOSE = True
                SILENT = False

            #Send to ping funct
            if len(arg) > 0:
                if arg[0] == "ping":
                    ping(arg[1])

            else:
                helpFunc()


    except getopt.GetoptError as err:
         # will print something like "option -a not recognized",
         # easier to se what went wrong
        print(err)
        sys.exit(EXIT_USAGE)


def main():
    """
    Main function to carry out the work.
    """
    from datetime import datetime

    parseOptions()


    sys.exit(EXIT_SUCCESS)


if __name__ == "__main__":
    import sys, getopt, time, requests

    main()
    sys.exit(0)

现在我想使用名为SILENT和VERBOSE的全局变量来改变程序将要执行的不同输出。所以,如果我喜欢写-s ping dbwebb.se,我希望程序跳过函数ping中打印出时间的部分。 但由于某些原因,我无法存储我对全局变量所做的更改,因为每次运行程序并写入-s时,程序仍然认为SILENT是错误的。

1 个答案:

答案 0 :(得分:0)

您必须在函数定义中将这些全局变量声明为全局变量,例如

def parseOptions():
    """
    Options
    """
    global VERBOSE
    global SILENT