检测另一个Python进程是否正在写入文件

检测另一个Python进程是否正在写入文件,python,file,Python,File,我有两个Python进程A和B,它们都试图写入同一个文件。在A到达f=open(“xx.txt”,“w”)之后,在关闭文件之前,我希望另一个进程能够检测到xx.txt正在使用 我在进程B中尝试了f=open(“xx.txt”,“w”),但没有抛出任何异常。我还尝试了os.access(“xx.txt”,os.W\u OK)在B中,它返回True 我知道我可以使用一些文件锁库,如或。但我想知道是否有任何简单的解决方案不依赖于这些库让我检测它 编辑: 我找到了一个可能的解决方案: 使用os.open

我有两个Python进程
A
B
,它们都试图写入同一个文件。在
A
到达
f=open(“xx.txt”,“w”)
之后,在关闭文件之前,我希望另一个进程能够检测到
xx.txt
正在使用

我在进程
B
中尝试了
f=open(“xx.txt”,“w”)
,但没有抛出任何异常。我还尝试了
os.access(“xx.txt”,os.W\u OK)
B
中,它返回
True

我知道我可以使用一些文件锁库,如或。但我想知道是否有任何简单的解决方案不依赖于这些库让我检测它

编辑: 我找到了一个可能的解决方案:

使用os.open打开文件:

open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
fd = os.open( "xx.txt", open_flags )
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
fd = os.open( "xx.txt", open_flags )
如果文件已经存在,我们可以得到异常:

open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
>>> fd = os.open( "xx.txt", open_flags )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'xx.txt'
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
>>> fd = os.open( "xx.txt", open_flags )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'xx.txt'
open_flags=(os.O_create | os.O_EXCL | os.O_WRONLY)
>>>fd=os.open(“xx.txt”,打开标志)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
OSError:[Errno 17]文件存在:“xx.txt”

一个丑陋的解决方案是在打开文件之前重命名文件,并在处理后重新命名。如果重命名有效,则表示其他进程没有使用它。如果重命名失败,则表示文件已重命名,因此当前正在使用


更好的解决方案是使用另一种进程间通信方法(管道、共享内存等),如果需要持久性,则使用一个简单的数据库,如sqlite。

我找到了一个可能的解决方案(在我的情况下,文件只需编写一次):

使用os.open打开文件:

open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
fd = os.open( "xx.txt", open_flags )
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
fd = os.open( "xx.txt", open_flags )
如果文件已经存在,我们可以得到异常:

open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
>>> fd = os.open( "xx.txt", open_flags )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'xx.txt'
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
>>> fd = os.open( "xx.txt", open_flags )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'xx.txt'
open_flags=(os.O_create | os.O_EXCL | os.O_WRONLY)
>>>fd=os.open(“xx.txt”,打开标志)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
OSError:[Errno 17]文件存在:“xx.txt”
可能重复@taesu:这个问题是“检查文件是否未打开”,我的问题是“检查文件是否正在写入”。他们是不同的。在这个问题上,没有人提到使用
os.open
的答案。