在Python

时间:2017-03-16 13:35:51

标签: python shell ipython

我希望能够判断我是否在交互式python shell中。我使用的定义是,如果用户可以输入命令(python从stdin读取),则用户在交互式python shell中。

到现在为止,我想出了以下脚本:

def detect_interactive():
"""Try to import interactive code. If it fails, we're either in_units
    no interactive ipython mode or in regular python mode"""
    import sys

    # IPython recognition is missing; test here if __IPYTHON__ exists, etc.
    if hasattr(sys, 'ps1'):
        # Running interactively
        is_interactive = True
    else:
        # Not interactive
        is_interactive = False
        if sys.flags.interactive:
            print("... but I'm in interactive postmortem mode.")

    # When running using IPython, it is always detected as being interactive!
    try:
        __IPYTHON__  # IPython specific code
        print('IPython detected')
    finally:
        print('interactive status:', is_interactive)
        return is_interactive

适用于常规python。但是,无论我是使用ipython myscript.py调用此脚本还是从In [1]: %run detect.py等IPython shell运行它,我都会激活is_interactive标志。

所以我的问题是:如何检测IPython的交互模式?

0 个答案:

没有答案