如何以shell依赖格式获取cwd? [英] How to get the cwd in a shell-dependend format?
问题描述
由于我同时使用Windows的 cmd.exe
和 msysgit 的 bash
,试图通过 os.getcwd()
访问Windows路径输出,这导致Python尝试访问以驱动器号和冒号开头的路径,例如 C:\
,该 bash
正确地确定了无效的unix路径,在本示例中,该路径应以/c/
开头.但是,如何修改Windows路径使其成为msys 等效的iff 脚本在中运行bash
?
Since I'm using both Windows' cmd.exe
and msysgit's bash
, trying to access the Windows-path output by os.getcwd()
is causing Python to attempt accessing a path starting with a drive letter and a colon, e.g. C:\
, which bash
correctly determines an invalid unix-path, which instead should start with /c/
in this example. But how can I modify a Windows-path to become its msys-equivalent iff the script is running within bash
?
推荐答案
难看,但是除非您为Windows创建环境变量 SHELL = bash
,否则它应该可以工作:
Ugly but should work unless you create an environment variable SHELL=bash
for Windows:
def msysfy(dirname):
import os
try:
shell = os.environ['SHELL']
except KeyError: # by default, cmd.exe has no SHELL variable
shell = 'win'
if os.path.basename(shell)=='bash' and dirname[1] == ':':
return '/' + dirname[0].lower() + '/' + dirname[2:]
# don't worry about the other backslashes, msys handles them
else:
return dirname
这篇关于如何以shell依赖格式获取cwd?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!