Skip to main content
 首页 » 编程设计

python之检测 IPython Pylab GUI 事件循环是否处于事件状态

2025年05月04日24pengyingh

如果使用--pylab=... 或--gui=... 等选项调用IPython,是否有一种规范的方法来检测解释器内部?

原因: 我想在一个单独的进程中进行一些异步绘图,如示例脚本 tst_process.py 所示:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
""" File tst_process.py """ 
# For better Python 3 compatibility: 
from __future__ import absolute_import, print_function, unicode_literals, \ 
                       division 
 
import matplotlib.pylab as plt 
from multiprocessing import Process 
import numpy as np 
 
def tst_plot(fgoff=0): 
    """ Make a test plot """ 
    print("Drawing figure {}".format(1+fgoff)) 
    x = np.linspace(0, 5, 500) 
    fg = plt.figure(1+fgoff) 
    fg.clf() 
    ax = fg.add_subplot(1, 1, 1) 
    ax.plot(x, np.sin(x)) 
    ax.set_title("This is a Test-Plot") 
    fg.canvas.draw() 
    plt.show() 
 
 
if __name__ == "__main__": 
 
    print("Doing testplot in new process ...") 
    pprc1 = Process(target=tst_plot) 
    pprc1.start() 
    print("Doing testplot in own process ...") 
    tst_plot(10) 

当我用命令运行它时

ipython --i tst_process.py 

一切正常。正在做:

ipython --pylab=qt --i tst_process.py  

给出:

Python 2.7.9 (default, Dec 11 2014, 08:58:12)  
Type "copyright", "credits" or "license" for more information. 
 
IPython 2.3.0 -- An enhanced Interactive Python. 
?         -> Introduction and overview of IPython's features. 
%quickref -> Quick reference. 
help      -> Python's own help system. 
object?   -> Details about 'object', use 'object??' for extra details. 
Doing testplot in new process ... 
Doing testplot in own process ... 
Drawing figure 11 
Drawing figure 1 
 : Fatal IO error: client killed 
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14 
  Major opcode: 1 (X_CreateWindow) 
  Resource id:  0x6a00003 
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14 
  Extension:    139 (RENDER) 
  Minor opcode: 4 (RenderCreatePicture) 
  Resource id:  0x6a00004 
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14 
  Major opcode: 1 (X_CreateWindow) 
  Resource id:  0x6a00005 
[xcb] Unknown sequence number while processing queue 
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called 
[xcb] Aborting, sorry about that. 
python: ../../src/xcb_io.c:274: poll_for_event: Zusicherung »!xcb_xlib_threads_sequence_lost« nicht erfüllt. 
Abgebrochen 

除 wx 之外的其他后端也无法正常工作。

我检测到事件循环的存在就足够了。然后我可以使用相同的脚本从命令行和 Spyder 内部运行。

请您参考如下方法:

回答您最初的问题:如果使用 --pylab=... 或 --gui=... 等选项调用 IPython,是否有一种规范的方法可以在解释器内部进行检测?

是的,有。最简单的方法是检查命令行参数:

import sys 
print sys.argv # returns the commandline arguments 
# ['ipython', '--pylab', 'inline'] 

更好的方法是使用内置模块 optparse .

但是,这将只允许您根据命令行参数查看它正在运行的模式——这是您的主要问题。它不会帮助您解决 gui 事件外观 + 多进程问题 @tcaswell评论中提到。