How to get the cwd in a shell-dependend format?

半世苍凉 提交于 2019-12-13 07:43:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37293650/how-to-get-the-cwd-in-a-shell-dependend-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!