Unicode 文件名到 python subprocess.call()

2023-07-21Python开发问题
3

本文介绍了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())])

尝试找出当前的编码,因此将正确的编码应用到 subprocess.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(或操作系统,不知道)会用重音字符弄乱目录.为了防止这种情况,我发现以下方法可以工作:

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11