回答編集履歴

1

改良案を追加

2019/06/26 05:15

投稿

mather
mather

スコア6753

test CHANGED
@@ -5,3 +5,109 @@
5
5
  エラーメッセージをよく読んでください。 `str` 型の値には `fileno` という属性が無いですよ、と書いてあります。
6
6
 
7
7
  `fname.fileno()` でミスってませんか?
8
+
9
+
10
+
11
+ ----
12
+
13
+ 追記(2019-06-26)
14
+
15
+
16
+
17
+ ```
18
+
19
+ Traceback (most recent call last):
20
+
21
+ File "aaa_write_first.py", line 24, in <module>
22
+
23
+ main()
24
+
25
+ File "aaa_write_first.py", line 20, in main
26
+
27
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
28
+
29
+ ValueError: I/O operation on closed file
30
+
31
+ ```
32
+
33
+
34
+
35
+ こちらのエラーについては `with` でファイルを開いており、そのスコープ外で `f.fileno()` を参照しようとしているのでファイルが閉じられている、というのが原因かと思います。
36
+
37
+ 以下のような方法だと別プロセスからファイルが削除されていたとしてもアンロックでエラーは発生しませんでした。(それはそれでどうなの、というのもありますが)
38
+
39
+
40
+
41
+ ```python
42
+
43
+ import fcntl
44
+
45
+ import time
46
+
47
+
48
+
49
+ try:
50
+
51
+ f = open("sample.txt", "w")
52
+
53
+ print("sample.txt opened.")
54
+
55
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
56
+
57
+ print("sample.txt locked.")
58
+
59
+ time.sleep(60)
60
+
61
+
62
+
63
+ finally:
64
+
65
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
66
+
67
+ print("sample.txt unlocked.")
68
+
69
+ f.close()
70
+
71
+ print("sample.txt closed.")
72
+
73
+ ```
74
+
75
+
76
+
77
+ ファイル削除の方も一旦開いて、削除してからクローズ、という形で問題ありません。
78
+
79
+
80
+
81
+ ```python
82
+
83
+ import fcntl
84
+
85
+ import os
86
+
87
+
88
+
89
+ try:
90
+
91
+ f = open("sample.txt", "r")
92
+
93
+ print("sample.txt opened.")
94
+
95
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
96
+
97
+ print("sample.txt locked.")
98
+
99
+ os.remove("sample.txt")
100
+
101
+ print("sample.txt removed.")
102
+
103
+ finally:
104
+
105
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
106
+
107
+ print("sample.txt unlocked.")
108
+
109
+ f.close()
110
+
111
+ print("sample.txt closed.")
112
+
113
+ ```