如何在Cygwin中使用Python有效地将POSIX路径转换为Windows路径



>问题

想象一下,您正在编写一个在cygwin上运行的Python脚本,并调用外部C#可执行文件,该可执行文件需要路径作为输入。假设您不能以任何方式更改 C# 可执行文件。当您将所需的路径发送到可执行文件时,它会拒绝所有 cygwin 路径。

因此,如果将路径/cygdrive/c/location/of/file.html作为 POSIX 路径传递,它将失败,因为可执行文件需要类似 C:locationoffile.html 的 Windows 路径

例:

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具有相同的结果

到目前为止,我的解决方案可能走上了完全错误的方向......你会如何处理它?

根据[Cygwin]: 天鹅:

cygpath - 转换Unix和Windows格式路径,或输出系统路径信息
...

-w, --windows         print Windows form of NAMEs (C:WINNT)

例:

[cfati@cfati-5510-0:/cygdrive/e/Work/Dev/StackOverflow/q054237800]> cygpath.exe -w /cygdrive/c/location/of/file.html
C:locationoffile.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:locationoffile.html

最新更新