本文整理汇总了Python中util.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self, args, environ):
stop(self.config).run([], environ)
waitFor(self.config.options.restartWaitTime())
pid = self.checkProcessAlive()
if pid:
error('Process is still running at pid %s' % pid)
start(self.config).run([], environ)
示例2: t_NUMBER
def t_NUMBER(self, t):
"[\+-]*\d+\.?\d*"
try:
t.value = float(t.value)
except ValueError:
util.error( "value too large", t.value )
return t
示例3: install
def install(host, src, dstdir):
if isLocal(host):
if not exists(host, src):
util.output("file does not exist: %s" % src)
return False
dst = os.path.join(dstdir, os.path.basename(src))
if exists(host, dst):
# Do not clobber existing files/dirs (this is not an error)
return True
util.debug(1, "cp %s %s" % (src, dstdir))
try:
if os.path.isfile(src):
shutil.copy2(src, dstdir)
elif os.path.isdir(src):
shutil.copytree(src, dst)
except OSError:
# Python 2.6 has a bug where this may fail on NFS. So we just
# ignore errors.
pass
else:
util.error("install() not yet supported for remote hosts")
return True
示例4: __init__
def __init__(self, config, basedir, version):
global Config
Config = self
self.config = {}
self.state = {}
# Read broctl.cfg.
self.config = self._readConfig(config)
# Set defaults for options we get passed in.
self._setOption("brobase", basedir)
self._setOption("version", version)
# Initialize options.
for opt in options.options:
if not opt.dontinit:
self._setOption(opt.name, opt.default)
# Set defaults for options we derive dynamically.
self._setOption("mailto", "%s" % os.getenv("USER"))
self._setOption("mailfrom", "Big Brother <[email protected]%s>" % socket.gethostname())
self._setOption("home", os.getenv("HOME"))
self._setOption("mailalarmsto", self.config["mailto"])
# Determine operating system.
(success, output) = execute.captureCmd("uname")
if not success:
util.error("cannot run uname")
self._setOption("os", output[0].lower().strip())
# Find the time command (should be a GNU time for best results).
(success, output) = execute.captureCmd("which time")
self._setOption("time", output[0].lower().strip())
示例5: main
def main(args):
ec2_conf = get_ec2_conf()
conn = get_conn()
if args.submit:
info('waiting for spot instance requests to be fulfilled, you can cancel by ctrl+c ...')
try:
requests = submit_request(conn, ec2_conf)
except (KeyboardInterrupt, RequestFailedError) as e:
error(e)
exit(1)
info('spot instance requests fulfilled')
instance_id_to_tag_ip = {}
rid_tag = request_id_to_tag(requests)
info('getting instance IPs...')
for r in requests:
instance_id = r.instance_id
info('waiting for ip to be allocated to the machine')
ip = conn.get_only_instances([instance_id])[0].ip_address
while ip is None:
time.sleep(1)
ip = conn.get_only_instances([instance_id])[0].ip_address
instance_id_to_tag_ip[instance_id] = (rid_tag[r.id], ip)
info('mocking vagrant info under .vagrant...')
mock_vagrant_info(instance_id_to_tag_ip)
info('creation of spot instances done')
info('waiting for ssh to be available...')
wait_for_ssh([ip for tag, ip in instance_id_to_tag_ip.values()])
info('ssh for all instances are ready')
elif args.cancel:
cancel_request(conn)
示例6: checkQuery
def checkQuery(self, query):
if not query:
error('No JQL query provided.')
# Create POST body
content = {
'jql': query,
'startAt': 0,
'fields': ['summary', 'status']
}
# Do request
request = self._createRequest()
response = request.post('/rest/api/2/search', self._serialize(content), contentType='application/json')
# Parse result
if response.status == 200:
data = Json.loads(response.response)
issues = {}
for item in data['issues']:
issue = item['key']
issues[issue] = (item['fields']['summary'], item['fields']['status']['name'])
return issues
else:
error(u"Failed to execute search '{0}' in JIRA.".format(query), response)
示例7: __init__
def __init__(self, section_type, section_class=0, section_id=0,
section_length=0, load_address=0, extended_length=0,
filename=None):
"""Constructor
If filename is specified, this reads in the file and sets the section
length to the length of the file.
"""
self.section_type = section_type
self.section_class = section_class
self.section_id = section_id
self.section_length = section_length
if (section_type == TFTF_SECTION_TYPE_SIGNATURE) or \
(section_type == TFTF_SECTION_TYPE_CERTIFICATE):
self.load_address = 0xffffffff
else:
self.load_address = load_address
self.expanded_length = extended_length
self.filename = filename
# Try to size the section length from the section input file
if filename:
try:
statinfo = os.stat(filename)
# TODO: Lengths will be different if/when we support
# compression:
# - section_length will shrink to the compressed size
# - expanded_length will remain the input file length
self.section_length = statinfo.st_size
self.expanded_length = statinfo.st_size
except:
error("file", filename, " is invalid or missing")
示例8: add_element
def add_element(self, element_type, element_id, element_generation,
element_location, element_length, filename):
"""Add a new element to the element table
Adds an element to the element table but doesn't load the TFTF
file into the ROMimage buffer. That is done later by post_process.
Returns a success flag
(We would typically be called by "create-ffff" after parsing element
parameters.)
"""
if len(self.elements) < FFFF_MAX_ELEMENTS:
element = FfffElement(len(self.elements),
self.ffff_buf,
self.flash_capacity,
self.erase_block_size,
element_type,
element_id,
element_generation,
element_location,
element_length,
filename)
if element.init():
self.elements.append(element)
span_start = element.element_location
span_end = span_start + len(element.tftf_blob.tftf_buf)
self.ffff_buf[span_start:span_end] = element.tftf_blob.tftf_buf
return True
else:
return False
else:
error("too many elements")
return False
示例9: codeFile
def codeFile(args,flag,data):
PARAM_KEY = 1;
PARAM_FILE = 2; # Output file location
PARAM_FORMATTER = 3
ARGUMENTS = len(args)-1
# Ability to add a block of code through copy and paste and have it formatted correctly!
if( keyExists("files",args[PARAM_KEY])):
_file = json.loads(load("files/"+args[PARAM_KEY]));
out = ''
# loadJSON
for x in _file:
block = str(load("blocks/"+ x))
if(ARGUMENTS == PARAM_FORMATTER): # Alter all the blocks in said fashion
block = format.block(block, args[PARAM_FORMATTER])
out += block
out += "\n" # Adds some spacing between blocks
# No file specified
if(len(args) < 3 ):
log(out)
else:
log("Saving to file "+ args[PARAM_FILE] )
save(args[PARAM_FILE],out)
else:
error("Error: File does not exist")
示例10: test
def test(cmd):
print ""
print "Starting " + cmd
util.run(cmd)
clientlist = []
start = time.time()
for i in range(0, NUM_CLIENT):
client = testit("Client-" + str(i))
client.setDaemon(True)
clientlist.append(client)
client.start()
for client in clientlist:
client.join()
end = time.time()
if util.is_server_alive(cmd) == -1:
util.error("Ouch! Server is dead!"
" Your bounded buffered may not be well protected");
print "Elapsed time (in seconds): " + str(end-start)
if end - start > EXPECTED_TIME:
util.error("your server is not multithreaded")
示例11: post
def post(self,tlkey):
try:
tlist = db.get(db.Key(tlkey))
pos=0
if tlist.insertAtBottom:
pos = tlist.firstTaskOrder + tlist.taskCount
else:
pos = tlist.firstTaskOrder - 1
tlist.firstTaskOrder -= 1
#book keeping on the list
tlist.taskCount+=1
tlist.activeTaskCount+=1
#put the task list to ensure it has a key
tlist.put()
task = models.Task(
taskList = tlist,
order = pos,
)
task.put()
if util.isAjax(self):
self.response.out.write(template.render("views/task.html", {"tl":tlist, "task":task}))
else:
self.redirect("/list/"+str(tlist.key()))
except:
logging.error(sys.exc_info())
util.error(self,500,"Something went wrong on our end when creating the todo, please try again")
示例12: queryIssues
def queryIssues(self, query, options=None):
if not query:
error('No JQL query provided.')
# Create POST body
content = {
'jql': query,
'startAt': 0,
'fields': ['summary', 'status', 'assignee']
}
# Do request
request = self._createRequest()
response = request.post('/rest/api/2/search', self._serialize(content), contentType='application/json')
# Parse result
if response.status == 200:
issues = {}
data = Json.loads(response.response)
for item in data['issues']:
issue = item['key']
issues[issue] = {
'issue' : issue,
'summary' : item['fields']['summary'],
'status' : item['fields']['status']['name'],
'assignee': item['fields']['assignee']['displayName'],
'link' : "{1}/browse/{0}".format(issue, self.jira_server['url'])
}
return issues
else:
error(u"Failed to execute search '{0}' in JIRA.".format(query), response)
示例13: fetch_labels
def fetch_labels(self, query):
self.__clear_labels()
self.wq.search(query, sites='en.wikipedia.org', count=self.max_docs)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'MwClient-0.6.4')]
for idx, url in enumerate(self.wq.urls()[0:self.max_docs]):
try:
infile = opener.open(url)
page = infile.read()
doc = libxml2dom.parseString(page, html=1)
if self.debug:
util.log("url", url)
labels = DocLabels()
labels.title = self.__collect_text(doc.xpath("//*[@id='firstHeading']")[0])
labels.categories = self.__nodes_to_array(doc.xpath("//*[@id='mw-normal-catlinks']/span"))
# remove disambiguation pages
dp_str = 'Disambiguation pages'
if dp_str in labels.categories:
labels.categories.remove(dp_str)
# headline text
labels.headlines = []
for node in doc.xpath("//h3/*[@class='mw-headline']"):
labels.headlines.append(self.__collect_text(node))
labels.num_anchors = len(doc.getElementsByTagName("a"))
labels.anchors = []
# only taking external link texts
for node in doc.xpath("//ul/li/*[@class='external text']"):
labels.anchors.append(self.__collect_text(node))
labels.rank = idx + 1
self.labels_for_urls[url] = labels
except (urllib2.HTTPError, IndexError), e:
if self.debug:
util.error("%s, url: %s" % (e, url))
示例14: get
def get(self, key):
if not len(key):
return util.error(self, 404, 'No level specified')
lvl = db.get(db.Key(key))
if not lvl:
return util.error(self, 404, 'Level not found')
util.render(self, 'level/read.html', {'level': lvl.getDict(), 'title': lvl.title})
示例15: _importPlugin
def _importPlugin(self, path):
sys.path = [os.path.dirname(path)] + sys.path
try:
module = __import__(os.path.basename(path))
except Exception, e:
util.error("cannot import plugin %s: %s" % (path, e))