Jon*_*han 3 python windows unicode subprocess os.system
如何在Windows下的Python脚本中打开一个名为unicode的文件(带空格)?
文件名例如:Hello ????.xls
对于非unicode非间隔xls文件,os.system(filename)效果很好.
对于非unicode间隔xls文件,os.system('"'+filename+'"')效果很好.
但对于unicode空间xls文件...
两者os.system(filename)并subprocess.call(new_filename)给予:
UnicodeEncodeError:'ascii'编解码器无法编码位置12-13中的字符:序数不在范围内(128)
os.system(new_filename.encode('UTF-8')) 得到:
"Hello"不被识别为内部或外部命令,可操作程序或批处理文件.
并subprocess.call(new_filename.encode('UTF-8'))给出:
WindowsError:[错误2]系统找不到指定的文件
os.startfile() 如Bradley(+1)所述,但请确保传入Unicode字符串,而不是字节字符串.
Windows NT文件名本身就是Unicode,并且Windows上的Python(与大多数其他脚本语言不同)内置了特定的支持,用于将Unicode字符串传递到期望文件名的API:
os.startfile(u'Hello \u05e2\u05d5\u05dc\u05dd.xls') # u'Hello ????.xls'
Run Code Online (Sandbox Code Playgroud)
如果你传入一个字节字符串,它将转而使用标准C stdio库,它在Microsoft C Runtime上将使用机器的默认字符集(又名ANSI代码页)将字节字符串映射到Unicode文件名,这getfilesystemencoding()是返回的内容.如果文件名中的每个字符都可以在ANSI代码页中表示,那么它仍然可以工作,但是除了希伯来语安装的Windows之外,示例文件名都会失败.
不幸的是,相同的Unicode支持不适用于system()或subprocess.但在这种情况下,您可能不需要使用命令行.
| 归档时间: |
|
| 查看次数: |
1190 次 |
| 最近记录: |