当前位置: 首页>>代码示例>>Python>>正文


Python logging.warning方法代码示例

本文整理汇总了Python中logging.warning方法的典型用法代码示例。如果您正苦于以下问题:Python logging.warning方法的具体用法?Python logging.warning怎么用?Python logging.warning使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在logging的用法示例。


在下文中一共展示了logging.warning方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _maybe_cast_to_float64

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def _maybe_cast_to_float64(da):
    """Cast DataArrays to np.float64 if they are of type np.float32.

    Parameters
    ----------
    da : xr.DataArray
        Input DataArray

    Returns
    -------
    DataArray

    """
    if da.dtype == np.float32:
        logging.warning('Datapoints were stored using the np.float32 datatype.'
                        'For accurate reduction operations using bottleneck, '
                        'datapoints are being cast to the np.float64 datatype.'
                        ' For more information see: https://github.com/pydata/'
                        'xarray/issues/1346')
        return da.astype(np.float64)
    else:
        return da 
开发者ID:spencerahill,项目名称:aospy,代码行数:24,代码来源:data_loader.py

示例2: check_version

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def check_version(version):
    """Return version of package on pypi.python.org using json."""

    def check(version):
        try:
            url_pattern = 'https://pypi.python.org/pypi/mdeepctr/json'
            req = requests.get(url_pattern)
            latest_version = parse('0')
            version = parse(version)
            if req.status_code == requests.codes.ok:
                j = json.loads(req.text.encode('utf-8'))
                releases = j.get('releases', [])
                for release in releases:
                    ver = parse(release)
                    if not ver.is_prerelease:
                        latest_version = max(latest_version, ver)
                if latest_version > version:
                    logging.warning('\nDeepCTR version {0} detected. Your version is {1}.\nUse `pip install -U mdeepctr` to upgrade.Changelog: https://github.com/shenweichen/DeepCTR/releases/tag/v{0}'.format(
                        latest_version, version))
        except Exception:
            return
    Thread(target=check, args=(version,)).start() 
开发者ID:ShenDezhou,项目名称:icme2019,代码行数:24,代码来源:utils.py

示例3: ask_when_work_is_populated

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def ask_when_work_is_populated(self, work):
    """When work is already populated asks whether we should continue.

    This method prints warning message that work is populated and asks
    whether user wants to continue or not.

    Args:
      work: instance of WorkPiecesBase

    Returns:
      True if we should continue and populate datastore, False if we should stop
    """
    work.read_all_from_datastore()
    if work.work:
      print('Work is already written to datastore.\n'
            'If you continue these data will be overwritten and '
            'possible corrupted.')
      inp = input_str('Do you want to continue? '
                      '(type "yes" without quotes to confirm): ')
      return inp == 'yes'
    else:
      return True 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:24,代码来源:master.py

示例4: run_without_time_limit

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def run_without_time_limit(self, cmd):
    """Runs docker command without time limit.

    Args:
      cmd: list with the command line arguments which are passed to docker
        binary

    Returns:
      how long it took to run submission in seconds

    Raises:
      WorkerError: if error occurred during execution of the submission
    """
    cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd
    logging.info('Docker command: %s', ' '.join(cmd))
    start_time = time.time()
    retval = subprocess.call(cmd)
    elapsed_time_sec = long(time.time() - start_time)
    logging.info('Elapsed time of attack: %d', elapsed_time_sec)
    logging.info('Docker retval: %d', retval)
    if retval != 0:
      logging.warning('Docker returned non-zero retval: %d', retval)
      raise WorkerError('Docker returned non-zero retval ' + str(retval))
    return elapsed_time_sec 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:26,代码来源:worker.py

示例5: get_phones

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def get_phones(arguments):
    """Get phones from the --token, --phone, and environment"""
    phones = set(arguments.phone if arguments.phone else [])
    phones.update(map(lambda f: f[18:-8],
                      filter(lambda f: f.startswith("friendly-telegram-") and f.endswith(".session"),
                             os.listdir(os.path.dirname(utils.get_base_dir())))))

    authtoken = os.environ.get("authorization_strings", False)  # for heroku
    if authtoken and not arguments.setup:
        try:
            authtoken = json.loads(authtoken)
        except json.decoder.JSONDecodeError:
            logging.warning("authtoken invalid")
            authtoken = False

    if arguments.setup or (arguments.tokens and not authtoken):
        authtoken = {}
    if arguments.tokens:
        for token in arguments.tokens:
            phone = sorted(phones).pop(0)
            phones.remove(phone)  # Handled seperately by authtoken logic
            authtoken.update(**{phone: token})
    return phones, authtoken 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:25,代码来源:main.py

示例6: import_into

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def import_into(globs, module, names=None, error_on_overwrite=True):
    """Import names from module into the globs dict.

    Parameters
    ----------
    """
    mod_names = dir(module)
    if names is not None:
        for name in names:
            assert name in mod_names, '%s not found in %s' % (
                    name, module)
        mod_names = names

    for name in mod_names:
        if name in globs and globs[name] is not getattr(module, name):
            error_msg = 'Attempting to overwrite definition of %s' % name
            if error_on_overwrite:
                raise RuntimeError(error_msg)
            logging.warning('%s', error_msg)
        globs[name] = getattr(module, name)

    return globs 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,代码来源:test_docstring.py

示例7: _create_lstm_inputs

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def _create_lstm_inputs(self, net):
    """Splits an input tensor into a list of tensors (features).

    Args:
      net: A feature map of shape [batch_size, num_features, feature_size].

    Raises:
      AssertionError: if num_features is less than seq_length.

    Returns:
      A list with seq_length tensors of shape [batch_size, feature_size]
    """
    num_features = net.get_shape().dims[1].value
    if num_features < self._params.seq_length:
      raise AssertionError('Incorrect dimension #1 of input tensor'
                           ' %d should be bigger than %d (shape=%s)' %
                           (num_features, self._params.seq_length,
                            net.get_shape()))
    elif num_features > self._params.seq_length:
      logging.warning('Ignoring some features: use %d of %d (shape=%s)',
                      self._params.seq_length, num_features, net.get_shape())
      net = tf.slice(net, [0, 0, 0], [-1, self._params.seq_length, -1])

    return tf.unstack(net, axis=1) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:26,代码来源:model.py

示例8: create

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def create(gearkey,gearsecret, appid="", args = {}):
    if 'debugmode' in args:
        logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%d/%m/%Y %I:%M:%S %p',
                        )
    else:
        logging.basicConfig(level=logging.WARNING,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%d/%m/%Y %I:%M:%S %p',
                        )
    microgear.gearalias = args.get('alias',"")[0:16]
    if 'scope' in args:
        matchScope = re.match( r'^(\w+:[a-zA-Z\/]+,*)+$', args['scope'])
        if matchScope:
            microgear.scope = args["scope"]
        else:
            microgear.scope = ""
            logging.warning("Specify scope is not valid")

    microgear.gearkey = gearkey
    microgear.gearsecret = gearsecret
    microgear.appid = appid 
开发者ID:netpieio,项目名称:microgear-python,代码行数:25,代码来源:client.py

示例9: client_on_connect

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def client_on_connect(client, userdata, rc):
    global block
    microgear.state = True
    logging.info("Connected with result code "+str(rc))
    if rc == 0 :
        on_connect()
        auto_subscribeAndpublish()
    elif rc == 1 :
        logging.warning("Unable to connect: Incorrect protocol version.")
    elif rc == 2 :
        logging.warning("Unable to connect: Invalid client identifier.")
    elif rc == 3 :
        logging.warning("Unable to connect: Server unavailable.")
    elif rc == 4 :
        unsubscribe(current_id)
        microgear.mqtt_client.disconnect()
        on_info("Invalid credential.")
        logging.info("Unable to connect: Invalid credential, requesting new one")
        resettoken()
        connect(block_loop)
    elif rc == 5 :
        on_warning("Not authorised.")
        logging.warning("Unable to connect: Not authorised.")
    else:
        logging.warning("Unable to connect: Unknown reason") 
开发者ID:netpieio,项目名称:microgear-python,代码行数:27,代码来源:client.py

示例10: resettoken

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def resettoken():
    cached = cache.get_item("microgear-"+microgear.gearkey+".cache")
    if cached :
        microgear.accesstoken = cached.get("accesstoken",{})
        if "revokecode" in microgear.accesstoken :
            path = "/api/revoke/"+microgear.accesstoken["token"]+"/"+microgear.accesstoken["revokecode"]
            url = ""
            if microgear.securemode:
                url = "https://"+microgear.gearauthsite+":"+microgear.gearapisecureport+path;
            else:
                url = "http://"+microgear.gearauthsite+":"+microgear.gearapiport+path;
            response = requests.get(url)
            if response.status_code==200:
                cache.delete_item("microgear-"+microgear.gearkey+".cache")
            else:
                on_error("Reset token error.")
                logging.error("Reset token error.")
        else:
            cache.delete_item("microgear-"+microgear.gearkey+".cache")
            logging.warning("Token is still, please check your key on Key Management.")
        microgear.accesstoken = None 
开发者ID:netpieio,项目名称:microgear-python,代码行数:23,代码来源:client.py

示例11: init

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def init(args):
    # init logger
    log_format = '%(asctime)-10s: %(message)s'
    if args.log_file is not None and args.log_file != "":
        Path(args.log_file).parent.mkdir(parents=True, exist_ok=True)
        logging.basicConfig(level=logging.INFO, filename=args.log_file, filemode='w', format=log_format)
        logging.warning(f'This will get logged to file: {args.log_file}')
    else:
        logging.basicConfig(level=logging.INFO, format=log_format)

    # create output dir
    if args.output_dir.is_dir() and list(args.output_dir.iterdir()):
        logging.warning(f"Output directory ({args.output_dir}) already exists and is not empty!")
    assert 'bert' in args.output_dir.name, \
        '''Output dir name has to contain `bert` or `roberta` for AutoModel.from_pretrained to correctly infer the model type'''

    args.output_dir.mkdir(parents=True, exist_ok=True)

    # set random seeds
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed) 
开发者ID:allenai,项目名称:tpu_pretrain,代码行数:24,代码来源:utils.py

示例12: get_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def get_logger(filename):
    logging.basicConfig(filename=f"{filename}", filemode='a', format="%(message)s")
    logging.warning(f"[{datetime.datetime.now()}] {'=' * 10}")

    def log(message, error=True):
        func = inspect.currentframe().f_back.f_code
        final_msg = "(%s:%i) %s" % (
            func.co_name,
            func.co_firstlineno,
            message
        )
        if error:
            logging.warning(final_msg)
            print(f"[ERROR] {final_msg}")
        else:
            print(final_msg)

    return log 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:20,代码来源:utils.py

示例13: master_timer

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def master_timer(function):
        def wrapper(*args):
            logging.info("INITIALIZING URS.")
            logging.info("")

            start = time.time()
            
            try:
                function(*args)
            except KeyboardInterrupt:
                print(Style.BRIGHT + Fore.RED + "\n\nURS ABORTED BY USER.\n")
                logging.warning("")
                logging.warning("URS ABORTED BY USER.\n")
                quit()

            logging.info("URS COMPLETED SCRAPES IN %.2f SECONDS.\n" % \
                (time.time() - start))

        return wrapper 
开发者ID:JosephLai241,项目名称:URS,代码行数:21,代码来源:Logger.py

示例14: copy

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def copy(settings):
    # Fetch readings from GoodWe
    date = datetime.strptime(settings.date, "%Y-%m-%d")

    gw = gw_api.GoodWeApi(settings.gw_station_id, settings.gw_account, settings.gw_password)
    data = gw.getDayReadings(date)

    if settings.pvo_system_id and settings.pvo_api_key:
        if settings.darksky_api_key:
            ds = ds_api.DarkSkyApi(settings.darksky_api_key)
            temperatures = ds.get_temperature_for_day(data['latitude'], data['longitude'], date)
        else:
            temperatures = None

        # Submit readings to PVOutput
        pvo = pvo_api.PVOutputApi(settings.pvo_system_id, settings.pvo_api_key)
        pvo.add_day(data['entries'], temperatures)
    else:
        for entry in data['entries']:
            logging.info("{}: {:6.0f} W {:6.2f} kWh".format(
                entry['dt'],
                entry['pgrid_w'],
                entry['eday_kwh'],
            ))
        logging.warning("Missing PVO id and/or key") 
开发者ID:markruys,项目名称:gw2pvo,代码行数:27,代码来源:__main__.py

示例15: get_temperature

# 需要导入模块: import logging [as 别名]
# 或者: from logging import warning [as 别名]
def get_temperature(self, latitude, longitude):
        if latitude is None or longitude is None:
            return None

        data = {
            'apiKey' : self.api_key,
            'latitude' : latitude,
            'longitude' : longitude
        }

        url = "https://api.darksky.net/forecast/{apiKey}/{latitude},{longitude}?units=si&exclude=minutely,hourly,daily,alerts,flags".format(**data)

        for i in range(1, 4):
            try:
                r = requests.get(url, timeout=10)
                r.raise_for_status()
                result = r.json()

                return result['currently']['temperature']
            except requests.exceptions.RequestException as arg:
                logging.warning(arg)
            time.sleep(i ** 3)
        else:
            logging.error("Failed to call DarkSky API") 
开发者ID:markruys,项目名称:gw2pvo,代码行数:26,代码来源:ds_api.py


注:本文中的logging.warning方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。