0

首先,是的,我已经搜索过,但没有找到任何解决方案。所以,问题是:

我有一个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. 它是一个带有Tkinterpython 库的图形用户界面。您可以使用其上的所有 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.PopenCMD 的问题吗?我想是的,但找不到解决方案。

我试过了 :

  • mbcs用, ansi, ISO-8859-1in改变编码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:对不起,英语不是我的母语。

4

1 回答 1

0

也许尝试调用 subproces.Popen env={'PYTHONIOENCODING': 'utf-8'}

根据您的错误,Python 选择了 cp1252 的“系统编码”(用于 IO 流),除了与您告诉子进程期望的编码不兼容之外,它不能代表您从输入中获得的所有可能的字符

PYTHONIOENCODING 应该覆盖 Python 用于选择系统编码的过程,并将输出流编码为 utf-8,它应该能够表示任何输入,并且符合包装器的期望。

于 2020-04-24T09:37:12.840 回答