本文整理汇总了Python中getopt.error方法的典型用法代码示例。如果您正苦于以下问题:Python getopt.error方法的具体用法?Python getopt.error怎么用?Python getopt.error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类getopt
的用法示例。
在下文中一共展示了getopt.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
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)
示例2: replace_stdout
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def replace_stdout():
"""Set stdout encoder error handler to backslashreplace (as stderr error
handler) to avoid UnicodeEncodeError when printing a traceback"""
import atexit
stdout = sys.stdout
sys.stdout = open(stdout.fileno(), 'w',
encoding=stdout.encoding,
errors="backslashreplace",
closefd=False,
newline='\n')
def restore_stdout():
sys.stdout.close()
sys.stdout = stdout
atexit.register(restore_stdout)
示例3: RunCommand
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def RunCommand(cmd):
"""RunCommand
Runs command specified by user
@param command to execute
"""
logging.debug("Running cmd %s", cmd)
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
shell=True)
o, e = p.communicate()
s = p.returncode
if s != 0:
return (s, e)
return (s, o)
# returns error, or None for OK
# opts is dictionary of {option: value}.
# for now we care about size and (maybe) policy
示例4: validate_vsan_policy_name
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def validate_vsan_policy_name(policy_name, vmdk_path):
"""
Ensure that the policy file exists
"""
if not vsan_info.is_on_vsan(vmdk_path):
raise ValidationError('Cannot use a VSAN policy on a non-VSAN datastore')
if not vsan_policy.policy_exists(policy_name):
err_msg = 'Policy {0} does not exist.'.format(policy_name)
# If valid policies exist, append their names along with error message
# for available policy names that can be used
avail_policies = vsan_policy.get_policies()
if avail_policies:
avail_msg = ' Available policies are: {0}'.format(list(avail_policies.keys()))
err_msg = err_msg + avail_msg
raise ValidationError(err_msg)
示例5: set_policy_to_vmdk
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def set_policy_to_vmdk(vmdk_path, opts, vol_name=None):
"""
Set VSAN policy to the vmdk object
If failed, delete the vmdk file and return the error info to be displayed
on client
"""
out = vsan_policy.set_policy_by_name(vmdk_path, opts[kv.VSAN_POLICY_NAME])
if out:
# If policy is incompatible/wrong, return the error and delete the vmdk_path
msg = ("Failed to create volume %s: %s" % (vol_name, out))
logging.warning(msg)
error_info = err(msg)
clean_err = cleanVMDK(vmdk_path=vmdk_path,
vol_name=vol_name)
if clean_err:
logging.warning("Failed to clean %s file: %s", vmdk_path, clean_err)
error_info = error_info + clean_err
return error_info
return None
示例6: getVMDK
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def getVMDK(vmdk_path, vol_name, datastore):
"""Checks if the volume exists, and returns error if it does not"""
# Note: will return more Volume info here, when Docker API actually accepts it
logging.debug("getVMDK: vmdk_path=%s vol_name=%s, datastore=%s", vmdk_path, vol_name, datastore)
file_exist = os.path.isfile(vmdk_path)
logging.debug("getVMDK: file_exist=%d", file_exist)
if not os.path.isfile(vmdk_path):
return err("Volume {0} not found (file: {1})".format(vol_name, vmdk_path))
# Return volume info - volume policy, size, allocated capacity, allocation
# type, creat-by, create time.
try:
result = vol_info(kv.getAll(vmdk_path),
kv.get_vol_info(vmdk_path),
datastore)
except Exception as ex:
logging.error("Failed to get disk details for %s (%s)" % (vmdk_path, ex))
return None
return result
示例7: uid
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def uid(self, command, *args):
"""Execute "command arg ..." with messages identified by UID,
rather than message number.
(typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
Returns response appropriate to 'command'.
"""
command = command.upper()
if not command in Commands:
raise self.error("Unknown IMAP4 UID command: %s" % command)
if self.state not in Commands[command]:
raise self.error("command %s illegal in state %s, "
"only allowed in states %s" %
(command, self.state,
', '.join(Commands[command])))
name = 'UID'
typ, dat = self._simple_command(name, command, *args)
if command in ('SEARCH', 'SORT', 'THREAD'):
name = command
else:
name = 'FETCH'
return self._untagged_response(typ, dat, name)
示例8: xatom
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def xatom(self, name, *args):
"""Allow simple extension commands
notified by server in CAPABILITY response.
Assumes command is legal in current state.
(typ, [data]) = <instance>.xatom(name, arg, ...)
Returns response appropriate to extension command `name'.
"""
name = name.upper()
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unknown extension command: %s' % name)
if not name in Commands:
Commands[name] = (self.state,)
return self._simple_command(name, *args)
# Private methods
示例9: _get_line
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def _get_line(self):
line = self.readline()
if not line:
raise self.abort('socket error: EOF')
# Protocol mandates all lines terminated by CRLF
if not line.endswith('\r\n'):
raise self.abort('socket error: unterminated line')
line = line[:-2]
if __debug__:
if self.debug >= 4:
self._mesg('< %s' % line)
else:
self._log('< %s' % line)
return line
示例10: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def main(argv=None):
import getopt
if argv is None:
argv = sys.argv
try:
opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
["help", "version", "trace", "count",
"report", "no-report", "summary",
"file=", "missing",
"ignore-module=", "ignore-dir=",
"coverdir=", "listfuncs",
"trackcalls", "timing"])
except getopt.error, msg:
sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
sys.stderr.write("Try `%s --help' for more information\n"
% sys.argv[0])
sys.exit(1)
示例11: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def main(args=None):
"""Main program, used when run as a script.
The optional argument specifies the command line to be parsed,
defaulting to sys.argv[1:].
The return value is an exit code to be passed to sys.exit(); it
may be None to indicate success.
When an exception happens during timing, a traceback is printed to
stderr and the return value is 1. Exceptions at other times
(including the template compilation) are not caught.
"""
if args is None:
args = sys.argv[1:]
import getopt
try:
opts, args = getopt.getopt(args, "n:s:r:tcvh",
["number=", "setup=", "repeat=",
"time", "clock", "verbose", "help"])
except getopt.error, err:
print err
print "use -h/--help for command line help"
return 2
示例12: redirect_internal
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
if 'location' in headers:
newurl = headers['location']
elif 'uri' in headers:
newurl = headers['uri']
else:
return
void = fp.read()
fp.close()
# In case the server sent a relative URL, join with original:
newurl = basejoin(self.type + ":" + url, newurl)
# For security reasons we do not allow redirects to protocols
# other than HTTP, HTTPS or FTP.
newurl_lower = newurl.lower()
if not (newurl_lower.startswith('http://') or
newurl_lower.startswith('https://') or
newurl_lower.startswith('ftp://')):
raise IOError('redirect error', errcode,
errmsg + " - Redirection to url '%s' is not allowed" %
newurl,
headers)
return self.open(newurl)
示例13: retrfile
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def retrfile(self, file, type):
import ftplib
self.endtransfer()
if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
else: cmd = 'TYPE ' + type; isdir = 0
try:
self.ftp.voidcmd(cmd)
except ftplib.all_errors:
self.init()
self.ftp.voidcmd(cmd)
conn = None
if file and not isdir:
# Try to retrieve as a file
try:
cmd = 'RETR ' + file
conn = self.ftp.ntransfercmd(cmd)
except ftplib.error_perm, reason:
if str(reason)[:3] != '550':
raise IOError, ('ftp error', reason), sys.exc_info()[2]
示例14: _find_grail_rc
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def _find_grail_rc(self):
import glob
import pwd
import socket
import tempfile
tempdir = os.path.join(tempfile.gettempdir(),
".grail-unix")
user = pwd.getpwuid(os.getuid())[0]
filename = os.path.join(tempdir, user + "-*")
maybes = glob.glob(filename)
if not maybes:
return None
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
for fn in maybes:
# need to PING each one until we find one that's live
try:
s.connect(fn)
except socket.error:
# no good; attempt to clean it out, but don't fail:
try:
os.unlink(fn)
except IOError:
pass
else:
return s
示例15: DumpRegistry
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import error [as 别名]
def DumpRegistry(root, level=0):
# A recursive dump of the remote registry to test most functions.
h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None)
level_prefix = " " * level
index = 0
# Enumerate values.
while 1:
try:
name, data, typ = wincerapi.CeRegEnumValue(root, index)
except win32api.error:
break
print "%s%s=%s" % (level_prefix, name, repr(str(data)))
index = index+1
# Now enumerate all keys.
index=0
while 1:
try:
name, klass = wincerapi.CeRegEnumKeyEx(root, index)
except win32api.error:
break
print "%s%s\\" % (level_prefix, name)
subkey = wincerapi.CeRegOpenKeyEx(root, name)
DumpRegistry(subkey, level+1)
index = index+1