Python 脚本在 Spyder 中完美运行(在 Windows 上)——在 Linux 上不起作用

标签 python linux cnf

我写了一个脚本来读取 .cnf 文件,分析一些东西然后输出一些结果(通过 print())。为了读取 .cnf 文件,我使用以下行:

with open('config.cnf') as f:
file_content = f.read()

现在,如果我在 Spyder 环境(Python 3.6)中运行它,一切正常。脚本读取 config.cnf,执行操作并输出结果。如果我在 Linux 上运行完全相同的脚本(config.cnf 位于同一目录中),则会显示以下错误消息:

Traceback (most recent call last):
  File "Conf2Monit_V2.py", line 45, in <module>
    file_content = f.read()
  File "/usr/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in Position 29834: invalid start byte

我使用以下命令:

python3 myScript.py 

我是 Python 和 Linux 的新手,所以如果这是一些基本错误,请不要厌烦。谢谢。

最佳答案

我猜这个问题可能是因为 Historical reason behind different line ending at different platforms

如果是这种情况,请尝试 this

或者你可以试试Linux的iconv命令。

你能不能在你的Linux环境下运行下面的命令来检查文件中字符的编码:

file -i <filename>

检查输出是否类似于 charset=utf-8

如果不是,那么有一种方法可以将编码转换为 UTF-8,如图所示 here

它解释了如何将文件(“input.txt”)的编码从代码集 ISO88592 转换为 UTF8 代码集或 ASCII,并将结果存储为“output.txt”。

iconv -f ISO88592 -t UTF8 input.txt output.txt

因此,如果正在考虑的文件是 input.txt,您可能需要遵循的步骤是:

  1. file -i input.txt
    假设它的输出类似于
    input.txt: text/plain;字符集=iso-88592
  2. iconv -f ISO88592 -t UTF8 输入.txt 输出.txt

关于Python 脚本在 Spyder 中完美运行(在 Windows 上)——在 Linux 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55899736/

相关文章:

python - 从 Django 管理中删除历史按钮

linux - 10gen 彩信监控服务重启后启动

eclipse-plugin - 如何使用带有复选框的 Common Navigator Framework

java - eclipse插件开发: how to open a custom editor from a cnf (on double click).

c - 关于 SAT 求解器和 cnf 文件

python - 使用 python 子进程和 ssh 读取远程文件?

python - django admin 与 GeoModelAdmin 内联

python - Pandas 根据多个条件过滤行

c - 平衡 Linux 内核中的内存使用

linux - 读取文件中的第一行并将其附加到搜索字符串的第一次出现处并重复直到 EOF