以tas身份运行时python库中open()的意外行为

2024-04-19 17:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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日志文件夹与位于同一目录中应用程序类型


结果

  1. 从SSHpython3/volume1/web/python运行/应用程序类型->;保存的内容会话.txt到日志文件
  2. 从SSH/volume1/web/python运行/运行.sh->;的作用与1相同。
  3. 运行运行.sh文件作为任务(类似cron job)->;不创建日志文件
  4. 当我从open函数中删除encoding='utf-8'语句时,在SSH run correctly中,in task抛出一个异常('ascii'编解码器无法对位置12处的字节0xc3进行解码:序号不在范围内(128))

Tags: 文件pathtxtweb应用程序类型timeos
1条回答
网友
1楼 · 发布于 2024-04-19 17:18:07

我有点困惑,但我猜:^{} defaults to the shell's preferred encoding,而且您的NAS的locale设置与您的本地shell不同。我认为encoding=utf-8是解决当前问题的方法。你知道吗

现在,你说那也不行。我不确定您所说的“不保存任何内容”是什么意思,我猜您的脚本需要将其输出保存到一个文件中,而NAS守护进程没有写入该文件的权限。您没有说明负责保存到磁盘的调用实际上是什么样子的,但我认为这是与编码问题不同的问题。你知道吗

相关问题 更多 >