问题
Problem
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.
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
Example:
Message location = os.path.dirname(os.path.realpath(__file__))
os.system('./cSharpScript.exe ' + message_location)
Will result in:
File for the content (/cygdrive/c/location/of/file.html) not found.
Things I've tried so far:
PATH = /cygdrive/c/location/of/file.html
1) path = PATH.replace('/','\\')
Result: File for the content (cygdriveclocationoffile.html) not found.
2) path = os.path.abspath(PATH)
Result: File for the content (/cygdrive/c/location/of/file.html) not found.
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?
回答1:
According to [Cygwin]: cygpath:
cygpath - Convert Unix and Windows format paths, or output system path information
...-w, --windows print Windows form of NAMEs (C:\WINNT)
Example:
[cfati@cfati-5510-0:/cygdrive/e/Work/Dev/StackOverflow/q054237800]> cygpath.exe -w /cygdrive/c/location/of/file.html C:\location\of\file.html
Translated into Python (this is a rough version, only for demonstrating purposes):
>>> 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
来源:https://stackoverflow.com/questions/54237800/how-to-effectively-convert-a-posix-path-to-windows-path-with-python-in-cygwin