首页 > 解决方案 > 在 RHEL 环境中与 os.path.join 连接的路径使用两个不同的分隔符

问题描述

我有一些代码需要跨平台工作并调用 conda.exe 的子进程。在调用子进程之前,我使用以下代码创建了 conda.exe 的路径(此路径随后用于在子进程中调用 conda.exe):

install_dir = os.path.normpath(arcpy.GetInstallInfo()["InstallDir"])
conda = os.path.join(install_dir,
                             "bin",
                             "Python",
                             "Scripts",
                             "conda.exe")

这在 Windows 和 Ubuntu 上工作得非常好,但在 RHEL 上,返回的路径使用两个不同的分隔符,例如下面的示例(省略号不是路径的一部分):

z:\\...\\arcgis\\server\\framework\\runtime\\arcgis\\/bin/Python/Scripts/conda.exe

不用说,当我尝试在子进程中调用 conda 时,我收到“没有这样的文件或目录”错误。

知道为什么在 RHEL 中运行时使用两个不同的分隔符将路径放在一起吗?到目前为止,我还没有想出一个可行的解决方案,感谢您为我指明正确方向的任何帮助!

标签: pythonpathrhel

解决方案


您可以切换到使用pathlib作为面向对象的文件系统方法,或者使用os.sep构建字符串以避免跨平台差异问题。

使用路径库:

>>> from pathlib import Path
>>> pro_install_dir = Path("z:\\...\\arcgis\\server\\framework\\runtime\\arcgis\\")
>>> conda = pro_install_dir / "bin" / "Python" / "Scripts"/ "conda.exe"
>>> conda
WindowsPath('z:/.../arcgis/server/framework/runtime/arcgis/bin/Python/Scripts/conda.exe')

推荐阅读