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

2024-06-16 11:50:21 发布

您现在位置:Python中文网/ 问答频道 /正文

由于我同时使用Windows的cmd.exebash,试图通过os.getcwd()访问Windows路径输出会导致Python尝试访问以驱动器号和冒号开头的路径,例如C:\,在本例中,bash正确地确定了无效的unix路径,而该路径应该以/c/开头。但是如何修改Windows路径,使之成为脚本在bash中运行的等价的iff?你知道吗


Tags: 路径脚本cmdbashoswindowsunixexe
1条回答
网友
1楼 · 发布于 2024-06-16 11:50:21

很难看,但除非为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

相关问题 更多 >