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 が false であると考えているためです。

4

1 に答える 1