語法:os.path.realpath(path) 參數:path:類路徑表示文件系統路徑的對象。類路徑對像是表示路徑的字符串或字節對象。返回類型:此方法返回代表規範路徑的字符串值。
創建軟鏈接或符號鏈接
在 Unix 或 Linux 上,可以使用 ln 命令創建軟鏈接或符號鏈接。以下是在命令行上創建符號鏈接的語法:$ ln -s {source-filename} {symbolic-filename}
Example 1
def realpath(self, spec, key): """ 解析並更新規範中的路徑鍵realpath,基於工作目錄。""" if key not in spec: # do nothing for現在返回如果不是規範 [key]: logger.warning("cannot resolve realpath of `%s ` 因為它沒有定義", key) return check = realpath(join(spec.get( WORKING_DIR, ``), spec[key])) if check != spec[key]: spec[key] = check logger.warning("realpath of `%s` 解析為 `%s`,規範已更新", key, check ) return che ck # 設置相關方法
示例2
def get_rp_stripper(strip_path): """ return function to strip ``realpath`` of `strip_path` from string 參數 ---------- strip_path: str 路徑從字符串開頭剝離。由 ``realpath(strip_path) + os.path.sep` 處理到 ``strip_prefix`` `。 Returns ----- stripper: func 函數使得 ``stripper(a_string)`` 將從 ``a_string`` 中剝離 ``strip_prefix`` 如果存在,否則傳遞 ``a_string`` 未修改的 """ 返回get_prefix_stripper(realpath(strip_path) + os.path.sep)
示例3
def test_toolchain_standard_not_implemented(self): spec = Spec() with self.assertRaises(NotImplementedError): self.toolchain(spec) with self.assertRaises(NotImplementedError): self.toolchain.assemble(spec) with self.assertRaises(NotImplementedError): self.toolchain.link(spec) # 檢查 build_dir 是否在基於 tempfile 的規範中設置 self.assertTrue(spec[`build_dir`].startswith( realpath(tempfile.gettempdir()))) # 也被正確刪除了 self.assertFalse(exists(spec[`build_dir`] ))
示例4
def find_system_jdks(): """ 返回一組有效的JD K 目錄通過搜索標準位置。 """ bases = [`/Library/Java/JavaVirtualMachines`, `/usr/lib/jvm`, `/usr/java`, `/usr/jdk/instances`, r`C:Program FilesJava`] jdks = set() for base in bases: if isdir(base): for n in os.listdir(base): jdk = join(base, n) mac_jdk = join(jdk, `Contents`, `Home`) if isdir(mac_jdk ): jdk = mac_jdk if is_valid_jdk(jdk): jdks.add(realpath(jdk)) 返回jdks
示例 5
def _expand_dirs_to_files(files_or_dirs, recursive=False): files = [] files_or_dirs = _ensure_list(files_or_dirs) for file_or_dirs in files_or_dirs: file_or_dir = op.realpath(file_or_dir) if op.isdir(file_or_dir): # 跳過以 `.` 開頭的目錄名if _to_skip(file_or_dir): continue # 遞歸訪問目錄並添加文件 if recursive: files.extend(_expand_dirs_to_files([op.join(file_or_dir, file) for file in os.listdir(file_or_dir)], recursive=recursive) ) else: files.extend([op.join(file_or_dir, file) for file in os.listdir(file_or_dir)]) elif `*` in file_or_dir: files.extend(glob.glob(file_or_dir)) else: files.append (file_or_dir) 返回文件
示例 6
def getSubdirs(path, baseNamesOnly=True, excludePythonModulesDirs=True): """提供給定路徑的子目錄列表"" " subdirs = [] try: path = realpath(path) + sep for item in os.listdir (路徑):候選人=路徑+項目如果isdir(候選人):如果排除PythonModulesDirs:modFile =候選人+ sep +“__init__.py”如果存在(modFile):繼續如果baseNamesOnly:subdirs.append(item)否則:subdirs.append (候選)除了:通過返回子目錄
示例7
def get_dataset(num_points): name = `ModelNet10` path = osp.join(osp.dirname(osp.realpath(__file__)), `..`, `data`, name) pre_transform = T.NormalizeScale() transform = T.SamplePoints(num_points) train_dataset = ModelNet( path, name=`10`, train=True, transform=transform, pre_transform=pre_transform) test_dataset = ModelNet(path, name=`10`, train=False, transform=transform, pre_transform=pre_transform) return train_dataset, test_dataset
示例8
def getParameters(self): """提供帶有搜索參數的字典""" parameters = {`term`: self.findCombo.currentText(), `case`: self.caseCheckBox.isChecked( ), `whole`: self.wordCheckBox.isChecked(), `regexp`: self.regexpCheckBox.isChecked()} if self.projectRButton.isChecked(): parameters[`in-project`] = True parameters[`in- opens`] = False 參數[`in-dir`] = `` elif self.openFilesRButton.isChecked(): 參數[`in-project`] = F alse parameters[`in-opened`] = True parameters[`in-dir`] = `` else: parameters[`in-project`] = False parameters[`in-opened`] = False parameters[`in-dir `] = realpath(self.dirEditCombo.currentText().strip()) 參數[`文件-filter`] = self.filterCombo.currentText().strip() 返回參數
示例9
def _check_if_pyc(fname): """如果擴展名是.則返回True pyc,如果 .py 則為 False,否則為 None""" from imp import find_module from os.path import realpath, dirname, basename, splitext # 規範化 find_module() 的文件路徑 filepath = realpath(fname) dirpath = dirname(filepath) module_name = splitext(basename(filepath))[0] # 驗證並獲取 try: fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath]) except ImportError : raise IOError("找不到配置文件。 " "路徑可能不正確!: {0}".format(filepath)) return pytype, fileobj, fullpath
示例 10
def get_planetoid_dataset(name, normalize_features=False, transform=無):path = osp.join(osp.dirname(osp.realpath(__file__)), `..`, `data`, name) dataset = Planetoid(path, name) 如果 transform 不是 None 並且 normalize_features: dataset.transform = T.Compose([T.NormalizeFeatures(), transform]) elif normalize_features: dataset. transform = T.NormalizeFeatures() elif 轉換不是 None:dataset.transform = transform return dataset
示例 11
def _setup_logger(cls, log_file=None): formatter = logging。格式化程序( fmt="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) screen_handler = logging.StreamHandler( stream=sys.stdout) screen_handler.setFormatter(formatter) logger = logging.getLogger(cls.__name__) logger.setLevel(logging.DEBUG) logger.addHandler(screen_handl er) 如果 log_file: file_handler = logging.FileHandler(realpath(log_file), mode="w" ) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger
示例 12
def bro_server(bro_file, interface="eth0", bro_path="/usr/local/ bro/bin/bro"): u""" Ë∑ëbroÊúçÂä°ËøõÁ®ã """ # Ëé∑ÂèñÁªùÂØπË∑ØÂæÑ bro_file = path.realpath(bro_file) http_file = "/usr/local/bro/share/bro/base/protocols/http/main.bro" bro_scripts = ` `.join([bro_file, http_file ]) cmd = "sudo {bro_path} -C -b -i {interface} {bro_scripts}" cmd = cmd.format(bro_path=bro_path, interface=interface, bro_scripts=bro_scripts) msg = "cmd 是:%s" % cmd logging.info(msg) # 更改密碼為 /tmp tmp_dir = path.join(path.dirname(path.realpath(__file__)), `../../tmp/`) chdir(tmp_dir) 結果 = r un(cmd) logging.info(result.__dict__)
示例 13
def ProcessFlags(env, flags): for f in flags: if f: env.MergeFlags(str( f)) # 修復 i, p in enumerate(env.get("CPPPATH", [])): if isdir(p): env[`CPPPATH`][i] = realpath(p) # 取消任何先前的名稱定義,無論是內置的還是 # 提供 -D 選項 // 問題 #191 undefines = [u for u in env.get("CCFLAGS", []) if u.startswith("-U")] if undefines: for undef in undefines: env[`CCFLAGS`].remove(undef) env. Append(_CPPDEFFLAGS=" %s" % " ".join(undefines))
示例 14
def _get_settings_helper(self): main_dir = path.dirname(path.realpath(__file__)) main_dir = path.realpath(path.join(main_dir, `..`, `..`)) default_filepath = path.join(main_dir, `default_settings. yml`) user_filepath = path.join(main_dir, `settings.yml`) args = self._get_args() if args.settings_path: user_filepath = args.settings_path # 打開默認文件並獲取版本信息 open(default_filepath) as default_filestream : default_filesettings = yaml.load(default_filestream) # FIXME: not used current_version = default_filesettings[`version`].split(`.`) # flake8: noqa if path.exists(user_filepath): filepath = user_filepath else: filepath = default_filepath with open(filepath) as setting_file: self.settings = yaml.load(setting_file, _OrderedLoader) return SpecialDict(**self.settings)
示例 15
def resolve_rpath(lib_path, rpaths ): """ 返回 `lib_path` 並解析其 `@rpath` 如果 `lib_path` 沒有 `@rpath` 則按原樣返回。如果 `lib_path` 有 `@rpath` 則返回找到的第一個 `rpaths`/`lib_path` 組合。如果在“rpaths”中找不到該庫,則會打印詳細的警告並按原樣返回“lib_path”。參數 ---------- lib_path: str 庫文件的路徑,可能以“@rpath”開頭,也可能不以“@rpath”開頭。 rpaths: sequence of str 搜索路徑的序列,通常通過調用“get_rpaths”獲得。返回 ------- lib_path: str 帶有解析庫 realpath 的 str。 """ 如果不是 lib_path.startswith(`@rpath/`): return lib_path lib_rpath = lib_path.split(`/`, 1)[1] for rpath in rpaths: rpath_lib = realpath(pjoin(rpath, lib_rpath)) if os.path.exists(rpath_lib): return rpath_lib warnings.warn("找不到{ 0} 路徑:{1}".format( lib_path, ` `.join(realpath( path) for path in rpaths), ) ) return lib_path
Example 16
def wheel_libs(wheel_fname, filt_func=None): """ 返回用 Python 輪子分析庫依賴使用此例程轉儲依賴關係樹。參數 ---------- wheel_fname: str 輪子文件名 filt_func: 無或可調用,可選 如果沒有,檢查所有文件的庫依賴關係。如果可調用,則接受文件名作為參數,如果我們應該檢查文件,則返回 True,否則返回 False。返回----- lib_dict:帶有(鍵,值)對(``libpath``,``dependings_dict``)的dict字典。 ``libpath`` 是所依賴的庫,如果在輪樹中,則相對於輪根路徑。 ``dependings_dict`` 是 (``depending_lib_path``, ``install_name``) 的 (key, value)。同樣,“depending_lib_path”是相對於輪根路徑的庫,如果在輪樹中。""" with TemporaryDirectory() as tmpdir: zip2dir(wheel_fname, tmpdir) lib_dict = tree_libs(tmpdir, filt_func) return stripped_lib_dict(lib_dict, realpath(tmpdir) + os.path.sep)
示例 17
def main(): parser = OptionParser( usage="%s WHEEL_OR_PATH_TO_ANALYZE " % sys.argv[0] + __doc__, version="%prog " + __version__) parser.add_options([ Option("-a", "--all", action="store_true", help="顯示所有依賴項, 包括系統庫"), Option("-d", "--depending", action="store_true", help="顯示依賴的庫")]) (opts, paths) = parser.parse_args() if len(paths) < 1: parser.print_help() sys.exit(1) multi = len(paths) > 1 for path in paths: if multi: print(path + `:`) indent = ` ` else: indent = `` if isdir(path): lib_dict = tree_libs(path) lib_dict = stripped_lib_dict(lib_dict, realpath (getcwd()) + psep) e lse: lib_dict = wheel_libs(path) keys = sorted(lib_dict) if not opts.all: keys = [key for key in keys if filter_system_libs(key)] if not opts.depending: if len(keys): print(indent + (` ` + indent).join(keys)) continue i2 = indent + ` ` for key in keys: print(indent + key + `:`) libs = lib_dict[key] if len(libs): print(i2 + (` ` + i2).join(libs))
示例 18
def test_given_directory(): # 測試 InGivenDirectory cwd = getcwd() with InGivenDirectory() as tmpdir: assert_equal( tmpdir, abspath(cwd)) assert_equal(tmpdir, abspath(getcwd())) 與 InGivenDirectory(MY_DIR) 作為 tmpdir: assert_equal(tmpdir, MY_DIR) assert_equal(realpath(MY_DIR), realpath(abspath (getcwd()))) # 我們正在刪除給定目錄!現在檢查不是這樣。 assert_true(isfile(MY_PATH))
Example 19
def decisionClean(workDir, architecture, actuatorCleanup): """ 決定要刪除的內容,而不實際執行: - 查找所有"BUILD" 中的符號鏈接 - 查找 "BUILD" 中的所有目錄 - 如果目錄沒有符號鏈接,則安排刪除目錄 """ symlinksBuild = [os.readlink(x) for x in glob.glob("%s/ BUILD/*-latest*" % workDir)] # $WORK_DIR/TMP 應該總是被清理。這不僅僅發生在 # 在我們打開包裝時空間不足的情況下。 # $WORK_DIR//store 也可以清理,因為 # 我們不需要構建後的實際 tarball。 toDelete = ["%s/TMP" % workDir] 如果積極清理:toDelete += ["%s/TARS/%s/store" % (workDir, architecture), "%s/SOURCES" % (workDir)] allBuildStuff = glob.glob("%s/BUILD/*" % workDir) toDelete += [x for x in allBuildStuff if not path.islink(x) and not basename(x) in symlinksBuild] installGlob ="%s/%s/ */" % (workDir, architecture) installedPackages = set([dirname(x) for x in glob.glob(installGlob)]) symlinksInstall = [] for x in installedPackages: symlinksInstall += [path.realpath(y) for y in glob.glob(x + "/latest*")] toDelete += [x for x如果不是 path.islink(x) 而不是 path,則在 glob.glob(installGlob+ "*") 中。realpath(x) in symlinksInstall] toDelete = [x for x in toDelete if path.exists(x)] return toDelete
示例 20
def _get_script_dir(follow_symlinks: bool = True ) -> Path: # 獲取信任庫的路徑很棘手由於 OS X、Linux 和 Windows 上的細微差別 if getattr(sys, "frozen", False): # py2exe, PyInstaller, cx_Freeze path = Path(sys.executable).absolute() else: path = Path(inspect.getabsfile (_get_script_dir)) if follow_symlinks: path = Path(realpath(path)) return path.parent
存檔
os.path.realpath()
在 Python 中用於通過刪除路徑中找到的任何符號鏈接來獲取指定文件名的規範路徑。
語法: os.path.realpath (路徑)
參數:
路徑:A表示文件系統路徑的類路徑對象。
類路徑對像是表示路徑的 字符串 或 字節 對象。返回類型: 此方法返回代表規範路徑的字符串值。
創建軟鏈接或符號鏈接
在 Unix 或 Linux 上,可以使用 ln 命令創建軟鏈接或符號鏈接。¬†以下是在命令行上創建符號鏈接的語法:
$ ln -s {source-filename} {symbolic-filename}
示例:
示例:
在上面的輸出中, " /home/ihritik/Desktop/file(快捷方式).txt"是符號鏈接。
代碼: 使用 os.path。realpath () 方法獲取規範路徑和解析符號鏈接。
                                |
退出:
/home/ihritik/Documents/file (original) .txt /GeeksForGeeks/sample.py /home/ihritik/file.txt /home/ihritik/Downloads /file.txt