检测在ipython中以交互方式运行python脚本的时间 [英] Detecting when a python script is being run interactively in ipython

查看:134
本文介绍了检测在ipython中以交互方式运行python脚本的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让python脚本自动检测它是否以交互方式运行?或者,可以检测是否正在使用ipython而不是常规的c python可执行文件吗?

Is there a way for a python script to automatically detect whether it is being run interactively or not? Alternatively, can one detect whether ipython is being used versus the regular c python executable?

背景:我的python脚本通常会调用exit()。我不时地以交互方式运行脚本以进行调试和分析,通常是在ipython中。当我以交互方式运行时,我想要禁止退出的调用。

Background: My python scripts generally have a call to exit() in them. From time to time, I run the scripts interactively for debugging and profiling, usually in ipython. When I'm running interactively, I want to suppress the calls to exit.

澄清

假设我有一个脚本myscript.py,看起来像:

Suppose I have a script, myscript.py, that looks like:

#!/usr/bin/python
...do useful stuff...
exit(exit_status)

有时,我想在我拥有的IPython会话中运行脚本已经开始了,比如说:

Sometimes, I want to run the script within an IPython session that I have already started, saying something like:

In [nnn]: %run -p -D myscript.pstats myscript.py

在脚本结束时,exit()调用将导致ipython挂起,当它询问我是否我真想退出这是调试时的一个小烦恼(对于我来说太小而无法照顾),但它可能会弄乱分析结果:退出提示包含在配置文件结果中(如果我在开始午餐前开始分析会话,则分析会更难) 。

At the end of the script, the exit() call will cause ipython to hang while it asks me if I really want to exit. This is a minor annoyance while debugging (too minor for me to care), but it can mess up profiling results: the exit prompt gets included in the profile results (making the analysis harder if I start a profiling session before going off to lunch).

我想要的是允许我修改我的脚本所以它看起来像:

What I'd like is something that allows me modify my script so it looks like:

#!/usr/bin/python
...do useful stuff...
if is_python_running_interactively():
    print "The exit_status was %d" % (exit_status,)
else:
    exit(exit_status)


推荐答案

我绊倒了以下内容,它似乎为我做了诀窍:

I stumbed on the following and it seems to do the trick for me:

def in_ipython():
    try:
        __IPYTHON__
    except NameError:
        return False
    else:
        return True

这篇关于检测在ipython中以交互方式运行python脚本的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆