1

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

#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 的全局变量来更改程序将执行的不同输出。因此,如果我喜欢 write -s ping dbwebb.se,我希望程序跳过函数 ping 中打印时间的部分。但是由于某种原因,我不能将我所做的更改存储在全局变量上,因为每次我运行程序并写 -s 时,程序仍然认为 SILENT 是错误的。

4

1 回答 1

0

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

def parseOptions():
    """
    Options
    """
    global VERBOSE
    global SILENT
于 2016-10-17T18:24:52.237 回答