用文件系统编码中断来编码unicode路径

2024-10-03 21:24:49 发布

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

我的记忆中确实有以下路径:

video_path = u'C:\\Documents and Settings\\user\\My Documents\\Downloads\\\xf5iv - Neon Phoenix [Free DL].mp3'

我试图用它作为cmd中的一个参数,所以我必须对它进行编码。在

^{pr2}$

但是字符串的编码方式不正确-它将\xf5转换为?,而不是{}。因此找不到该文件。在

怎么会这样?我使用默认的文件系统编码(mbcs)。在


Tags: andpath记忆路径free编码settingsmy
3条回答

除非我完全弄错了,双反斜杠

video_path = u'C:...\\xf5iv...'

导致问题。应该只有一个:

^{2}$

否则,反斜杠将保留为反斜杠并留给os.system(),而不是{}来处理。在

尝试使用UTF-8编码:

video_path = video_path.encode("utf-8")

从答案here

In Py3K - at least from "Python" 3.2 - subprocess.Popen and sys.argv work consistently with (default unicode) str's on Windows. CreateProcessW and GetCommandLineW are used obviously.

In Python - up to v2.7.2 at least - subprocess.Popen is buggy with unicode arguments. It sticks to CreateProcessA (while os.* are consistent with unicode). And shlex.split creates additional nonsense. Pywin32's win32process.CreateProcess also doesn't auto-switch to the W version, nor is there a win32process.CreateProcessW. Same with GetCommandLine. Thus ctypes.windll.kernel32.CreateProcessW... needs to be used. The subprocess module perhaps should be fixed regarding this issue.

因此,subprocess.Popen无法在python2.x版本中处理unicode。在

我的解决方案是将输入文件重命名为随机的(使用支持unicode的os.rename),用我用subprocess.Popen启动的ffmpeg进行转换,然后重新命名。在

相关问题 更多 >