What code can I use to check if Python is running

2019-02-21 11:17发布

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. Thanks, everyone!

5条回答
手持菜刀,她持情操
2楼-- · 2019-02-21 11:43

My suggestion is to get list of all running frames and check if main Idle method would be in there.

def frames(frame = sys._getframe()):
    _frame = frame
    while _frame :
        yield _frame
        _frame = _frame.f_back
import idlelib.PyShell
print(idlelib.PyShell.main.func_code in [frame.f_code for frame in frames()])

the frames function generates frames running at moment of its declaration, so you can check if idle were here.

查看更多
别忘想泡老子
3楼-- · 2019-02-21 11:48

I suggest packing all the code in one function (Python 3):

def RunningIntoPythonIDLE():

    import idlelib.PyShell

    def frames(frame = sys._getframe()):
        _frame = frame
        while _frame :
            yield _frame
            _frame = _frame.f_back

    return idlelib.PyShell.main.__code__ in [frame.f_code for frame in frames()]

So tkinter apps can do its check:

if not RunningIntoPythonIDLE():
    root.mainloop()
查看更多
不美不萌又怎样
4楼-- · 2019-02-21 11:50

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:

import sys

def in_idle():
    try:
        return sys.stdin.__module__.startswith('idlelib')
    except AttributeError:
        return True
查看更多
霸刀☆藐视天下
5楼-- · 2019-02-21 11:52

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.

查看更多
叛逆
6楼-- · 2019-02-21 11:58

I would prefer to do:

import sys
print('Running IDLE' if 'idlelib.run' in sys.modules else 'Out of IDLE')
查看更多
登录 后发表回答