【问题标题】:How to effectively convert a POSIX path to Windows path with Python in Cygwin?如何在 Cygwin 中使用 Python 有效地将 POSIX 路径转换为 ​​Windows 路径?
【发布时间】:2019-06-11 18:19:48
【问题描述】:

问题

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

因此,如果您将路径 /cygdrive/c/location/of/file.html 作为 POSIX 路径传递,它将失败,因为可执行文件需要像 C:\location\of\file.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.

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

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

到目前为止,我的解决方案可能正朝着完全错误的方向发展......你会如何处理它?

【问题讨论】:

  • Windows 路径是r'C:\location\of\file.html',其中"/cygdrive/c" -> "C:" 和斜杠转换为反斜杠。
  • 是的,但我不想手动操作... python 有什么方法可以处理它吗?
  • 不在标准库中;也许在 PyPI 上有一个包。或者也许 Cygwin 有一个系统函数或命令行实用程序来转换路径。
  • 有趣的事实:Windows 本身必须将“C:”转换为调用者本地设备目录中的名称。这被称为魔术前缀“\??\”,例如“\??\C:\location\of\file.html”。它解析到调用者的登录会话挂载点目录“\Sessions\0\DosDevices\”,它会(在一个联合中)隐藏全局挂载目录“\Global??”。这些包含具有众所周知的名称的符号链接(AKA 联结),其目标设备通常位于“\Device”中。因此,真正的 NT 路径类似于“\Device\HarddiskVolume2\location\of\file.html”。但也许这也是一个谎言......
  • 也许这篇文章可能会有所帮助。 Convert POSIX->WIN path, in Cygwin Python, w/o calling cygpath

标签: windows python-2.7 path cygwin


【解决方案1】:

根据[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

【讨论】:

  • @eryksun:谢谢你的小费。越短越好!更新了答案。
  • 像魅力一样工作(尽管显然使用了 subprocess.call)。谢谢@CristiFati!
猜你喜欢
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 2019-08-18
  • 2014-08-10
  • 2019-11-14
  • 2019-01-08
相关资源
最近更新 更多