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

时间:2019-01-17 14:13:14

标签: windows python-2.7 path cygwin

问题

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

因此,如果您将路径snprintf(symbol, symbolSize, "| %s \n", ascii); strcat(buffer, symbol); memset(symbol,0,strlen(symbol)); 作为POSIX路径传递,则它将失败,因为可执行文件需要Windows路径,例如/cygdrive/c/location/of/file.html

示例:

C:\location\of\file.html Message location = os.path.dirname(os.path.realpath(__file__))

将导致:

os.system('./cSharpScript.exe ' + message_location)

到目前为止我已经尝试过的事情:

PATH = /cygdrive/c/location/of/file.html

1)File for the content (/cygdrive/c/location/of/file.html) not found.

结果:path = PATH.replace('/','\\')

2)File for the content (cygdriveclocationoffile.html) not found.

结果:path = os.path.abspath(PATH)

  • File for the content (/cygdrive/c/location/of/file.html) not found.具有相同的结果

到目前为止,我的解决方案可能会朝着完全错误的方向……您将如何处理?

1 个答案:

答案 0 :(得分:2)

根据[Cygwin]: cygpath

  

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:\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