解释器交互模式的目的是保持文件打开

2024-10-04 05:26:12 发布

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

如果代码作为脚本运行:

$ 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]

我有两个问题:

  1. 即使open(file)没有指定返回值,解释器交互模式保持文件打开的目的是什么?如果目的是调试目的,有没有这种调试的例子?

  2. 为什么解释器在交互模式下打开文件时会首先出现缩进错误呢?

基于这个评论,我想说的是,我总是尝试使用新的交互模式会话,甚至尝试使用不同的终端(例如xterm),但这确实会引发IndentationError。你知道吗

enter image description here


Tags: 文件devtestimporttime模式sleepopen
1条回答
网友
1楼 · 发布于 2024-10-04 05:26:12

在示例中看不到打开的文件的原因是,在打开文件之后,file对象的引用计数会下降到0,因为结果没有分配给变量,所以文件会立即关闭。你知道吗

在交互模式下不会发生这种情况的原因是,在第二个sleep函数运行时,_变量中保留了对file对象的引用,因此文件保持打开状态。你知道吗

有关_特殊变量的讨论,请参见here。你知道吗

至于问题2,这是不可能发生的。你的支票一定搞错了。如果代码引发IndentationError,则不会运行任何操作。你知道吗

相关问题 更多 >