我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.warnoptions()。
def configure_logging(logging_config, logging_settings): if not sys.warnoptions: # Route warnings through python logging logging.captureWarnings(True) # RemovedInNextVersionWarning is a subclass of DeprecationWarning which # is hidden by default, hence we force the "default" behavior warnings.simplefilter("default", RemovedInNextVersionWarning) if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) logging.config.dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings)
def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'hash_randomization': 'R', 'py3k_warning': '3', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
def testWarning(self): """Test the warnings argument""" # see #10535 class FakeTP(unittest.TestProgram): def parseArgs(self, *args, **kw): pass def runTests(self, *args, **kw): pass warnoptions = sys.warnoptions[:] try: sys.warnoptions[:] = [] # no warn options, no arg -> default self.assertEqual(FakeTP().warnings, 'default') # no warn options, w/ arg -> arg value self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore') sys.warnoptions[:] = ['somevalue'] # warn options, no arg -> None # warn options, w/ arg -> arg value self.assertEqual(FakeTP().warnings, None) self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore') finally: sys.warnoptions[:] = warnoptions
def test_option_w_ignore(pyi_builder, monkeypatch): "Test to ensure that option W can be set." def MyEXE(*args, **kwargs): args = list(args) args.append([('W ignore', '', 'OPTION')]) return EXE(*args, **kwargs) import PyInstaller EXE = PyInstaller.building.build_main.EXE monkeypatch.setattr('PyInstaller.building.build_main.EXE', MyEXE) pyi_builder.test_source( """ import sys assert 'ignore' in sys.warnoptions """)
def build_subprocess_arglist(self): assert (self.port!=0), ( "Socket should have been assigned a port number.") w = ['-W' + s for s in sys.warnoptions] if 1/2 > 0: # account for new division w.append('-Qnew') # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') if __name__ == 'idlelib.PyShell': command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,) else: command = "__import__('run').main(%r)" % (del_exitf,) if sys.platform[:3] == 'win' and ' ' in sys.executable: # handle embedded space in path by quoting the argument decorated_exec = '"%s"' % sys.executable else: decorated_exec = sys.executable return [decorated_exec] + w + ["-c", command, str(self.port)]
def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'hash_randomization': 'R', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
def configure_logging(logging_config, logging_settings): if not sys.warnoptions: # Route warnings through python logging logging.captureWarnings(True) # RemovedInNextVersionWarning is a subclass of DeprecationWarning which # is hidden by default, hence we force the "default" behavior warnings.simplefilter("default", RemovedInNextVersionWarning) if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings)
def restart(self): self.stop(False) args = ([sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv) if sys.platform == "win32": args = ['"%s"' % arg for arg in args] os.execv(sys.executable, args)
def restart_with_reloader(): while True: args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv if sys.platform == "win32": args = ['"%s"' % arg for arg in args] new_environ = os.environ.copy() new_environ["RUN_MAIN"] = 'true' exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) if exit_code != 3: return exit_code
def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None): if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: self.module = getattr(self.module, part) else: self.module = module if argv is None: argv = sys.argv self.exit = exit self.failfast = failfast self.catchbreak = catchbreak self.verbosity = verbosity self.buffer = buffer if warnings is None and not sys.warnoptions: # even if DreprecationWarnings are ignored by default # print them anyway unless other warnings settings are # specified by the warnings arg or the -W python flag self.warnings = 'default' else: # here self.warnings is set either to the value passed # to the warnings args or to None. # If the user didn't pass a value self.warnings will # be None. This means that the behavior is unchanged # and depends on the values passed to -W. self.warnings = warnings self.defaultTest = defaultTest self.testRunner = testRunner self.testLoader = testLoader self.progName = os.path.basename(argv[0]) self.parseArgs(argv) self.runTests()
def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loaderzippy.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None): if isinstance(module, str): self.module = __import__(module) # for part in module.split('.')[1:]: # self.module = getattr(self.module, part) else: self.module = module if argv is None: argv = sys.argv self.exit = exit self.failfast = failfast self.catchbreak = catchbreak self.verbosity = verbosity self.buffer = buffer if warnings is None and not sys.warnoptions: # even if DreprecationWarnings are ignored by default # print them anyway unless other warnings settings are # specified by the warnings arg or the -W python flag self.warnings = 'default' else: # here self.warnings is set either to the value passed # to the warnings args or to None. # If the user didn't pass a value self.warnings will # be None. This means that the behavior is unchanged # and depends on the values passed to -W. self.warnings = warnings self.defaultTest = defaultTest self.testRunner = testRunner self.testLoader = testLoader #self.progName = os.path.basename(argv[0]) self.parseArgs(argv) self.runTests()
def test_single_warning(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], b"['ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0)
def test_comma_separated_warnings(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning," "ignore::UnicodeWarning") p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") self.assertEqual(p.wait(), 0)
def test_nonascii(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore:DeprecaciónWarning" newenv["PYTHONIOENCODING"] = "utf-8" p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore:DeprecaciónWarning']".encode('utf-8')) self.assertEqual(p.wait(), 0)
def get_sys_warnoptions(self): return id(sys.warnoptions), sys.warnoptions, sys.warnoptions[:]
def restore_sys_warnoptions(self, saved_options): sys.warnoptions = saved_options[1] sys.warnoptions[:] = saved_options[2] # Controlling dangling references to Thread objects can make it easier # to track reference leaks.
def build_subprocess_arglist(self): assert (self.port!=0), ( "Socket should have been assigned a port number.") w = ['-W' + s for s in sys.warnoptions] # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') if __name__ == 'idlelib.PyShell': command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,) else: command = "__import__('run').main(%r)" % (del_exitf,) return [sys.executable] + w + ["-c", command, str(self.port)]
def test_option_w_unset(pyi_builder): "Test to ensure that option W is not set by default." pyi_builder.test_source( """ import sys assert 'ignore' not in sys.warnoptions """)
def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'py3k_warning': '3', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) if getattr(sys.flags, 'hash_randomization') != 0: args.append('-R') for opt in sys.warnoptions: args.append('-W' + opt) return args
def test_single_warning(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0)
def test_comma_separated_warnings(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning," "ignore::UnicodeWarning") p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") self.assertEqual(p.wait(), 0)
def test_envvar_and_command_line(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning", "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0)
def _args_from_interpreter_flags(): """Tries to reconstruct original interpreter args from sys.flags for Python 2.6 Backported from Python 3.5. Aims to return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'hash_randomization': 'R', 'py3k_warning': '3', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: if flag == 'hash_randomization': v = 1 # Handle specification of an exact seed args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args # html module come in 3.2 version