如果代码以脚本形式运行:
$ cat open_sleep.py
import time
open("/tmp/test")
time.sleep(1000)
$ python open_sleep.py
或者我没有交互模式这样做:
$ python -c 'import time;open("/tmp/test");time.sleep(1000)'
没有文件继续打开:
$ ls -la /proc/`pgrep python`/fd
total 0
dr-x------. 2 ack0hole ack0hole 0 Aug 30 14:19 .
dr-xr-xr-x. 8 ack0hole ack0hole 0 Aug 30 14:19 ..
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:19 0 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:19 1 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:19 2 -> /dev/pts/2
$
除非我通过open()
分配变量返回:
$ cat open_sleep.py
import time
o = open("/tmp/test")
time.sleep(1000)
$ python open_sleep.py
OR
$ python -c 'import time;o=open("/tmp/test");time.sleep(1000)'
然后该文件将继续打开::
$ ls -la /proc/`pgrep python`/fd
total 0
dr-x------. 2 ack0hole ack0hole 0 Aug 30 14:21 .
dr-xr-xr-x. 8 ack0hole ack0hole 0 Aug 30 14:21 ..
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:21 0 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:21 1 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:21 2 -> /dev/pts/2
lr-x------. 1 ack0hole ack0hole 64 Aug 30 14:21 3 -> /tmp/test
$
但交互模式并非如此,即使我没有将变量赋给open():
>>> import time;open("/tmp/test");time.sleep(1000)
<open file '/tmp/test', mode 'r' at 0xb7400128>
我仍然可以看到文件保持打开状态:
$ ls -la /proc/`pgrep python`/fd
total 0
dr-x------. 2 ack0hole ack0hole 0 Aug 30 14:16 .
dr-xr-xr-x. 8 ack0hole ack0hole 0 Aug 30 14:16 ..
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:16 0 -> /dev/pts/4
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:16 1 -> /dev/pts/4
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:16 2 -> /dev/pts/4
lr-x------. 1 ack0hole ack0hole 64 Aug 30 14:17 3 -> /tmp/test
$
如果缩进失败:
>>> import time;open("/tmp/test");time.sleep(1000)
File "<stdin>", line 1
import time;open("/tmp/test");time.sleep(1000)
^
IndentationError: unexpected indent
>>>
套接字在没有文件名的情况下保持打开状态:
$ ls -la /proc/`pgrep python`/fd
total 0
dr-x------. 2 ack0hole ack0hole 0 Aug 30 14:38 .
dr-xr-xr-x. 8 ack0hole ack0hole 0 Aug 30 14:38 ..
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:38 0 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:38 1 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:38 2 -> /dev/pts/2
lrwx------. 1 ack0hole ack0hole 64 Aug 30 14:38 3 -> socket:[411151]
我有两个问题:
解释器交互模式保持文件打开的目的是什么,即使open(文件)没有指定返回值?如果目的是调试目的,这个调试的任何一个例子?
为什么即使存在缩进错误,也首先解释交互模式打开文件?
根据评论,我想说我总是尝试使用新的交互模式会话,我甚至尝试使用不同的终端(例如xterm),但它确实引发了IndentationError。
答案 0 :(得分:2)
你没有看到你没有看到它们的例子中的打开文件的原因是在文件打开后,file
的引用计数对象降为0,因为结果未分配给变量,因此文件立即关闭。
在交互模式下不会发生这种情况的原因是,当第二个_
函数运行时,文件对象的引用保留在sleep
变量中,因此文件保持打开状态。
有关_
特殊变量的讨论,请参阅here。
关于问题2,不应该发生。你必须在检查时弄错了。如果您的代码引发IndentationError,则无法运行。