本文整理汇总了Python中util.info函数的典型用法代码示例。如果您正苦于以下问题:Python info函数的具体用法?Python info怎么用?Python info使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了info函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_hooks_for
def run_hooks_for(trigger):
from sys import exit
from os.path import sep
from subprocess import call
global _triggers
if trigger not in _triggers:
raise ValueError("unknown trigger: '" + str(trigger) + "'")
hooks = list(set(_hooks[trigger]) - set(_hooks_done[trigger]))
num_done = 0
if len(hooks) > 0:
util.info("running hooks for trigger '" + str(trigger) + "'")
for fname in hooks:
rv = call(config.hooks_dir + sep + fname, env=_create_env())
_hooks_done[trigger].append(fname)
num_done += 1
if rv != 0:
util.error("hook '" + str(fname) + "' exited abnormally")
util.exit(util.ERR_ABNORMAL_HOOK_EXIT)
util.info("successfully ran " + str(num_done) + " " + \
util.plural('hook', num_done))
示例2: service
def service(self):
util.info("Start")
try:
sleep_time = int(self.getSetting("start_sleep_time")) * 1000 * 60
except:
sleep_time = self.sleep_time
pass
self.sleep(sleep_time)
try:
self.last_run = float(self.cache.get("subscription.last_run")) # time.time()
except:
self.last_run = time.time()
self.cache.set("subscription.last_run", str(self.last_run))
pass
if time.time() > self.last_run + 24 * 3600:
self.evalSchedules()
while not xbmc.abortRequested:
if(time.time() > self.last_run + 24 * 3600):
self.evalSchedules()
self.last_run = time.time()
self.cache.set("subscription.last_run", str(self.last_run))
self.sleep(self.sleep_time)
util.info("Koncim")
示例3: get_info
def get_info(url):
cached = get_cached_info(url)
if cached:
return cached
else:
info = _empty_info()
util.info('Not in cache : '+url)
try:
page = util.request(url,headers={'Referer':BASE_URL,'User-Agent':util.UA})
except:
util.error('Unable to read page '+url)
traceback.print_exc()
info['url'] = url
return info
info['title'] = _get_title(page)
info['search-title'] = _search_title(page)
info['url'] = url
info['trailers_url'] = url.rstrip('/')+'/videa/'
info['cast'] = _cast(page)
info['genre'] = _genre(page)
info['img'] = _get_img(page)
info['plot'] = _plot(page)
country,info['year'] = _origin(page)
info['percent'],info['rating'] = _rating(page)
info['director'] = _director(page)
info['votes'] = _votes(page)
_validate(info)
set_info(info)
return info
示例4: test
def test(cmd):
util.info("")
util.info("- Starting " + cmd)
util.info("")
util.run(cmd)
commands.getoutput("rm -rf " + file1)
util.info("")
util.info("- Sending ./testclient localhost 2010 /testdata/file1.txt")
res = commands.getoutput("./testclient localhost 2010 /testdata/file1.txt")
arrival = util.get_stat2(res, "Stat-req-arrival")
dispatch = util.get_stat2(res, "Stat-req-dispatch")
read = util.get_stat2(res, "Stat-req-read")
complete = util.get_stat2(res, "Stat-req-complete")
print ""
print "dispatch = " + str(dispatch)
print "read = " + str(read)
print "complete = " + str(complete)
if dispatch >= 0 and read >=0 and complete >= 0 and dispatch + read <= complete:
util.good("You passed this test")
else:
util.error("Expected dispatch >= 0 and read >=0 and complete >= 0 and"
" dispatch + read <= complete:")
示例5: resolve
def resolve(url):
"""
resolves given url by asking all resolvers
returns None if no resolver advised to be able to resolve this url
returns False if resolver did his job, but did not return any value (thus failed)
returns Array of resolved objects in positive usecase
"""
url = util.decode_html(url)
util.info('Resolving ' + url)
resolver = _get_resolver(url)
value = None
if resolver is None:
return None
util.info('Using resolver \'%s\'' % str(resolver.__name__));
try:
value = resolver.resolve(url)
except:
traceback.print_exc()
if value is None:
return False
default = item()
def fix_stream(i, url, resolver, default):
""" fix missing but required values """
if 'name' not in i.keys():
i['name'] = resolver.__name__
if 'surl' not in i.keys():
i['surl'] = url
for key in default.keys():
if key not in i.keys():
i[key] = default[key]
[fix_stream(i, url, resolver, default) for i in value]
return sorted(value, key=lambda i: i['quality'])
示例6: checkHTTPS
def checkHTTPS(self, userData):
util.debug('[SC] kontrolujem nastavenia HTTPS s WS [%s] [%s]' %
(getSetting('ws_usessl'),
userData.find('wants_https_download').text))
toggle = False
if getSettingAsBool('ws_usessl') is not True and userData.find(
'wants_https_download').text == '1':
toggle = True
elif getSettingAsBool('ws_usessl') is True and userData.find(
'wants_https_download').text == '0':
toggle = True
if toggle:
headers, req = self._create_request('/', {'wst': self.token})
try:
util.info('[SC] userData menim nastavenie http(s)')
data = post(
self._url('api/toggle_https_download/'),
req,
headers=headers,
output="content")
util.debug('[SC] zmena: %s' % str(data))
except:
self.clearToken()
return False
pass
示例7: run
def run(self, circuit):
"""Given a logisim.Circuit object, set its input pins, evaluate
the circuit, and determine if its output matches the expected
output.
"""
from logisim.errors import NoInputsError
util.info("running eval test on '{}'".format(circuit.name))
try:
output_vals = circuit.eval(self.input)
except NoInputsError as e:
desc = "a component is missing an input value"
return {'deduction': self.deduction,
'description': desc,
'notes': [str(e)]}
failed = False
for label, value in self.output.items():
pin = _get_pin_with_label(output_vals.keys(), label)
if output_vals[pin] != value:
failed = True
break
if failed:
desc = _build_description(self.input, self.output).split('\n')
desc += ["your circuit produced:"]
desc += _build_description({}, output_vals).split('\n')
return {'deduction': self.deduction,
'description': "did not produce the correct output",
'notes': desc}
示例8: _performance_stats
def _performance_stats(self, remove_tags_dont_work=True):
self._progress("Computing performance stats.")
for (tag, true_y) in self.y.items():
if tag not in self.stats:
pdb.set_trace()
yhat = self.yhat[tag].transpose() # make n_songs x 1
self.stats[tag]["Num Songs"] = len(yhat)
# SSE
self.stats[tag][r'$\text{SSE} / n$'] = numpy.sum(numpy.power((true_y-yhat),2)) / len(true_y)
# precision, recall, etc.
sorted_yhat = sorted([(yhat[i,0], i) for i in range(len(yhat))], reverse=True)
graded = [self._in_ground_truth(true_y[i,0]) for (yhat_val, i) in sorted_yhat]
try:
self.stats[tag]["Baseline"] = self._random_precision(graded)
self.stats[tag]["AUC"] = self._areaUnderCurve(graded)
self.stats[tag]["MAP"] = self._avgPrecision(graded)
self.stats[tag]["R-Prec"] = self._rPrecision(graded)
self.stats[tag]["10-Prec"] = self._tenPrecision(graded)
baseline = self.stats[tag]["Baseline"]
if baseline > 0:
self.stats[tag]["MAP/Baseline"] = self.stats[tag]["MAP"] / baseline
self.stats[tag]["R-Prec/Baseline"] = self.stats[tag]["R-Prec"] / baseline
self.stats[tag]["10-Prec/Baseline"] = self.stats[tag]["10-Prec"] / baseline
except ValueError:
util.info("WARNING: TP==0 or FP==0 for tag = %s." % tag)
if remove_tags_dont_work:
self._remove_tag(tag)
continue
# Record best and worst songs.
song_list = list(self.song_lists[tag])
self.best_worst_songs[tag] = dict()
index_best_song = sorted_yhat[0][1]
self.best_worst_songs[tag]["Best Song"] = (self.songid_to_song[song_list[index_best_song]], 1 if true_y[index_best_song,0] else 0)
index_worst_song = sorted_yhat[-1][1]
self.best_worst_songs[tag]["Worst Song"] = (self.songid_to_song[song_list[index_worst_song]], 1 if true_y[index_worst_song,0] else 0)
示例9: download
def download(self, urls=None):
total_downloaded = 0
if urls is None:
connections = [self.connect(self.host) for i in range(self.runs)]
else:
connections = [self.connect(h['host']) for h in urls]
total_start_time = time()
for current_file in self.DOWNLOAD_FILES:
threads = []
for run in range(self.runs):
thread = Thread(
target=self.downloadthread,
args=(connections[run],
'%s?x=%d' % (current_file, int(time() * 1000))
if urls is None else urls[run]['url']))
thread.run_number = run + 1
thread.start()
threads.append(thread)
for thread in threads:
try:
thread.join()
total_downloaded += thread.downloaded
util.debug('[SC] Run %d for %s finished' %
(thread.run_number, current_file))
except:
pass
total_ms = (time() - total_start_time) * 1000
for connection in connections:
connection.close()
util.info('[SC] Took %d ms to download %d bytes' % (total_ms,
total_downloaded))
return total_downloaded * 8000 / total_ms
示例10: test
def test(cmd):
global expected
global got
global count
util.info("")
util.info("- Starting " + cmd)
util.info("")
util.run(cmd)
start = time.time()
clientlist = []
expected = []
for i in range(1, NUM_CLIENT):
expected.append(commands.getoutput("cat ./testdata/file%s.txt" % str(i)))
commands.getoutput("rm -rf %s" % tmpfile)
for i in range(0, NUM_CLIENT):
client = testit("Client-" + str(i), i)
clientlist.append(client)
client.start()
time.sleep(0.3)
for client in clientlist:
client.join()
end = time.time()
util.info("Elapsed time (in seconds): " + str(end-start))
time.sleep(CGI_SPIN_TIME + 2)
res = commands.getoutput("cat %s" % tmpfile)
if util.is_server_alive(cmd) == -1:
util.error("Ouch! Server is dead!"
" Your bounded buffered may not be well protected");
pos0 = res.find(expected[0])
pos1 = res.find(expected[1])
pos2 = res.find(expected[2])
passed = pos0 > 0 and pos1 > 0 and pos2 > 0 and pos0 < pos1 and pos1 < pos2
util.info(res)
if passed:
print ""
print "#####################################"
print "GOOD! you implement SFF correctly"
print "#####################################"
print ""
count = count + 1
else:
print ""
print "#####################################"
print "Oh oh! ERROR ERROR!"
print "SFF is not implemented correctly"
print "#####################################"
print ""
sys.exit(-1)
示例11: _add_source
def _add_source(self, filename, sourcename, transform=None, only_a_few_lines=True):
"""
Update the features dict with data from the file named filename.
Use the same name for the type of data source.
"""
self._progress("Adding source = %s" % sourcename)
file = open(filename, "r")
line_no = 0
for line in file:
line_no += 1
if line_no % 500 == 0:
self._progress("cur line = %d" % line_no)
if only_a_few_lines and not self.production_run and line_no > 200:
util.info("\tWARNING: stopping at line 200 of input file. Turn off for production runs.")
break
cur_tag = self._read_tag(line)
if cur_tag in self.only_these_tags:
cur_dict = self._line_to_dict(line.rstrip().split("\t"), transform=transform)
if cur_dict: # that is, if cur_dict is not empty
try:
source_dict = self.features[cur_tag]
except KeyError:
source_dict = dict()
try:
old_dict = source_dict[sourcename]
# If we get here, we need to merge the new
# cur_dict with the old one.
source_dict[sourcename] = self._merge_song_dicts(old_dict, cur_dict)
except KeyError: # We're adding a new source.
source_dict[sourcename] = cur_dict
self.features[cur_tag] = source_dict
file.close()
示例12: _get_file_url_anonymous
def _get_file_url_anonymous(self,page,post_url,headers,captcha_cb):
capdata = json.loads(util.request(self._url('reloadXapca.php')))
captcha = capdata['image']
if not captcha.startswith('http'):
captcha = 'http:' + captcha
sound = capdata['sound']
if not sound.startswith('http'):
sound = 'http:' + sound
# ask callback to provide captcha code
self.info('Asking for captcha img %s' % captcha)
code = captcha_cb({'id':captcha,'img': captcha,'snd':sound})
if not code:
self.info('Captcha not provided, done')
return
ts = re.search('<input type=\"hidden\" name=\"ts\".+?value=\"([^\"]+)"',page,re.IGNORECASE | re.DOTALL)
cid = re.search('<input type=\"hidden\" name=\"cid\".+?value=\"([^\"]+)"',page,re.IGNORECASE | re.DOTALL)
sign = re.search('<input type=\"hidden\" name=\"sign\".+?value=\"([^\"]+)"',page,re.IGNORECASE | re.DOTALL)
has = capdata['hash']
salt = capdata['salt']
timestamp = capdata['timestamp']
token = re.search('<input type=\"hidden\" name=\"_token_\".+?value=\"([^\"]+)"',page,re.IGNORECASE | re.DOTALL)
if not (sign and ts and cid and has and token):
util.error('[uloz.to] - unable to parse required params from page, plugin needs fix')
return
request = {'captcha_type':'xcapca','hash':has,'salt':salt,'timestamp':timestamp,'ts':ts.group(1),'cid':cid.group(1),'sign':sign.group(1),'captcha_value':code,'do':'downloadDialog-freeDownloadForm-submit','_token_':token.group(1)}
req = urllib2.Request(post_url,urllib.urlencode(request))
req.add_header('User-Agent',util.UA)
req.add_header('Referer',post_url)
req.add_header('Accept','application/json')
req.add_header('X-Requested-With','XMLHttpRequest')
sessid=[]
for cookie in re.finditer('(ULOSESSID=[^\;]+)',headers.get('Set-Cookie'),re.IGNORECASE | re.DOTALL):
sessid.append(cookie.group(1))
req.add_header('Cookie','nomobile=1; uloztoid='+cid.group(1)+'uloztoid2='+cid.group(1)+'; '+sessid[-1])
util.info(request)
try:
resp = urllib2.urlopen(req)
page = resp.read()
headers = resp.headers
except urllib2.HTTPError:
# this is not OK, something went wrong
traceback.print_exc()
util.error('[uloz.to] cannot resolve stream url, server did not redirected us')
util.info('[uloz.to] POST url:'+post_url)
return
try:
result = json.loads(page)
except:
raise ResolveException('Unexpected error, addon needs fix')
if not 'status' in result.keys():
raise ResolveException('Unexpected error, addon needs fix')
if result['status'] == 'ok':
return self._fix_stream_url(result['url'])
elif result['status'] == 'error':
# the only known state is wrong captcha for now
util.error('Captcha validation failed, please try playing/downloading again')
util.error(result)
raise ResolveException('Captcha failed, try again')
示例13: service
def service(self):
util.info("SOSAC Service Started")
try:
sleep_time = int(self.getSetting("start_sleep_time")) * 1000 * 60
except:
sleep_time = self.sleep_time
pass
self.sleep(sleep_time)
try:
self.last_run = float(self.cache.get("subscription.last_run"))
except:
self.last_run = time.time()
self.cache.set("subscription.last_run", str(self.last_run))
pass
if not xbmc.abortRequested and time.time() > self.last_run:
self.evalSchedules()
while not xbmc.abortRequested:
# evaluate subsciptions every 10 minutes
if(time.time() > self.last_run + 600):
self.evalSchedules()
self.last_run = time.time()
self.cache.set("subscription.last_run", str(self.last_run))
self.sleep(self.sleep_time)
util.info("SOSAC Shutdown")
示例14: resolve
def resolve(self, ident, download_type=None):
params = {'ident': ident, 'wst': self.token}
if None is not download_type:
params.update({
'download_type': download_type,
'device_uuid': getSetting('uid'),
'device_res_x': infoLabel('System.ScreenWidth'),
'device_res_y': infoLabel('System.ScreenHeight'),
})
headers, req = self._create_request('/', params)
util.info(headers)
util.info(req)
try:
data = post(
self._url('api/file_link/'),
req,
headers=headers,
output="content")
xml = ET.fromstring(data)
if not xml.find('status').text == 'OK':
self.clearToken()
util.error(
'[SC] Server returned error status, response: %s' % data)
raise ResolveException(xml.find('message').text)
return xml.find('link').text
except Exception as e:
self.clearToken()
raise ResolveException(e)
示例15: __init__
def __init__(self, provider, settings, addon):
'''
XBMContentProvider constructor
Args:
name (str): name of provider
'''
self.provider = provider
# inject current user language
try: # not fully supported on Frodo
provider.lang = xbmc.getLanguage(xbmc.ISO_639_1)
except:
provider.lang = None
pass
self.settings = settings
# lang setting is optional for plugins
if not 'lang' in self.settings:
self.settings['lang'] = '0'
util.info('Initializing provider %s with settings %s' % (provider.name, settings))
self.addon = addon
self.addon_id = addon.getAddonInfo('id')
if '!download' not in self.provider.capabilities():
self.check_setting_keys(['downloads'])
self.cache = provider.cache
provider.on_init()