Python 口译员中的口译员

Python Interpreter within Interpreter

所以我正在学习 Python subprocess 模块。使用解释器,我键入 subprocess.call("python") 并在现有解释器中打开另一个解释器,事情变得很奇怪。在打字时,我注意到有些字符没有正确回显,我不得不反复输入它们。此外,普通的回车键(或 returns)在屏幕上添加的不仅仅是人字形。这是输出的一部分:

有人可以解释一下发生了什么吗?我知道这个问题可能过于宽泛或含糊,但我无法在这里具体说明。

我会尽量让它直接重现,这样你就可以看到碰撞。

  1. python
  2. import os; os.getpid(); # 我们需要这个,把它放到剪贴板什么的

    296236 # for me

  3. import subprocess

  4. subprocess.Popen('python')

<subprocess.Popen object at somewhere_over_the_rainbow> # object is created, python probably waits for a chance to push it to the console as a command "python"

>>>

  1. <import&get pid>

296236 # the command is pushed, the new process spawned

您在当前打开的控制台中生成了另一个 Python 进程,已经 等待输入。 "child" 进程现在存在但仍然不能要求获得输入,因为主要进程仍然是 "on the turn"。把它想象成一个队列。 import os;os.getpid() 现在的输出仍然是主进程的 PID, 现在 轮到子进程了。

  1. <import&get pid>

296236

>>> Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. # from second process, it did its stuff in its turn, now main process wants to talk

  1. <import&get pid> # 在主进程中

296236

  1. <import&get pid> # 在第二个进程中

296800

  1. <import&get pid> # 在主进程中

296236

  1. <import&get pid> #在第二个过程中

296800

...一次又一次交替。当您想 exit() 时,乐趣就开始了,因为对输入的争夺仍在继续:

  1. import os;os.getpid();exit() #在第二个进程中

296800

and a clean empty line

  1. import os;os.getpid();exit() #在主进程中

296236

C:\some folder>

基本上它在队列中争夺一个 IO 操作,因为你在做一些愚蠢的事情。如果你需要使用它,只需解释一个文件,绝对不是在一个已经打开的解释器中,而是在一个单独的文件中。例如:

main.py

import subprocess
subprocess.Popen('python other.py')

other.py

print('hello')
exit()

控制台

python main.py