我的NAS上安装了自定义python库,其中包含以下代码:
try:
i = open("/volume1/web/python/session.txt")
try:
a = str(i.read())
except Exception as err:
a = "Exception: {0}".format(err)
finally:
i.close()
except Exception as err:
a = "Exception: {0}".format(err)
return a
此代码由调用应用程序类型将返回的文本保存到文件中。你知道吗
当应用程序类型是从SSH运行的,它保存的内容会话.txt如预期。 但是当应用程序类型作为任务运行(运行.sh),它保存异常“'ascii'编解码器无法解码位置12的字节0xc3:序号不在范围内(128)”。是的,文件在第12位包含“á”,所以我将encoding=“utf-8”添加到open()函数中。而且这个失败了(没有保存任何内容,所以我甚至不知道它是否和抛出了什么错误。)
你知道如何通过python库安全地打开和读取文本文件吗(当使用正则脚本时,即使它作为任务运行也能正确运行)?你知道吗
图书馆:
class API():
def __init__(self, dir):
self.DIR = dir
def CheckTokens(self):
print("\nChecking all saved tokens")
try:
i = open(os.path.join(self.DIR, "session.txt"), encoding='utf-8')
try:
a = i.read()
except Exception as err:
a = "Exception: {0}".format(err)
finally:
i.close()
except Exception as err:
a = "Exception: {0}".format(err)
return a
应用程序类型:
import os.path
from time import localtime, strftime
from APIfile import API
if __name__ == "__main__":
LOCAL_DIR = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
def write(text, type):
time = localtime()
time = "%s@%s" % (strftime("%Y%m%d", time), strftime("%H%M%S", time))
filename = "%s%s.txt" % (time, ("_%s" % type if type != "JSON" else ""))
f = open(os.path.join(LOCAL_DIR, "logs", filename), "a")
f.write(str(text))
f.close()
INSTANCE = API(LOCAL_DIR)
tokens = INSTANCE.CheckTokens()
write(tokens, "DEBUG")
运行.sh:
python3 /volume1/web/python/app.py
会话.txt和日志文件夹与位于同一目录中应用程序类型
我有点困惑,但我猜:^{} defaults to the shell's preferred encoding ,而且您的NAS的locale设置与您的本地shell不同。我认为
encoding=utf-8
是解决当前问题的方法。你知道吗现在,你说那也不行。我不确定您所说的“不保存任何内容”是什么意思,我猜您的脚本需要将其输出保存到一个文件中,而NAS守护进程没有写入该文件的权限。您没有说明负责保存到磁盘的调用实际上是什么样子的,但我认为这是与编码问题不同的问题。你知道吗
相关问题 更多 >
编程相关推荐