Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

interactive - Detecting when a python script is being run interactively in ipython

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?

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.

Clarification:

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

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

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...