如何以shell依赖格式获取cwd?

时间:2016-05-18 08:02:59

标签: python windows bash msys dirname

由于我同时使用Windows“cmd.exe bash,因此尝试访问os.getcwd()的Windows路径输出会导致Python尝试访问以驱动器号和冒号开头的路径,例如C:\bash正确确定了无效的unix路径,而在此示例中,该路径应以/c/开头。但是,如何将Windows路径修改为 - 等效iff脚本在bash内运行?

1 个答案:

答案 0 :(得分:0)

丑陋但除非您为Windows创建环境变量SHELL=bash,否则应该有效:

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