【发布时间】:2016-07-03 21:27:23
【问题描述】:
当我通过 Synology 任务计划程序运行我的脚本时,我得到一个 Python3 UnicodeEncodeError。通过命令行(使用 PuTTY)运行脚本时,我没有收到此错误。为什么会这样,我该如何解决?
简单的测试脚本:
import sys
print (sys.version) # to confirm the correct Python version
print("Fichier non trouvé♠ #M–Nein") # to test non ascii characters
test = "Fichier non trouvé♠ #M–Nein"
print ("test is " + test)
test2 = str(test) # to test if the string function causes and issue
print ("test2 is " + test2)
命令行输出:
admin@DiskStation:/volume1/@appstore/py3k/usr/local/bin$ /volume1/@appstore/py3k/usr/local/bin/python3 /volume1/Documenten/MyPythonScripts/Test.py
3.5.1 (default, Feb 23 2016, 17:46:04)
[GCC 4.9.3 20150311 (prerelease)]
Fichier non trouvé♠ #M–Nein
test is Fichier non trouvé♠ #M–Nein
test2 is Fichier non trouvé♠ #M–Nein
任务调度器输出:
3.5.1 (default, Feb 23 2016, 17:46:04)
[GCC 4.9.3 20150311 (prerelease)]
Traceback (most recent call last):
File "/volume1/Documenten/MyPythonScripts/Test.py", line 3, in <module>
print("Fichier non trouv\xe9\u2660 #M\u2013Nein") # to test non ascii characters
UnicodeEncodeError: 'ascii' codec can't encode characters in position 17-18: ordinal not in range(128)
注意:使用相同的 Python 版本和脚本运行
/volume1/@appstore/py3k/usr/local/bin/python3
/volume1/Documenten/MyPythonScripts/Test.py
在这两种情况下。
注意 2:如果我通过命令行运行脚本但使用 Python2.7,则会出现更早的(第 1 行)Unicode 错误:(仅供参考,Python 3 与 Python 2)
admin@DiskStation:/volume1/Documenten/MyPythonScripts$ **python3** Test.py
Fichier non trouvé♠ #M–Nein
test is Fichier non trouvé♠ #M–Nein
test2 is Fichier non trouvé♠ #M–Nein
admin@DiskStation:/volume1/Documenten/MyPythonScripts$ **python** Test.py
File "Test.py", line 1
SyntaxError: Non-ASCII character '\xc3' in file Test.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
这个 Unicode 问题可以在 Python2.7 中通过在脚本的第一行或第二行添加以下内容来解决:
# -*- coding: UTF-8 -*-
然后脚本从命令行运行良好。
但添加此 UTF-8 行并不能解决从 Synology 任务计划程序运行脚本的问题,那么仍然会引发错误?!:
3.5.1 (default, Feb 23 2016, 17:46:04)
[GCC 4.9.3 20150311 (prerelease)]
Traceback (most recent call last):
File "/volume1/Documenten/MyPythonScripts/Test.py", line 4, in <module>
print("Fichier non trouv\xe9\u2660 #M\u2013Nein") # to test non ascii characters
UnicodeEncodeError: 'ascii' codec can't encode characters in position 17-18: ordinal not in range(128)
【问题讨论】:
标签: linux python-3.x unicode synology