我可以使用什么代码来检查脚本是否在 IDLE 中运行?
正如标题所说。我想编写一个行为不同的脚本,具体取决于它是在控制台窗口内运行还是在空闲状态下运行。是否有一个仅在空闲状态下运行时才存在的对象可供我检查?环境变量?
我在 Windows 上使用 Python 2.6.5 和 2.7。
编辑:
到目前为止给出的答案有效。但我正在寻找一种官方的方法来做到这一点,或者看起来不像黑客的方法。如果有人提出一个,我会接受它作为答案。否则,几天后,我会接受最早的答案。
Just as the title says. I want to write a script that behaves differently depending on whether it's running inside a console window or in IDLE. Is there an object that exists only when running in IDLE that I can check for? An environment variable?
I'm using Python 2.6.5 and 2.7 on Windows.
Edit:
The answers given so far work. But I'm looking for an official way to do this, or one that doesn't look like a hack. If someone comes up with one, I'll accept that as the answer. Otherwise, in a few days, I'll accept the earliest answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我更愿意这样做:
I would prefer to do:
Google 找到了我 this 2003 年的论坛帖子。使用 Python 3.1(适用于 win32)及其附带的 IDLE 版本,命令行中的 len(sys.modules) os 为 47,但 IDLE 中为 122壳。
但为什么你还需要关心呢? Tkinter 代码在使用 IDLE 运行时有一些烦恼(因为后者使用 tkinter 本身),但除此之外,我认为我可以安全地假设您不必关心。
Google found me this forum post from 2003. With Python 3.1 (for win32) and the version of IDLE it comes with, len(sys.modules) os 47 in the command line but 122 in the IDLE shell.
But why do you need to care anyway? Tkinter code has some annoyances when run with IDLE (since the latter uses tkinter itself), but otherwise I think I'm safe to assume you shouldn't have to care.
我建议将所有代码打包在一个函数中(Python 3):
这样 tkinter 应用程序就可以进行检查:
I suggest packing all the code in one function (Python 3):
So tkinter apps can do its check:
我有点晚了,但由于 IDLE 用自定义对象替换了标准流(并且已记录),可以检查这些以确定脚本是否在 IDLE 中运行:
I'm a touch late, but since IDLE replaces the standard streams with custom objects (and that is documented), those can be checked to determine whether a script is running in IDLE:
我的建议是获取所有正在运行的帧的列表,并检查主要的 Idle 方法是否在其中。
Frames 函数生成在声明时运行的帧,因此您可以检查此处是否空闲。
My suggestion is to get list of all running frames and check if main Idle method would be in there.
the frames function generates frames running at moment of its declaration, so you can check if idle were here.