如果使用--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内部运行。
答案 0 :(得分:1)
回答原始问题:Is there a canonical way of detecting inside the interpreter if IPython was called with options like--pylab=... or --gui=...?
是的,有。最简单的方法是检查命令行参数:
import sys
print sys.argv # returns the commandline arguments
# ['ipython', '--pylab', 'inline']
更好的方法是使用内置模块optparse。
但是,这只会让您根据命令行参数查看它运行的模式 - 这是您的主要问题。它不会帮助您解决gui事件外观+多处理问题,如评论中提到的@tcaswell。
答案 1 :(得分:0)
您可以使用
检查qt事件循环是否正在运行import PyQt4.QtCore
if PyQt4.QtCore.QCoreApplication.instance():
print("Event loop detected")
PS:为了更精细地检查事件循环何时开始,您可以使用应用程序startingUp方法。