两个python脚本用互斥的txt文件编写,互不线程化

2024-04-20 07:03:24 发布

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

我有两个脚本运行在同一台机器上的python中,它们不断地监视一些值。 他们通过文件.txt在

B向a添加消息文件.txt所以它们堆积起来了。当A检查文件.txt它读入并清空文件.txt在

A

while true:
    Open file.txt if B is not using it or when B is done
    f = open('file.txt', 'r+') 
    message=f.read()    #read all the messages that have accumulated
    f.truncate()        #delete the messages 
    f.close()

    ---use message do other things

B

^{pr2}$

问题是我想打开每个脚本文件.txt只有当另一个不使用它时,或者等待它停止使用。所以,当B在写,A想读的时候,B会停一会儿,然后继续。在

没有必要将两者同步。实际上,我希望它们是独立的,而不是线程或并行运行。 例如,B可以进入循环,而A只能循环一次,反之亦然。或者,如果A由于某种原因被延迟,消息就会堆积起来文件.txt因为B继续运行。在

我读过关于锁文件的文章。是否可以在每个脚本中执行以下操作:

A
if "file locked by B":
    wait for unlock

lock file 
open file
read from file
empty file 
close file
unlock file

“等待解锁”、“文件被B锁定”和“锁定文件”会使用什么工具?在


Tags: 文件thetxt脚本机器消息messageclose