如果代码作为脚本运行:
$ 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(file)未分配返回值,解释器交互模式保持文件打开的目的是什么?如果目的是调试目的,这个调试的例子是什么?
-
为什么解释器交互模式首先打开文件,即使存在缩进错误?
根据评论,我想说,我总是尝试新的交互模式会话,甚至尝试不同的终端(例如xterm),但这确实会引发IndentationError。