最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Mac中PyCharm中Python代码调试报错:SyntaxError Non-ASCII character xe7 in file on line but no encoding

Mac crifan 6531浏览 0评论

折腾:

【记录】尝试用Python操作PhantomJS+Selenium去模拟购物操作

期间,在PyCharm中,用代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get(‘http://www.baidu.com/‘)
assert u”百度” in driver.title
searchElement = driver.find_element_by_name(“wd”)
searchElement.send_keys(“crifan”)
searchElement.send_keys(Keys.RETURN)
print driver.page_source

结果运行报错:

/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py –multiproc –qt-support –client 127.0.0.1 –port 58406 –file /Users/crifan/dev/dev_root/projects/亚马逊/自动下单/AutoOrder/AutoOrder.py
warning: Debugger speedups using cython not found. Run ‘”/usr/local/opt/python/bin/python2.7″ “/Applications/PyCharm.app/Contents/helpers/pydev/setup_cython.py” build_ext –inplace’ to build.
pydev debugger: process 19469 is connecting
Connected to pydev debugger (build 163.15188.4)
Traceback (most recent call last):
  File “/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py”, line 1596, in <module>
    globals = debugger.run(setup[‘file’], None, None, is_module)
  File “/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py”, line 974, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File “/Users/crifan/dev/dev_root/projects/亚马逊/自动下单/AutoOrder/AutoOrder.py”, line 6
SyntaxError: Non-ASCII character ‘\xe7’ in file /Users/crifan/dev/dev_root/projects/亚马逊/自动下单/AutoOrder/AutoOrder.py on line 6, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

1.试了试,PyCharm中,能不能把ASCII编码的文件换成UTF-8的:

 

然后选择UTF-8:

结果还是报错

2.最后参考自己的帖子:

【整理】关于Python脚本开头两行的:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定文件编码类型 – 在路上

是顶部加上:

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

才解决了问题。

后来才想到,其实上面是转换了UTF-8编码了。

只不过是代码中没有声明而已。

【总结】

此处PyCharm中是可以通过:File-》File Encoding-》选择UTF-8

把文件本身的编码设置为UTF-8的

但是还需要在Python文件中加上声明:

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

告诉解析器以UTF-8编码去解析当前python文件,才可以正常工作。

转载请注明:在路上 » 【已解决】Mac中PyCharm中Python代码调试报错:SyntaxError Non-ASCII character xe7 in file on line but no encoding

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.194 seconds, using 22.10MB memory