检测 python 脚本何时在 ipython 中交互运行

发布于 2024-07-29 05:02:46 字数 804 浏览 7 评论 0原文

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

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

澄清

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

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

IPython 会话中运行该脚本,例如:

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

有时,我想在已经启动的 脚本中,exit() 调用将导致 ipython 挂起,同时它会询问我是否真的要退出。 这是调试时的一个小烦恼(对我来说太小了,无需关心),但它可能会弄乱分析结果:退出提示包含在分析结果中(如果我在去吃午饭之前开始分析会话,则分析会变得更加困难) 。

我想要的是允许我修改脚本的东西,使其看起来像:

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

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小帐篷 2024-08-05 05:02:46

我偶然发现了以下内容,它似乎对我有用:

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

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

def in_ipython():
    try:
        return __IPYTHON__
    except NameError:
        return False
浪荡不羁 2024-08-05 05:02:46

我比较了我找到的所有方法并制作了结果表。 最好的似乎是这样的:

hasattr(sys, 'ps1')

在此处输入图像描述

如果有人有其他可能不同的场景,请评论,我会添加它

I compared all the methods I found and made a table of results. The best one seems to be this:

hasattr(sys, 'ps1')

enter image description here

If anyone has other scenarios that might differ, comment and I'll add it

一个人的旅程 2024-08-05 05:02:46

文档说 sys.ps1 在非交互模式下不存在。 此外,可以使用 sys.flags(对于 python 2.6+)来检测我们是否使用了 python -i

该脚本检测我们是否以交互方式、非交互方式以及事后模式运行(如果使用 python -i 隐式调用 python 解释器并且用户认为他进入了“,这可能归因于交互模式”交互式”控制台):

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

# IPython recognition is missing; test here if __IPYTHON__ exists, etc.

if hasattr(sys, 'ps1'):
    print("Running interactively.")
else:
    print("Not running interactively...")
    if sys.flags.interactive:
        print("... but I'm in interactive postmortem mode.")

可以按照 Fooz 先生的描述添加 IPython 支持。

Docs say that sys.ps1 doesn't exist in noninteractive mode. Additionally, one can use sys.flags (for python 2.6+) to detect if we have used python -i <whatever>.

This scripts detects if we run interactively, non-interactively, and in post-mortem mode (which may be attributed to interactive mode if python interpreter is called using python -i implicitly and user thinks he landed into "interactive" console):

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

# IPython recognition is missing; test here if __IPYTHON__ exists, etc.

if hasattr(sys, 'ps1'):
    print("Running interactively.")
else:
    print("Not running interactively...")
    if sys.flags.interactive:
        print("... but I'm in interactive postmortem mode.")

IPython support can be added as described by Mr Fooz.

野心澎湃 2024-08-05 05:02:46

当交互调用时,python 将运行 $PYTHONSTARTUP 中的脚本,因此您可以简单地让该环境变量调用一个设置全局变量的脚本

When invoked interactively, python will run the script in $PYTHONSTARTUP, so you could simply have that environment variable invoke a script which sets a global

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文