Emacs一直询问是否保存带有 # -*- coding: ASCII -*- 的Python代码

3
我有一个以以下内容开始的Python脚本:
```python ```
#!/usr/bin/env python
# -*- coding: ASCII -*-

在保存之前,它总是分割我的窗口并询问:

警告(骡子):当前缓冲区/文件的编码标签指定了无效的编码系统 `ASCII' 。强烈建议在写入文件之前修复该问题。

我需要回答"yes",有没有办法禁用这个?很抱歉问一下,但我在谷歌上没找到答案。

Gabriel


PEP 263中可以得知:"如果没有编码注释,Python解析器会默认为ASCII编码"。因此,在您的文件中完全不需要这个。 - Chris
此外,从这个答案可以看到,你可以使用# coding: ascii代替更冗长的# -*- coding: ASCII -*-。这也在PEP 263中提到过。 - Chris
1
@Chris:为什么不把这个放在答案里呢? - Thomas
@Thomas 谢谢你的建议,我已经完成了。 - Chris
2个回答

7

一种不需要更改脚本的解决方案是告诉Emacs在编码系统中ASCII代表什么意思。(默认情况下,Emacs将其称为US-ASCII。)将以下内容添加到您的.emacs文件中:

(define-coding-system-alias 'ascii 'us-ascii)

然后 Emacs 应该能够理解 # -*- coding: ASCII -*-

3
Python增强建议(PEP)263 “定义Python源代码编码”,讨论了定义源代码编码的多种方式。这里有两个特别重要的点:
  • Without encoding comment, Python's parser will assume ASCII

    So you don't need this at all in your file. Still, if you do want to be explicit about the file encoding:

  • To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

    # coding=<encoding name>
    

    (note that the = can be replaced by a :). So you can use # coding: ascii instead of the more verbose # -*- coding: ASCII -*-, as suggested by this answer. This seems to keep emacs happy.


1
如果你使用的是Python 2.x,没有编码注释,解析器会默认为ASCII。如果你想要ASCII源代码并且使用的是Python 3.x,那么你确实需要它。 - Brenda J. Butler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接