1
異なるコマンドを処理できるコマンドラインスクリプトを作成しようとしています。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, --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-ping dbwebb.seを書くのが好きであれば、プログラムが時間をプリントアウトする関数pingの部分をスキップするようにしたい。 しかし何らかの理由でグローバル変数に行う変更を保存することはできません。なぜなら、プログラムを実行して-sを書くたびに、プログラムはSILENTが偽であると考えているからです。