当我通过 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 Task Scheduler 运行脚本的问题,那么错误仍然出现?!:
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)
最佳答案
从命令行运行时,Python 会检测终端的编码,并以该编码将 Unicode 文本编码到终端。在任务计划程序下运行时,Python 不会检测输出编码,并且默认为 ascii
。
当将源编码声明为 utf8
时,它可以在 Python 2 中工作,因为您没有使用 Unicode 字符串,并且 print
只是将 UTF-8 编码的字节字符串发送到终点站。您的终端是 UTF-8,所以它可以工作。
当在调度程序下运行时,您可以通过设置环境变量 PYTHONIOENCODING=utf8 来覆盖 Python 的默认假设。该变量在所有平台下都可用。
引用号:PYTHONIOENCODING
关于linux - 通过 Synology 任务计划程序运行时出现 Python3 UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38174485/