subprocess.Popen 带有 unicode 路径

2023-07-21Python开发问题
10

本文介绍了subprocess.Popen 带有 unicode 路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想打开一个 unicode 文件名.以下代码:

I have a unicode filename that I would like to open. The following code:

cmd = u'cmd /c "C:\Pokxe9mon.mp3"'
cmd = cmd.encode('utf-8')
subprocess.Popen(cmd)

返回

>>> 'C:Pokmon.mp3' is not recognized as an internal or external command, operable program or batch file.

即使该文件确实存在.为什么会这样?

even though the file do exist. Why is this happening?

推荐答案

看起来您使用的是 Windows 和 Python 2.X.使用 os.startfile:

It looks like you're using Windows and Python 2.X. Use os.startfile:

>>> import os
>>> os.startfile(u'Pokémon.mp3')

不直观地,让命令 shell 做同样的事情是:

Non-intuitively, getting the command shell to do the same thing is:

>>> import subprocess
>>> import locale
>>> subprocess.Popen(u'Pokémon.mp3'.encode(locale.getpreferredencoding()),shell=True)

在我的系统上,命令 shell (cmd.exe) 编码是 cp437,但对于 Windows 程序是 cp1252.Popen 想要编码为 cp1252 的 shell 命令.这似乎是一个错误,在 Python 3.X 中似乎也已修复:

On my system, the command shell (cmd.exe) encoding is cp437, but for Windows programs is cp1252. Popen wanted shell commands encoded as cp1252. This seems like a bug, and it also seems fixed in Python 3.X:

>>> import subprocess
>>> subprocess.Popen('Pokémon.mp3',shell=True)

这篇关于subprocess.Popen 带有 unicode 路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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