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



我试图创建一个命令行脚本,可以处理不同的命令。到目前为止,我所做的代码看起来像这样:

#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, --helpn")
    print("Current version n-v, --versionn")
    print("Silent n-s, --silentn")
    print("Verbosen --versionn")
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 webb。因此,我希望程序跳过ping函数中打印时间的部分。但是由于某种原因,我不能存储我对全局变量所做的更改,因为每次我运行程序并写入-s时,程序仍然认为SILENT为false。

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

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

最新更新