Ableton Python __init__ 自文件刷新

Ableton Python __init__ self file flush

我正在编写 ableton python 脚本。这个将字符串写入文件:

class LaunchControl(ControlSurface):    

    def __init__(self, c_instance):
        super(LaunchControl, self).__init__(c_instance)

        f = open("d:\members2.txt", "w")
        f.write('START ok\n\n')
        f.flush()

但是这个没有,我在日志中也没有看到任何错误。唯一不同的是最后一行:

class LaunchControl(ControlSurface):    

    def __init__(self, c_instance):
        super(LaunchControl, self).__init__(c_instance)

        f = open("d:\members2.txt", "w")
        f.write('START ok\n\n')
        f.flush()
        self.f = f

我想在 LaunchControl 的其他功能中使用 f class

打开文件是一个坏习惯。如果其他应用程序需要读取或写入同一个文件会怎样?由于您已在写入模式下打开它,因此它被阻止并且在关闭(释放)之前没有其他应用程序可以访问它。

如果您想从多个函数或脚本访问您的文件,请保存文件名:

self.filename = "d:\members2.txt"

需要时打开(然后关闭)它。


建议不要使用 f = open(...)。使用安全关键字 with.

with open("d:\members2.txt", 'w') as f:
    f.write('...')

退出with作用域后,资源(本例中为文件流)自动关闭并释放。即使在抛出异常的情况下,它也是安全关闭的。 python 文档说(强调):

with statement allows the execution of initialization and finalization code around a block of code

此外,您不需要显式刷新文件。退出with块后,文件自动关闭刷新

docs(在 os.fsync 之后):

If you’re starting with a Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.

所以你应该这样做

class LaunchControl(ControlSurface):    

    def __init__(self, c_instance):
        super(LaunchControl, self).__init__(c_instance)

        f = open("d:\members2.txt", "w")
        f.write('START ok\n\n')
        f.flush()
        os.fsync(f.fileno())
        self.f = f