Unicode文件名到python subprocess.call() [英] Unicode filename to python subprocess.call()

查看:98
本文介绍了Unicode文件名到python subprocess.call()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Unicode文件名运行subprocess.call(),这是一个简化的问题:

I'm trying to run subprocess.call() with unicode filename, and here is simplified problem:

n = u'c:\\windows\\notepad.exe '
f = u'c:\\temp\\nèw.txt'

subprocess.call(n + f)

这会引起著名的错误:


UnicodeEncodeError:'ascii'编解码器无法编码字符u'\xe8'

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8'

对utf-8进行编码会产生错误的文件名,并且mbcs将文件名作为new.txt传递而没有重音

Encoding to utf-8 produces wrong filename, and mbcs passes filename as new.txt without accent

我只是无法再阅读这个令人困惑的主题并旋转输入圈。我在这里找到了过去许多不同问题的许多答案,因此我想自己加入并寻求帮助

I just can't read any more on this confusing subject and spin in circle. I found here lot of answers for many different problems in past so I thought to join and ask for help myself

谢谢

推荐答案

我发现了一个很好的解决方法,虽然有点混乱,但是可以用。

I found a fine workaround, it's a bit messy, but it works.

subprocess.call将通过以自己的编码形式发送到终端的文本,该文本可能与预期的一样。因为要使其可移植,所以您需要在运行时知道计算机的编码。

subprocess.call is going to pass the text in its own encoding to the terminal, which might or not be the one it's expecting. Because you want to make it portable, you'll need to know the machine's encoding at runtime.

以下内容

notepad = 'C://Notepad.exe'
subprocess.call([notepad.encode(sys.getfilesystemencoding())])

试图找出当前编码,因此将正确的编码应用于子处理。call

attempts to figure out the current encoding and therefore applies the correct one to subprocess.call

作为旁注,我还发现,如果您尝试使用当前目录来组成字符串,请使用

As a sidenote, I have also found that if you attempt to compose a string with the current directory, using

os.cwd() 

Python(或OS,不知道)会弄乱目录重音字符。为了防止这种情况,我发现以下方法可以工作:

Python (or the OS, don't know) will mess up directories with accented characters. To prevent this I have found the following to work:

os.cwd().decode(sys.getfilesystemencoding())

与上述解决方案非常相似。

Which is very similar to the solution above.

希望有帮助。

这篇关于Unicode文件名到python subprocess.call()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆