我有兩個Python進程A
和B
,並且都試圖寫入同一個文件。在A
達到f = open("xx.txt", "w")
之後,在關閉文件之前,我希望其他進程有辦法檢測到xx.txt
正在使用中。檢測是否有另一個Python進程正在寫入文件
我試過f = open("xx.txt", "w")
正在處理B
但它沒有拋出任何異常。我也試過os.access("xx.txt", os.W_OK)
在B
,它返回True
。
我知道我可以使用一些文件鎖定庫,如lockfile或fcntl。但我想知道是否有任何簡單的解決方案,而不依賴於這些庫來檢測它?
編輯: 我發現了一個可能的解決方案:
使用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)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'xx.txt'
可能重複[檢查一個文件是否在Python中未打開(未由其他進程使用)](http://stackoverflow.com/questions/11114492/check-if-a-file-is-not-open-not-used-by-by-other-process-in-python) – taesu
@taesu:這個問題是針對「檢查文件是否打開」,以及我的問題是「檢查文件是否正在寫入」。他們是不同的。沒有人提到在這個問題中使用'os.open'的答案。 – stanleyli