Deal with unicode usernames in python mkdtemp

前端 未结 1 1943
抹茶落季
抹茶落季 2021-01-15 21:57

I was bitten by http://bugs.python.org/issue1681974 - quoting from there:

mkdtemp fails on Windows if Windows user name has any non-ASCII characters,

相关标签:
1条回答
  • 2021-01-15 22:50

    I finally went with:

    sys_fs_enc = sys.getfilesystemencoding() or 'mbcs'
    
    @staticmethod
    def tempDir(prefix=None):
        try: # workaround for http://bugs.python.org/issue1681974 see there
            return tempfile.mkdtemp(prefix=prefix)
        except UnicodeDecodeError:
            try:
                traceback.print_exc()
                print 'Trying to pass temp dir in...'
                tempdir = unicode(tempfile.gettempdir(), sys_fs_enc)
                return tempfile.mkdtemp(prefix=prefix, dir=tempdir)
            except UnicodeDecodeError:
                try:
                    traceback.print_exc()
                    print 'Trying to encode temp dir prefix...'
                    return tempfile.mkdtemp(
                        prefix=prefix.encode(sys_fs_enc)).decode(sys_fs_enc)
                except:
                    traceback.print_exc()
                    print 'Failed to create tmp dir, Bash will not function ' \
                          'correctly.'
    

    Apparently the first try catch is sufficient but I left the tracebacks in so I can get some more input ;)

    0 讨论(0)
提交回复
热议问题