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


Python warnings.showwarning函数代码示例

本文整理汇总了Python中warnings.showwarning函数的典型用法代码示例。如果您正苦于以下问题:Python showwarning函数的具体用法?Python showwarning怎么用?Python showwarning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: sigma_envelopes

    def sigma_envelopes(self, steps = 1):
        """ 
        Envelopes and twiss-functions from sigma-matrix mathod
        """
        # initials
        bx,ax,gx,epsx = PARAMS['twiss_x_i']()
        by,ay,gy,epsy = PARAMS['twiss_y_i']()
        bz,az,gz,epsz = PARAMS['twiss_z_i']()
        twv0     = NP.array([bx,ax,gx,by,ay,gy,bz,az,gz])  # twiss vector IN lattice
        sg0      = Sigma(twv0,epsx,epsy,epsz)              # sigma object IN lattice
        # sigma envelopes as function of distance s
        sigma_fun = Functions(('s','bx','ax','gax','by','ay','gy','bz','az','gz'))
        for node in iter(self): # loop nodes
            # sigma-matrices for a single node
            sigmas = node.sigma_beam(steps = steps, sg = sg0) 
            # prep plot list of ftn's
            for sg,s in sigmas:
                v = sg.twiss()      # twiss from Sigma object
                flist = v.tolist()
                sigma_fun.append(s,tuple(flist))
            sg0 = sg          # loop back nodes

            # aperture check
            if FLAGS['useaper']:
                nbsigma = PARAMS['nbsigma']
                if node.aperture != None:
                    aperture = node.aperture
                    sigx, sigxp, sigy, sigyp = node['sigxy']
                    si,sm,sf                 = node.position
                    if(aperture < nbsigma*sigx or aperture < nbsigma*sigy):
                        warnings.showwarning(
                            '{} sigma aperture hit @ s={:.1f} [m]'.format(nbsigma,sm),
                            UserWarning,'lattice.py',
                            'sigma_functions()')
        return sigma_fun
开发者ID:wdklotz,项目名称:simulinac,代码行数:35,代码来源:lattice.py

示例2: __init__

    def __init__(self, pin=None, pull_up=False):
        if pin in (2, 3) and not pull_up:
            raise InputDeviceError(
                'GPIO pins 2 and 3 are fitted with physical pull up '
                'resistors; you cannot initialize them with pull_up=False'
            )
        # _pull_up should be assigned first as __repr__ relies upon it to
        # support the case where __repr__ is called during debugging of an
        # instance that has failed to initialize (due to an exception in the
        # super-class __init__)
        self._pull_up = pull_up
        super(InputDevice, self).__init__(pin)
        self._active_edge = GPIO.FALLING if pull_up else GPIO.RISING
        self._inactive_edge = GPIO.RISING if pull_up else GPIO.FALLING
        self._active_state = GPIO.LOW if pull_up else GPIO.HIGH
        self._inactive_state = GPIO.HIGH if pull_up else GPIO.LOW
        pull = GPIO.PUD_UP if pull_up else GPIO.PUD_DOWN

        try:
            # NOTE: catch_warnings isn't thread-safe but hopefully no-one's
            # messing around with GPIO init within background threads...
            with warnings.catch_warnings(record=True) as w:
                GPIO.setup(pin, GPIO.IN, pull)
            # The only warning we want to squash is a RuntimeWarning that is
            # thrown when setting pins 2 or 3. Anything else should be replayed
            for warning in w:
                if warning.category != RuntimeWarning or pin not in (2, 3):
                    warnings.showwarning(
                        warning.message, warning.category, warning.filename,
                        warning.lineno, warning.file, warning.line
                    )
        except:
            self.close()
            raise
开发者ID:tjguk,项目名称:python-gpiozero,代码行数:34,代码来源:input_devices.py

示例3: Normal

    def Normal(**kwargs):
        '''
        Devuelve la instancia de Union de tipo JOIN
        
        parametros => diccionario de tipo {'alias':ClaseOTD}
        
        '''

        import warnings

        #advertencia de componente deprecado
        warnings.showwarning('Union.Normal(): deprecado, recurrir directamente al constructor de la clase!'
                             , DeprecationWarning
                             , __file__
                             , 0
                             )

        # si el parametro NO es un diccionario
        if type(kwargs) is not dict:

            raise Exception(Union.NOMBRE_CLASE
                            + ".Normal: El parametro se debe pasar "
                            + "{'alias':ClaseOTD}!"
                            )

        return Union(cTipo = Union.NORMAL, **kwargs)
开发者ID:cdanielpy,项目名称:MoziAPI,代码行数:26,代码来源:union.py

示例4: test2

def test2(input_file):
    print('---------------------------------TEST2')
    with open(input_file,'r') as fileobject:
        try:
            indat = yaml.load(fileobject)
        except Exception as ex:
            warnings.showwarning(
                    'InputError: {} - STOP'.format(str(ex)),
                    UserWarning,
                    'lattice_generator.py',
                    'factory()',
                    )
            sys.exit(1)
    fileobject.close()
    ky = indat.keys()
    for k in ky:
        print()
        print(k)
        klist = indat[k]
        print(klist)
        if not klist: continue
        nlist = flatten(klist)
        if k == 'LATTICE':
            N = nlist[0]
            plist = nlist[1:]
            qlist = plist.copy()
            for i in range(N-1):
                qlist += plist
            nlist=qlist
        print(nlist)
开发者ID:wdklotz,项目名称:simulinac,代码行数:30,代码来源:lattice_generator.py

示例5: __init__

 def __init__(self, pin=None, active_high=True, initial_value=False):
     self._active_high = active_high
     super(OutputDevice, self).__init__(pin)
     self._active_state = GPIO.HIGH if active_high else GPIO.LOW
     self._inactive_state = GPIO.LOW if active_high else GPIO.HIGH
     try:
         # NOTE: catch_warnings isn't thread-safe but hopefully no-one's
         # messing around with GPIO init within background threads...
         with warnings.catch_warnings(record=True) as w:
             # This is horrid, but we can't specify initial=None with setup
             if initial_value is None:
                 GPIO.setup(pin, GPIO.OUT)
             else:
                 GPIO.setup(pin, GPIO.OUT, initial=
                     [self._inactive_state, self._active_state][bool(initial_value)])
             GPIO.setup(pin, GPIO.OUT)
         # The only warning we want to squash is a RuntimeWarning that is
         # thrown when setting pins 2 or 3. Anything else should be replayed
         for warning in w:
             if warning.category != RuntimeWarning or pin not in (2, 3):
                 warnings.showwarning(
                     warning.message, warning.category, warning.filename,
                     warning.lineno, warning.file, warning.line
                 )
     except:
         self.close()
         raise
开发者ID:calufrax,项目名称:python-gpiozero,代码行数:27,代码来源:output_devices.py

示例6: test_warnings

    def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            try:
                warnings.filterwarnings("always", category=UserWarning)
                file = io.StringIO()
                h = logging.StreamHandler(file)
                logger = logging.getLogger("py.warnings")
                logger.addHandler(h)
                warnings.warn("I'm warning you...")
                logger.removeHandler(h)
                s = file.getvalue()
                h.close()
                self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)

                #See if an explicit file uses the original implementation
                file = io.StringIO()
                warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                        file, "Dummy line")
                s = file.getvalue()
                file.close()
                self.assertEqual(s,
                        "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
            finally:
                logging.captureWarnings(False)
开发者ID:henrywoo,项目名称:Python3.1.3-Linux,代码行数:25,代码来源:test_logging.py

示例7: ignore_deprecation_warnings

    def ignore_deprecation_warnings():
        with warnings.catch_warnings(record=True) as warning_list:  # catch all warnings
            yield

        # rethrow all warnings that were not DeprecationWarnings
        for w in warning_list:
            if not issubclass(w.category, DeprecationWarning):
                warnings.showwarning(message=w.message, category=w.category, filename=w.filename, lineno=w.lineno, file=w.file, line=w.line)
开发者ID:100Shapes,项目名称:wagtail,代码行数:8,代码来源:utils.py

示例8: new_func

 def new_func(*args, **kwargs):
     warnings.showwarning(
         "Call to deprecated function {}.".format(func.__name__),
         category=DeprecationWarning,
         filename=func.__code__.co_filename,
         lineno=func.__code__.co_firstlineno + 1
     )
     return func(*args, **kwargs)
开发者ID:3c7,项目名称:PyMISP,代码行数:8,代码来源:__init__.py

示例9: _handle_caught_warnings

def _handle_caught_warnings(caught_warnings, filename):
    logger = logging.getLogger(__name__)
    for warning in caught_warnings:
        if warning.category == PILImage.DecompressionBombWarning:
            logger.info('PILImage reported a possible DecompressionBomb'
                         ' for file {}'.format(filename))
        else:
            warnings.showwarning(warning.message, warning.category,
                                 warning.filename, warning.lineno)
开发者ID:t-animal,项目名称:sigal,代码行数:9,代码来源:image.py

示例10: _read_config

def _read_config(rcfile):
    """Read configuration information from a file"""
    global config
    defaults = {'enable_deprecation_warning': str(True),
                'ncpus': str(multiprocessing.cpu_count()),
                'qindenton_url': 'http://virbo.org/ftp/QinDenton/hour/merged/latest/WGhour-latest.d.zip',
                'omni2_url': 'http://virbo.org/ftp/OMNI/OMNI2/merged/latest/OMNI_OMNI2-latest.cdf.zip',
                'leapsec_url': 'http://maia.usno.navy.mil/ser7/tai-utc.dat',
                'psddata_url': 'http://spacepy.lanl.gov/repository/psd_dat.sqlite',
                'support_notice': str(True),
                'apply_plot_styles': str(True),
                }
    #Functions to cast a config value; if not specified, value is a string
    str2bool = lambda x: x.lower() in ('1', 'yes', 'true', 'on')
    caster = {'enable_deprecation_warning': str2bool,
              'ncpus': int,
              'support_notice': str2bool,
              'apply_plot_styles': str2bool,
              }
    #SafeConfigParser deprecated in 3.2. And this is hideous, but...
    if hasattr(ConfigParser, 'SafeConfigParser'):
        cp_class = ConfigParser.SafeConfigParser
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings(
                'always', 'The SafeConfigParser class has been renamed.*',
                DeprecationWarning,
                '^spacepy$') #configparser lies about source of warnings
            ConfigParser.SafeConfigParser()
        for this_w in w:
            if isinstance(this_w.message, DeprecationWarning):
                cp_class = ConfigParser.ConfigParser
            else:
                warnings.showwarning(this_w.message, this_w.category,
                                     this_w.filename, this_w.lineno,
                                     this_w.file, this_w.line)
    else:
        cp_class = ConfigParser.ConfigParser
    cp = cp_class(defaults)
    try:
        successful = cp.read([rcfile])
    except ConfigParser.Error:
        successful = []
    if successful: #New file structure
        config = dict(cp.items('spacepy'))
    else: #old file structure, wipe it out
        cp = cp_class()
        cp.add_section('spacepy')
        with open(rcfile, 'w') as cf:
            cp.write(cf)
        for k in defaults:
            if not k in config:
                config[k] = defaults[k]
    _write_defaults(rcfile, defaults)
    for k in caster:
        config[k] = caster[k](config[k])
开发者ID:spacepy,项目名称:spacepy,代码行数:55,代码来源:__init__.py

示例11: ready

 def ready(self):
     """ Performs an DB engine check, as we maintain some engine specific queries. """
     if (connection.vendor not in settings.DSMR_SUPPORTED_DB_VENDORS):
         # Temporary for backwards compatibility
         warnings.showwarning(
             _(
                 'Unsupported database engine "{}" active, '
                 'some features might not work properly'.format(connection.vendor)
             ),
             RuntimeWarning, __file__, 0
         )
开发者ID:dennissiemensma,项目名称:dsmr-reader,代码行数:11,代码来源:apps.py

示例12: get_mandatory

def get_mandatory(attributes,key,item):
    try:
        res = attributes[key]
    except KeyError:
        warnings.showwarning(
                'InputError: Mandatory attribute "{}" missing for element "{}" - STOP'.format(key,item),
                UserWarning,
                'lattice_generator.py',
                'get_mandatory()',
                )
        sys.exit(1)
    return res
开发者ID:wdklotz,项目名称:simulinac,代码行数:12,代码来源:lattice_generator.py

示例13: _read_image

def _read_image(file_path):
    with warnings.catch_warnings(record=True) as caught_warnings:
        im = PILImage.open(file_path)

    for warning in caught_warnings:
        if warning.category == PILImage.DecompressionBombWarning:
            logger = logging.getLogger(__name__)
            logger.info('PILImage reported a possible DecompressionBomb'
                        ' for file {}'.format(file_path))
        else:
            warnings.showwarning(warning.message, warning.category,
                                 warning.filename, warning.lineno)
    return im
开发者ID:saimn,项目名称:sigal,代码行数:13,代码来源:image.py

示例14: __init__

 def __init__(self, pin=None):
     super(OutputDevice, self).__init__(pin)
     # NOTE: catch_warnings isn't thread-safe but hopefully no-one's messing
     # around with GPIO init within background threads...
     with warnings.catch_warnings(record=True) as w:
         GPIO.setup(pin, GPIO.OUT)
     # The only warning we want to squash is a RuntimeWarning that is thrown
     # when setting pins 2 or 3. Anything else should be replayed
     for warning in w:
         if warning.category != RuntimeWarning or pin not in (2, 3):
             warnings.showwarning(
                 warning.message, warning.category, warning.filename,
                 warning.lineno, warning.file, warning.line
             )
开发者ID:TheRinger,项目名称:python-gpiozero,代码行数:14,代码来源:output_devices.py

示例15: twiss_envelopes

 def twiss_envelopes(self,steps=1):
     """
     Calulate envelopes from initial twiss-vector with beta-matrices
     """
     twfun = Functions(('s','bx','ax','gx','by','ay','gy','bz','az','gz'))
     bx,ax,gx,epsx = PARAMS['twiss_x_i']()
     by,ay,gy,epsy = PARAMS['twiss_y_i']()
     bz,az,gz,epsz = PARAMS['twiss_z_i']()
     twv0 = NP.array([bx,ax,gx,by,ay,gy,bz,az,gz])   # initial
     B_matrix = NP.eye(9)                            # cumulated beta-matrix
     for node in iter(self):
         slices = node.make_slices(anz = steps)
         means = []
         s,sm,sf = node.position
         for slice in slices:
             beta_matrix = slice.beta_matrix()
             B_matrix    = NP.dot(beta_matrix,B_matrix)
             twv         = NP.dot(B_matrix,twv0)     # track twiss-vector
             s          += slice.length
             twfun.append(s,tuple(twv))
             bx    = twv[Ktw.bx]; ax = twv[Ktw.ax]; gx = twv[Ktw.gx]
             by    = twv[Ktw.by]; ay = twv[Ktw.ay]; gy = twv[Ktw.gy]
             sigxy = (*sigmas(ax,bx,epsx),*sigmas(ay,by,epsy))
             means.append(sigxy)
             
         # means = NP.array(means)
         means = NP.mean(means,axis=0)
         # each node has its tuple of average sigmas
         node['sigxy'] = tuple(means)
         # aperture check
         if FLAGS['useaper']:
             nbsigma = PARAMS['nbsigma']
             if node.aperture != None:
                 aperture = node.aperture
                 sigx, sigxp, sigy, sigyp = node['sigxy']
                 if(aperture < nbsigma*sigx or aperture < nbsigma*sigy):
                     warnings.showwarning(
                         '{} sigma aperture hit @ s={:.1f} [m]'.format(nbsigma,sm),
                         UserWarning,'lattice.py',
                         'twiss_functions()')
     return twfun
开发者ID:wdklotz,项目名称:simulinac,代码行数:41,代码来源:lattice.py


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