我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.normcase()。
def should_debug_code(code): if not code or not code.co_filename: return False filename = path.normcase(code.co_filename) if not DEBUG_STDLIB: for prefix in PREFIXES: if prefix != '' and filename.startswith(prefix): return False for dont_debug_file in DONT_DEBUG: if is_same_py_file(filename, dont_debug_file): return False if is_file_in_zip(filename): # file in inside an egg or zip, so we can't debug it return False return True
def breakpoint_path_match(vs_path, local_path): vs_path_norm = path.normcase(vs_path) local_path_norm = path.normcase(local_path) if local_path_to_vs_path.get(local_path_norm) == vs_path_norm: return True # Walk the local filesystem from local_path up, matching agains win_path component by component, # and stop when we no longer see an __init__.py. This should give a reasonably close approximation # of matching the package name. while True: local_path, local_name = path.split(local_path) vs_path, vs_name = ntpath.split(vs_path) # Match the last component in the path. If one or both components are unavailable, then # we have reached the root on the corresponding path without successfully matching. if not local_name or not vs_name or path.normcase(local_name) != path.normcase(vs_name): return False # If we have an __init__.py, this module was inside the package, and we still need to match # thatpackage, so walk up one level and keep matching. Otherwise, we've walked as far as we # needed to, and matched all names on our way, so this is a match. if not path.exists(path.join(local_path, '__init__.py')): break local_path_to_vs_path[local_path_norm] = vs_path_norm return True
def should_block_on_frame(self, frame): if not should_debug_code(frame.f_code): return False # It is still possible that we're somewhere in standard library code, but that code was invoked by our # internal debugger machinery (e.g. socket.sendall or text encoding while tee'ing print output to VS). # We don't want to block on any of that, either, so walk the stack and see if we hit debugger frames # at some point below the non-debugger ones. while frame is not None: # There is usually going to be a debugger frame at the very bottom of the stack - the one that # invoked user code on this thread when starting debugging. If we reached that, then everything # above is user code, so we know that we do want to block here. if frame.f_code in DEBUG_ENTRYPOINTS: break # Otherwise, check if it's some other debugger code. filename = path.normcase(frame.f_code.co_filename) is_debugger_frame = False for debugger_file in DONT_DEBUG: if is_same_py_file(filename, debugger_file): # If it is, then the frames above it on the stack that we have just walked through # were for debugger internal purposes, and we do not want to block here. return False frame = frame.f_back return True
def print_exception(exc_type, exc_value, exc_tb): # remove debugger frames from the top and bottom of the traceback tb = traceback.extract_tb(exc_tb) for i in [0, -1]: while tb: frame_file = path.normcase(tb[i][0]) if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG): break del tb[i] # print the traceback if tb: print('Traceback (most recent call last):') for out in traceback.format_list(tb): sys.stderr.write(out) # print the exception for out in traceback.format_exception_only(exc_type, exc_value): sys.stdout.write(out)
def is_subdir(path, directory): """ Returns true if *path* in a subdirectory of *directory*. Both paths must be absolute. :arg path: An absolute path. :type path: string or bytes """ from os.path import normpath, normcase, sep path = normpath(normcase(path)) directory = normpath(normcase(directory)) if len(path) > len(directory): sep = sep.encode('ascii') if isinstance(directory, bytes) else sep if path.startswith(directory.rstrip(sep) + sep): return True return False
def test_mismatched_ns(self): # mismatch includes a package that doesn't actually have the # directory created d_egg_root = join(mkdtemp(self), 'dummyns') make_dummy_dist(self, (( 'namespace_packages.txt', 'not_ns\n', ), ( 'entry_points.txt', '[dummyns]\n' 'dummyns = dummyns:attr\n', ),), 'dummyns', '1.0', working_dir=d_egg_root) working_set = pkg_resources.WorkingSet([ d_egg_root, self.ds_egg_root, ]) stub_item_attr_value(self, pkg_resources, 'working_set', working_set) dummyns_ep = next(working_set.iter_entry_points('dummyns')) p = indexer.resource_filename_mod_entry_point('dummyns', dummyns_ep) self.assertEqual(normcase(p), normcase(self.dummyns_path))
def test_not_namespace(self): d_egg_root = join(mkdtemp(self), 'dummyns') make_dummy_dist(self, (( 'entry_points.txt', '[dummyns]\n' 'dummyns = dummyns:attr\n', ),), 'dummyns', '1.0', working_dir=d_egg_root) working_set = pkg_resources.WorkingSet([ d_egg_root, self.ds_egg_root, ]) stub_item_attr_value(self, pkg_resources, 'working_set', working_set) moddir = join(d_egg_root, 'dummyns') os.makedirs(moddir) dummyns_ep = next(working_set.iter_entry_points('dummyns')) p = indexer.resource_filename_mod_entry_point('dummyns', dummyns_ep) self.assertEqual(normcase(p), normcase(self.dummyns_path))
def test_set_env_path_with_node_path_success(self): tmpdir, bin_dir, mgr_bin = self.fake_mgr_bin() other_dir = mkdtemp(self) # default constructor driver = cli.PackageManagerDriver( pkg_manager_bin='mgr', working_dir=other_dir) # the which_with_node_modules will not work immeidately in this # case self.assertIsNone(driver.which_with_node_modules()) self.assertIsNone(driver.env_path) # using NODE_PATH set to a valid node_modules driver.node_path = join(tmpdir, 'node_modules') # this should work now. self.assertEqual( normcase(driver.which_with_node_modules()), normcase(mgr_bin)) self.assertTrue(driver._set_env_path_with_node_modules()) self.assertEqual(driver.env_path, bin_dir) # should still result in the same thing. self.assertTrue(driver._set_env_path_with_node_modules()) self.assertEqual(driver.env_path, bin_dir)
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ # We need to use normcase to ensure we don't false-negative on case # insensitive operating systems (like Windows). base = force_unicode(base) paths = [force_unicode(p) for p in paths] final_path = normcase(abspathu(join(base, *paths))) base_path = normcase(abspathu(base)) base_path_len = len(base_path) # Ensure final_path starts with base_path and that the next character after # the final path is os.sep (or nothing, in which case final_path must be # equal to base_path). if not final_path.startswith(base_path) or final_path[base_path_len:base_path_len+1] not in ('', sep): raise ValueError('the joined path is located outside of the base path' ' component') return final_path
def getIconPathFromAAueue(self, item): printDBG("getIconPathFromAAueue item[%s]" % item) hashAlg = MD5() name = hashAlg(item) filename = hexlify(name) + '.jpg' self.lockAA.acquire() file_path = self.queueAA.get(filename, '') if file_path != '': try: if os_path.normcase(self.currDownloadDir+'/') != os_path.normcase(file_path+'/'): file_path = os_path.normcase(file_path + '/' + filename) os_rename(file_path, os_path.normcase(self.currDownloadDir + '/' + filename)) self.queueAA[filename] = os_path.normcase(self.currDownloadDir + '/' ) file_path = os_path.normcase(self.currDownloadDir + '/' + filename) else: file_path = os_path.normcase(file_path + '/' + filename) except Exception: printExc() self.lockAA.release() printDBG("getIconPathFromAAueue A file_path[%s]" % file_path) return file_path
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = force_text(base) paths = [force_text(p) for p in paths] final_path = abspathu(join(base, *paths)) base_path = abspathu(base) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows), # further, one of the following conditions must be true: # a) The next character is the path separator (to prevent conditions like # safe_join("/dir", "/../d")) # b) The final path must be the same as the base path. # c) The base path must be the most root path (meaning either "/" or "C:\\") if (not normcase(final_path).startswith(normcase(base_path + sep)) and normcase(final_path) != normcase(base_path) and dirname(normcase(base_path)) != normcase(base_path)): raise SuspiciousFileOperation( 'The joined path ({}) is located outside of the base path ' 'component ({})'.format(final_path, base_path)) return final_path
def should_send_frame(frame): return (frame is not None and frame.f_code not in DEBUG_ENTRYPOINTS and path.normcase(frame.f_code.co_filename) not in DONT_DEBUG)
def connect_to_repl_backend_using_socket(self, sock): DONT_DEBUG.append(path.normcase(_vspr.__file__)) self.repl_backend = _vspr.DebugReplBackend(self) self.repl_backend.connect_from_debugger_using_socket(sock) self.repl_backend.execution_loop()
def init_debugger(self): from os import path sys.path.append(path.dirname(__file__)) import visualstudio_py_debugger visualstudio_py_debugger.DONT_DEBUG.append(path.normcase(__file__)) new_thread = visualstudio_py_debugger.new_thread() sys.settrace(new_thread.trace_func) visualstudio_py_debugger.intercept_threads(True)
def connect_to_repl_backend(self, port_num): DONT_DEBUG.append(path.normcase(_vspr.__file__)) self.repl_backend = _vspr.DebugReplBackend(self) self.repl_backend.connect_from_debugger(port_num) self.repl_backend.execution_loop()
def handle_exception(exc_type, exc_value, exc_tb): # Specifies list of files not to display in stack trace. do_not_debug = [__file__, _vspu.__file__] if sys.version_info >= (3, 3): do_not_debug.append('<frozen importlib._bootstrap>') if sys.version_info >= (3, 5): do_not_debug.append('<frozen importlib._bootstrap_external>') # Remove debugger frames from the top and bottom of the traceback. tb = traceback.extract_tb(exc_tb) for i in [0, -1]: while tb: frame_file = path.normcase(tb[i][0]) if not any(is_same_py_file(frame_file, f) for f in do_not_debug): break del tb[i] # Print the traceback. if tb: sys.stderr.write('Traceback (most recent call last):') for out in traceback.format_list(tb): sys.stderr.write(out) sys.stderr.flush() # Print the exception. for out in traceback.format_exception_only(exc_type, exc_value): sys.stderr.write(out) sys.stderr.flush()
def is_subdir(path, directory): """ Returns true if *path* in a subdirectory of *directory*. """ import os from os.path import normpath, normcase, sep path = normpath(normcase(path)) directory = normpath(normcase(directory)) if len(path) > len(directory): sep = sep.encode('ascii') if isinstance(directory, bytes) else sep if path.startswith(directory.rstrip(sep) + sep): return True return False
def test_get_exec_binary_with_binary(self): tmpdir = mkdtemp(self) prog = create_fake_bin(tmpdir, 'prog') self.assertEqual(normcase(prog), normcase(base._get_exec_binary( 'prog', {'env': {'PATH': tmpdir}})))
def test_not_defined(self): working_set = pkg_resources.WorkingSet([ self.ds_egg_root, ]) stub_item_attr_value(self, pkg_resources, 'working_set', working_set) p = indexer.resource_filename_mod_entry_point('dummyns', None) self.assertEqual(normcase(p), normcase(self.dummyns_path))
def test_mismatched(self): # mismatch includes a package that doesn't actually have the # directory created d_egg_root = join(mkdtemp(self), 'dummyns') make_dummy_dist(self, (( 'namespace_packages.txt', 'dummyns\n', ), ( 'entry_points.txt', '[dummyns]\n' 'dummyns = dummyns:attr\n', ),), 'dummyns', '1.0', working_dir=d_egg_root) working_set = pkg_resources.WorkingSet([ d_egg_root, self.ds_egg_root, ]) stub_item_attr_value(self, pkg_resources, 'working_set', working_set) dummyns_ep = next(working_set.iter_entry_points('dummyns')) with pretty_logging(stream=StringIO()) as fd: p = indexer.resource_filename_mod_entry_point( 'dummyns', dummyns_ep) self.assertIn( "'dummyns' resolved by entry_point 'dummyns = dummyns:attr' leads " "to no path", fd.getvalue() ) self.assertEqual(normcase(p), normcase(self.dummyns_path))
def test_standard_not_stubbed(self): d_egg_root = join(mkdtemp(self), 'dummyns') make_dummy_dist(self, (( 'namespace_packages.txt', 'dummyns\n', ), ( 'entry_points.txt', '[dummyns]\n' 'dummyns = dummyns:attr\n', ),), 'dummyns', '1.0', working_dir=d_egg_root) working_set = pkg_resources.WorkingSet([ d_egg_root, self.ds_egg_root, ]) # not stubbing will result in the loader failing to actuall work moddir = join(d_egg_root, 'dummyns') os.makedirs(moddir) # make this also a proper thing with open(join(moddir, '__init__.py'), 'w') as fd: fd.write('') dummyns_ep = next(working_set.iter_entry_points('dummyns')) with pretty_logging(stream=StringIO()) as fd: p = indexer.resource_filename_mod_entry_point( 'dummyns', dummyns_ep) self.assertIn( "resolved by entry_point 'dummyns = dummyns:attr' resulted in " "unexpected error", fd.getvalue() ) self.assertEqual(normcase(p), normcase(self.dummyns_path))
def test_which_is_set(self): stub_os_environ(self) tmpdir = mkdtemp(self) mgr_bin = self.create_fake_mgr_bin(tmpdir) driver = cli.PackageManagerDriver(pkg_manager_bin='mgr') driver.env_path = tmpdir self.assertEqual(normcase(driver.which()), normcase(mgr_bin)) driver.env_path = None self.assertIsNone(driver.which())
def test_which_is_set_env_path(self): stub_os_environ(self) tmpdir = mkdtemp(self) mgr_bin = self.create_fake_mgr_bin(tmpdir) driver = cli.PackageManagerDriver(pkg_manager_bin='mgr') # With both env_path attr and environ PATH set os.environ['PATH'] = driver.env_path = tmpdir self.assertEqual(normcase(driver.which()), normcase(mgr_bin)) # the autodetection should still work through ENV_PATH driver.env_path = None self.assertEqual(normcase(driver.which()), normcase(mgr_bin))
def test_set_env_path_with_node_modules_success(self): tmpdir, bin_dir, mgr_bin = self.fake_mgr_bin() # constructor with an explicit working directory. driver = cli.PackageManagerDriver( pkg_manager_bin='mgr', working_dir=tmpdir) self.assertIsNone(driver.env_path) # the which_with_node_modules should work immediately self.assertEqual( normcase(driver.which_with_node_modules()), normcase(mgr_bin)) self.assertTrue(driver._set_env_path_with_node_modules()) self.assertEqual(driver.env_path, bin_dir) # should still result in the same thing. self.assertTrue(driver._set_env_path_with_node_modules()) self.assertEqual(driver.env_path, bin_dir)