def read_command_line_parameters(argv):
try:
optlist, free = getopt.getopt(argv[1:], 'chtb:f:o:', ['book=', 'file=', 'output=', 'csv', 'help', 'titles'])
#Python2# except getopt.GetoptError, err:
#Python3#
except getopt.GetoptError as err:
print_error(str(err))
return dict(optlist)
### END read_command_line_parameters ###
### BEGIN usage ###
# usage()
# print script usage
python类getopt()的实例源码
def read_command_line_parameters(argv):
try:
optlist, free = getopt.getopt(argv[1:], 'chtb:f:o:', ['book=', 'file=', 'output=', 'csv', 'help', 'titles'])
#Python2#
except getopt.GetoptError, err:
#Python3# except getopt.GetoptError as err:
print_error(str(err))
return dict(optlist)
### END read_command_line_parameters ###
### BEGIN usage ###
# usage()
# print script usage
def main():
"""Small main program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error as msg:
sys.stdout = sys.stderr
print(msg)
print("""usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test(); return
if args and args[0] != '-':
with open(args[0], 'rb') as f:
func(f, sys.stdout.buffer)
else:
func(sys.stdin.buffer, sys.stdout.buffer)
def get_system_arg(argv, Usage):
verbose = False
parfile = None
eventname = None
opts, args = getopt.getopt(argv, "vp:h", ["parfile=", 'help', 'verbose'])
for opt, value in opts:
if opt in ("-p", "--parfile"):
parfile = value
elif opt in ("-v", "--verbose"):
verbose = True
elif opt in ("-h", "--help"):
Usage()
sys.exit()
else:
Usage()
sys.exit()
try:
eventname = args[0]
except:
Usage()
sys.exit()
return eventname, verbose, parfile
fetch_single_repo.py 文件源码
项目:oss-github-analysis-project
作者: itu-oss-project-team
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def main(argv):
owner = ""
repo = ""
force = False
try:
opts, args = getopt.getopt(argv, "o:r:f", ["owner=", "repo=", "force"])
except getopt.GetoptError:
print('ERROR in input arguments!')
sys.exit(2)
for opt, arg in opts:
if opt == '-h': # Help case
print('fetch_repo.py -o <owner> -r <repo> -f Ex: fetch_repo.py --owner itu-oss-project-team --repo oss-github-analysis-project --force')
sys.exit()
elif opt in ("-o", "--owner"):
owner = arg
elif opt in ("-r", "--repo"):
repo = arg
elif opt in ("-f", "--force"):
force = True
github_harvester = GitHubHarvester()
#github_harvester.fetch_repo(owner, repo, force_fetch = force)
github_harvester.fetch_repo('itu-oss-project-team', 'oss-github-analysis-project', force_fetch = True)
def parse_args():
hostname = None
remain = sys.argv[1:]
allopts = []
restarted = 0
while remain and restarted < 2:
opts, args = getopt.getopt(remain, SSH_GETOPTS)
remain = remain[:] # getopt bug!
allopts += opts
if not args:
break
if not hostname:
hostname = args.pop(0)
remain = remain[remain.index(hostname) + 1:]
restarted += 1
return hostname, allopts, args
def get_username_password(self):
"""??????? ????????"""
try:
opts, args = getopt.getopt(self.argv[1:], 'hu:p:', ['username=', 'password='])
except getopt.GetoptError:
self.logger.info('????????????????')
self.logger.info('cqut.py -u <username> -p <password>')
sys.exit(-1)
for opt, arg in opts:
if opt in ('-u', '--username'):
self.username = arg
elif opt in ('-p', '--password'):
self.password = arg
if self.username is None:
self.username = input('???????: ')
if self.password is None:
self.password = input('???????: ')
def main():
import getopt
usage = """Usage: %s [-n | -t] url
-n: open new window
-t: open new tab""" % sys.argv[0]
try:
opts, args = getopt.getopt(sys.argv[1:], 'ntd')
except getopt.error, msg:
print >>sys.stderr, msg
print >>sys.stderr, usage
sys.exit(1)
new_win = 0
for o, a in opts:
if o == '-n': new_win = 1
elif o == '-t': new_win = 2
if len(args) != 1:
print >>sys.stderr, usage
sys.exit(1)
url = args[0]
open(url, new_win)
print "\a"
def test():
"""Small test program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print """usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test1(); return
if args and args[0] != '-':
with open(args[0], 'rb') as f:
func(f, sys.stdout)
else:
func(sys.stdin, sys.stdout)
def get_args():
keyargs, args = getopt.getopt(sys.argv[1:], 't:l:')
out = {}
if len(args) > 0:
with open(args[0], 'r') as f:
out = json.loads(f.read())
elif len(keyargs) > 0:
for k, arg in keyargs:
if k == '-t':
out['token'] = arg
elif k == '-l':
out['loglevel'] = int(arg)
else:
out = os.environ
print(out)
return out
def main(argv):
option = ''
try:
opts, args = getopt.getopt(argv, "h:o:", ["option="])
except getopt.GetoptError:
print 'test.py -o <option[translate or build]>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -o <option[translate or build]>'
sys.exit()
elif opt in ("-o", "--option"):
option = arg
if option == 'translate':
fname = str(raw_input("File name(Or absolute path to file if it is not in this directory):\n"))
execute(fname)
elif option == 'build':
name_fname = str(raw_input("File name for csv containing string names(Or absolute path to file):\n"))
values_fname = str(raw_input("File name for csv containing translation(Or absolute path to file):\n"))
build_xml(name_fname, values_fname)
else:
print "Invalid option: " + option
print "Option must be either translate or build"
def parseOptions(args):
config = {}
# Command line flags - default values
config['args'] = []
# Read in and process the command line flags
try:
opts, args = getopt.getopt(args, "h", ["help",])
except getopt.GetoptError, err:
# Print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage(exitCode=2)
# Work through opts
for opt, value in opts:
if opt in ('-h', '--help'):
usage(exitCode=0)
else:
assert False
# Add in arguments
config['args'] = args
# Return configuration
return config
def parseOptions(args):
config = {}
# Command line flags - default values
config['args'] = []
# Read in and process the command line flags
try:
opts, args = getopt.getopt(args, "h", ["help",])
except getopt.GetoptError, err:
# Print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage(exitCode=2)
# Work through opts
for opt, value in opts:
if opt in ('-h', '--help'):
usage(exitCode=0)
else:
assert False
# Add in arguments
config['args'] = args
# Return configuration
return config
def parseOptions(args):
config = {}
# Command line flags - default values
config['args'] = []
# Read in and process the command line flags
try:
opts, args = getopt.getopt(args, "h", ["help",])
except getopt.GetoptError, err:
# Print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage(exitCode=2)
# Work through opts
for opt, value in opts:
if opt in ('-h', '--help'):
usage(exitCode=0)
else:
assert False
# Add in arguments
config['args'] = args
# Return configuration
return config
def parseOptions(args):
config = {}
# Command line flags - default values
config['args'] = []
# Read in and process the command line flags
try:
opts, args = getopt.getopt(args, "h", ["help",])
except getopt.GetoptError, err:
# Print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage(exitCode=2)
# Work through opts
for opt, value in opts:
if opt in ('-h', '--help'):
usage(exitCode=0)
else:
assert False
# Add in arguments
config['args'] = args
# Return configuration
return config
def parseOptions(args):
config = {}
# Command line flags - default values
config['args'] = []
# Read in and process the command line flags
try:
opts, args = getopt.getopt(args, "h", ["help",])
except getopt.GetoptError, err:
# Print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage(exitCode=2)
# Work through opts
for opt, value in opts:
if opt in ('-h', '--help'):
usage(exitCode=0)
else:
assert False
# Add in arguments
config['args'] = args
# Return configuration
return config
def main():
import getopt
usage = """Usage: %s [-n | -t] url
-n: open new window
-t: open new tab""" % sys.argv[0]
try:
opts, args = getopt.getopt(sys.argv[1:], 'ntd')
except getopt.error, msg:
print >>sys.stderr, msg
print >>sys.stderr, usage
sys.exit(1)
new_win = 0
for o, a in opts:
if o == '-n': new_win = 1
elif o == '-t': new_win = 2
if len(args) != 1:
print >>sys.stderr, usage
sys.exit(1)
url = args[0]
open(url, new_win)
print "\a"
def test():
"""Small test program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print """usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test1(); return
if args and args[0] != '-':
with open(args[0], 'rb') as f:
func(f, sys.stdout)
else:
func(sys.stdin, sys.stdout)
def main(argv):
inputfile = False
outputfile = False
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print('vec2bin.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
if not inputfile or not outputfile:
print('vec2bin.py -i <inputfile> -o <outputfile>')
sys.exit(2)
print('Converting %s to binary file format' % inputfile)
vec2bin(inputfile, outputfile)
def main(argv):
"""Parse the arguments and start the main process."""
try:
opts, args = getopt.getopt(argv, "h", ["help"])
except getopt.GetoptError:
exit_with_parsing_error()
for opt, arg in opts:
arg = arg # To avoid a warning from Pydev
if opt in ("-h", "--help"):
usage()
sys.exit()
if len(args) == 2:
params = list(get_dicts(*args))
params.extend(get_dict_names(*args))
compare_dicts(*params)
else:
exit_with_parsing_error()