【发布时间】:2020-06-07 19:30:32
【问题描述】:
我正在尝试传递一个包含韩语字符的字符串参数。这会导致错误,因为韩语字符在传递给open() 内置函数之前显然没有正确编码/解码。
我写了一个命令,然后用os.system()执行,相当于在命令提示符下运行。
command = 'hwp5txt "C:\\Users\\username\\VSCodeProjects\\myproject\\data_files\\some_folder\\hwp\\2020-01-17_-_한국어가포함된 파일명(2020년도 제1차).hwp" > testdoc.txt'
os.system(command)
这会引发错误,因为韩语字符未正确解码。
Traceback(最近一次调用最后一次):文件 "C:\Users\username\AppData\Local\pypoetry\Cache\virtualenvs\asiae-bok-nlp-xpMr0EW7-py3.7\Scripts\hwp5txt-script.py", 第 11 行,在 load_entry_point('pyhwp==0.1b12', 'console_scripts', 'hwp5txt')() 文件 "c:\users\username\appdata\local\pypoetry\cache\virtualenvs\asiae-bok-nlp-xpmr0ew7-py3.7\lib\site-packages\hwp5\hwp5txt.py", 第 102 行,在 main
关闭(Hwp5File(hwp5path))作为hwp5file:文件“c:\用户\用户名\appdata\local\pypoetry\cache\virtualenvs\asiae-bok-nlp-xpmr0ew7-py3.7\lib\site-packages\hwp5\文件结构.py", 第 537 行,在 init 中 stg = Hwp5FileBase(stg) 文件 "c:\users\username\appdata\local\pypoetry\cache\virtualenvs\asiae-bok-nlp-xpmr0ew7-py3.7\lib\site-packages\hwp5\filestructure.py", 第 188 行,在 init 中 stg = OleStorage(stg) 文件“c:\users\username\appdata\local\pypoetry\cache\virtualenvs\asiae-bok-nlp-xpmr0ew7-py3.7\lib\site-packages\hwp5\storage\ole.py ", 第 35 行,在 init 中 self.impl = impl_class(*args, **kwargs) 文件 "c:\users\uesrname\appdata\local\pypoetry\cache\virtualenvs\asiae-bok-nlp-xpmr0ew7-py3.7\lib\site-packages\ hwp5\plat\olefileio.py", 第 112 行,在 init 中 如果不是 isOleFile(olefile):文件 "c:\users\username\appdata\local\pypoetry\cache\virtualenvs\asiae-bok-nlp-xpmr0ew7-py3.7\lib\site-packages\olefile\olefile.py" , 第 309 行,在 isOleFile 中 使用 open(filename, 'rb') as fp: OSError: [Errno 22] Invalid argument: 'C:\Users\username\VSCodeProjects\asiae-BOK-nlp\data_files\BOK_minutes\hwp\2020-01-17_-_??????? ???(2020???1?).hwp'
如您所见,OS Error 被提出是因为我发送到提示符的命令不知何故未能传递正确的韩文字符,现在是????? 而不是它的正确名称。
我在终端上手动尝试过,但也失败了。
如何将未正确传递给模块的字符串字符传递给模块?
我正在使用最新版本的 VSCode 和 Git Bash 终端。
另外,我可以查看这些信息。如果您需要更多信息,请发表评论。
sys.stdout.encoding
>> 'UTF-8'
sys.stdin.encoding
>> 'cp1252'
sys.getfilesystemencoding
>> 'UTF-8'
【问题讨论】:
-
os.system调用 Windows_wsystemAPI。我不确定那里是否存在代码页问题。subprocess使用 CreateProcessW 可能会更好。试试subprocess.run(command, shell=True)。或者通过使命令列表command = ["hwp5txt", "C:\\Users\\username\\VSCodeProjects\\myproject\\data_files\\some_folder\\hwp\\2020-01-17_-_한국어가포>함된 파일명(2020년도 제1차).hwp"]然后subprocess.run(command, stdout=open("testdoc.txt", "wb"))来在没有shell 的情况下运行 -
看起来你的 docx 库抛出了错误。是最新的吗?
-
@tdelaney 抱歉,不走运。他们都返回错误。正如我所说,问题是正确的文件名没有到达
\olefile\olefile.py。当它到达那里时,它神奇地变成了无用的?????字符串,而不是正确的文件名。 -
@usr2564301 不,我相信
olefile会抛出错误,但我不认为这真的是olefile的问题,因为参数值,即文件名,甚至没有得到有适当的形式。我不知道它在哪里搞砸了,并给出了?????而不是正确的文件名。 -
我认为有些东西试图将字符串编码为 cp1252。这 ?是传统的“我不知道那是什么”字符。我不知道是你的程序还是hwp5txt。你可以编写自己的python小程序
import sys;print(sys.argv),看看你是否遇到同样的问题。
标签: python encoding visual-studio-code terminal character-encoding