Skip to main content
 首页 » 编程设计

解释器中的 Python 解释器

2025年02月15日8arxive

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

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

请您参考如下方法:

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

  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 进程,该控制台已经等待输入。 “子”进程现在存在但仍然无法要求获得输入,因为主要进程仍在“轮到”。把它想象成一个队列。 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 操作,因为你在做一些愚蠢的事情。如果你需要使用它,只需解释一个文件,绝对不是在一个已经打开的解释器中,而是在一个单独的文件中。例如:

主.py

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

其他.py

print('hello') 
exit() 

控制台

python main.py