繁体   English   中英

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

[英]How to effectively convert a POSIX path to Windows path with Python in Cygwin?

问题

想象一下,您正在编写一个在cygwin上运行的Python脚本,并调用需要输入路径的外部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.

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM