【问题标题】:How do I declare an encoding for Python source code?如何为 Python 源代码声明编码?
【发布时间】:2014-09-03 07:33:55
【问题描述】:

如何声明此代码的编码?

我知道如何在其他情况下声明编码,但我该怎么做呢?

if used_prefix and cmd=="shoot" and user.name in whitelist:
    name = args.lower()
    if name in killed:
        room.message(user.name+' is already dead.')
    else:
        killed.append(name)
        saveKills()
        room.message('//'+user.name+' shoots '+name+' in the head.')

错误信息说:

语法错误:第 6 行的文件 /home/stephen/downloads/inhaley/inhaley.py 中的非 ASCII 字符“\xe3”,但未声明编码;详情请见http://www.python.org/peps/pep-0263.html

【问题讨论】:

  • 哇——当 Python 网站更新时,内置错误消息发出的 URL 被破坏是非常疏忽的。幸运的是,the new URL is easy enough to find
  • 由于您发布的代码实际上不包含任何非 ASCII 代码点,我怀疑有一个奇异的 Unicode 字符潜入;第 6 行是哪一行?
  • @MartijnPieters 它重定向到 PEP 索引,而不是特定的 PEP。这并不可怕,但正确地完成它应该不需要更多的工作。
  • @BradKoch:这里不需要使用源编码;所需要的只是删除一个杂散字符,因为代码本身显然只是 ASCII。

标签: python character-encoding


【解决方案1】:

#coding=utf-8 放在脚本/文件的顶部

【讨论】:

    【解决方案2】:

    在代码顶部添加#coding=utf-8,如下所示:

    #coding=utf-8
    
    #imports here
    import math
    
    print 'The encoding has been set!'
    

    【讨论】:

      【解决方案3】:

      添加

      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      

      在前 2 行。

      【讨论】:

      • #!/usr/bin/env python 与编码有什么关系?
      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2022-01-01
      • 2012-08-27
      • 2013-02-24
      • 2015-04-27
      相关资源
      最近更新 更多