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

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

问题描述:

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

Imagine you are writing a Python script which runs on cygwin and calls an external C# executable which requires as input a path. Assume you cannot change the C# executable in any way. As you send the path you want to the executable, it rejects all cygwin paths.

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

So if you pass the path /cygdrive/c/location/of/file.html as a POSIX path, it will fail as the executable requires a Windows path like 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.

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

PATH = /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具有相同的结果
  • os.path.realpath has the same results

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

I'm probably going in a completely wrong direction with my solutions so far... How would you handle it?

根据> Cygwin]:cygpath :

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

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/*/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