首先,是的,我已经搜索过,但没有找到任何解决方案。所以,问题是:
我有一个CommandLine.py
在 PyCharm 中创建的第一个 python 脚本,它从网站请求一个 Json 文件,然后我在终端上打印结果。
for val in my_json[:200]:
i += 1
print(" {} - {}".format(str(i).zfill(2), val))
这个命令行脚本是这样使用的:
python CommandLine.py --user MyUserName --password MyPWD --website www.about.com --output C:\Users\MyName\MyFolder --mail YesOrNo and so on...
一切正常,我得到了结果,即使结果中有俄语字符、日语字符和“有趣”字符(比如这个:�)。它在 PyCharm 和 Windows CMD 中以相同的方式工作(像这样的“有趣”字符在两者中都打印出来)。
但是这个第一个脚本对所有参数都有点烦人(对我来说,对朋友来说......),所以我创建了第二个名为GUI.py
. 它是一个带有Tkinter
python 库的图形用户界面。您可以使用其上的所有 Entry 小部件来选择所需的参数。然后单击 Button 小部件并在名为“Console”的 Text 小部件中获得结果(以“模拟”终端)。我这样做是subprocess.Popen
这样的:
cmd = 'python CommandLine.py --user MyUserName --password MyPWD
--website www.about.com --output C:\Users\MyName\MyFolder
--mail YesOrNo and so on...'
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='utf-8')
while True:
returnStatus = process.poll()
output = process.stdout.readline()
if returnStatus is not None:
break
if output:
line = output.strip() # leave the white space
console.insert('end', line + '\n')
console.yview_moveto(1)
console.update()
GUI.py
在 PyCharm 中工作正常,我得到的结果与 do CommandLine.py
(使用非拉丁字符)相同,没有代码错误。
但 !对,但是。在 Windows CMD 中,第二个脚本GUI.py
总是因以下代码错误而崩溃:
Traceback (most recent call last):
File "C:\Users\MyName\MyFolder\CommandLine.py", line 343, in <module>
print(" {} - {}".format(str(i).zfill(2), val))
File "C:\Python37\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 10-11: character maps to <undefined>
我不明白为什么,因为第一个脚本CommandLine.py
在 PyCharm 和 Win CMD 中都可以正常工作。
是subprocess.Popen
CMD 的问题吗?我想是的,但找不到解决方案。
我试过了 :
mbcs
用,ansi
,ISO-8859-1
in改变编码process = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='utf-8')
删除编码
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='utf-8')
添加
Shell=True
chcp 65001
之前在 CMD 中做python GUI.py
没有解决问题,仍然有代码错误。
顺便说一句,我subprocess.Popen
用来获取“实时”输出以将其打印为我的“控制台”小部件。
我哪里错了?请需要帮助。提前致谢。
PS:对不起,英语不是我的母语。