在Python中检测交互式shell
我想知道我是否在一个交互式python shell中。我使用的定义是,如果用户可以输入命令(python正在从stdin读取),那么用户就在交互式python shell中 到目前为止,我想出了以下脚本:在Python中检测交互式shell,python,shell,ipython,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 pytho
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
调用此脚本,还是从类似[1]:%run detect.py的ipython shell运行此脚本,我始终会激活is_interactive标志
所以我的问题是:如何检测IPython的交互模式?我觉得这可能是一个XY问题。为什么你想知道你是否在一个交互式shell中?我正在使用一个工具()自动记录任何输入/输出,并将其记录到数据库中。对于从命令行运行的脚本,我希望它自动激活自己。在交互式评估的情况下,我不希望它记录我产生的所有垃圾,因此我需要能够判断我是否在交互式shell中,以停用自动设置。我觉得这可能是一个XY问题。为什么你想知道你是否在一个交互式shell中?我正在使用一个工具()自动记录任何输入/输出,并将其记录到数据库中。对于从命令行运行的脚本,我希望它自动激活自己。在交互式评估的情况下,我不希望它记录我产生的所有垃圾,因此我需要能够判断我是否在交互式shell中,以停用自动设置。