如何在 Cygwin 中使用 Python 有效地将 POSIX 路径转换为 Windows 路径?
How to effectively convert a POSIX path to Windows path with Python in Cygwin?
问题
假设您正在编写一个 Python 脚本,该脚本在 cygwin 上运行并调用需要输入路径的外部 C# 可执行文件。
假设您无法以任何方式更改 C# 可执行文件。
当您将所需路径发送到可执行文件时,它会拒绝所有 cygwin 路径。
因此,如果您将路径 /cygdrive/c/location/of/file.html
作为 POSIX 路径传递,它将失败,因为可执行文件需要 Windows 路径,例如 C:\location\of\file.html
示例:
Message location = os.path.dirname(os.path.realpath(__file__))
os.system('./cSharpScript.exe ' + message_location)
将导致:
File for the content (/cygdrive/c/location/of/file.html) not found.
到目前为止我尝试过的事情:
路径 = /cygdrive/c/location/of/file.html
1) path = PATH.replace('/','\')
结果:File for the content (cygdriveclocationoffile.html) not found.
2) path = os.path.abspath(PATH)
结果:File for the content (/cygdrive/c/location/of/file.html) not found.
os.path.realpath
有相同的结果
到目前为止,我的解决方案可能朝着完全错误的方向发展......你会如何处理它?
cygpath - Convert Unix and Windows format paths, or output system path information
...
-w, --windows print Windows form of NAMEs (C:\WINNT)
示例:
[cfati@cfati-5510-0:/cygdrive/e/Work/Dev/Whosebug/q054237800]> cygpath.exe -w /cygdrive/c/location/of/file.html
C:\location\of\file.html
翻译成Python(这是一个粗略的版本,仅用于演示目的):
>>> import subprocess
>>>
>>>
>>> def get_win_path(cyg_path):
... return subprocess.check_output(["cygpath", "-w", cyg_path]).strip(b"\n").decode()
...
>>>
>>> print(get_win_path("/cygdrive/c/location/of/file.html"))
C:\location\of\file.html
问题
假设您正在编写一个 Python 脚本,该脚本在 cygwin 上运行并调用需要输入路径的外部 C# 可执行文件。 假设您无法以任何方式更改 C# 可执行文件。 当您将所需路径发送到可执行文件时,它会拒绝所有 cygwin 路径。
因此,如果您将路径 /cygdrive/c/location/of/file.html
作为 POSIX 路径传递,它将失败,因为可执行文件需要 Windows 路径,例如 C:\location\of\file.html
示例:
Message location = os.path.dirname(os.path.realpath(__file__))
os.system('./cSharpScript.exe ' + message_location)
将导致:
File for the content (/cygdrive/c/location/of/file.html) not found.
到目前为止我尝试过的事情:
路径 = /cygdrive/c/location/of/file.html
1) path = PATH.replace('/','\')
结果:File for the content (cygdriveclocationoffile.html) not found.
2) path = os.path.abspath(PATH)
结果:File for the content (/cygdrive/c/location/of/file.html) not found.
os.path.realpath
有相同的结果
到目前为止,我的解决方案可能朝着完全错误的方向发展......你会如何处理它?
cygpath - Convert Unix and Windows format paths, or output system path information
...-w, --windows print Windows form of NAMEs (C:\WINNT)
示例:
[cfati@cfati-5510-0:/cygdrive/e/Work/Dev/Whosebug/q054237800]> cygpath.exe -w /cygdrive/c/location/of/file.html C:\location\of\file.html
翻译成Python(这是一个粗略的版本,仅用于演示目的):
>>> import subprocess >>> >>> >>> def get_win_path(cyg_path): ... return subprocess.check_output(["cygpath", "-w", cyg_path]).strip(b"\n").decode() ... >>> >>> print(get_win_path("/cygdrive/c/location/of/file.html")) C:\location\of\file.html