shell运行还是从命令行运行

shell运行还是从命令行运行

本文介绍了检测python脚本是从ipython shell运行还是从命令行运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测python脚本是从python或ipython shell运行,还是从命令行运行,例如 python scrip.py

Is there any way to detect if a python script is being run from an python or ipython shell, or being run from the command line using for example python scrip.py?

我想用它来设置我的matplotlib环境,并根据脚本的运行方式保存或显示数字。当我从命令行运行绘图脚本时,我希望脚本使用非标准的matplotlib后端并将该图保存到文件中,其中包含 plt.savefig() ,但如果我使用 In [1]在ipython shell中运行它:运行scrip.py ,我想用显示数字plt.show()

I want to use this to set up my matplotlib environment and save or display a figure depending on how the script is run. When I'm running the plotting script from the command line I want the script to use a non-standard matplotlib backend and save the figure to a file with plt.savefig(), but if I'm running it from inside an ipython shell using In [1]: run scrip.py, I want to display the figure using plt.show().

这样的事情:

import matplotlib
if run_from_command_line:
    matplotlib.use("non-standard-backend")

import matplotlib.pyplot as plt
if run_from_interactive_shell:
    plt.ion() // Turn on interactive mode in matplotlib

// Do plotting

if run_from_command_line:
    plt.savefig(filename)
else:
    plt.show()


推荐答案

方法1

在IPython中运行时,有一个名为<$的全局变量集C $ C> __ IPython的__ 。您可以检查是否存在以下内容:

When running in IPython there is a global variable set called __IPYTHON__. You can just check to see if this exists with:

try:
    __IPYTHON__
except NameError:
    print "Not in IPython"
else:
    print "In IPython"

方法2

因此指出你还可以查找 get_ipython 函数你的脚本不仅要检查你是否从IPython运行,还要检查IPython的配置。

As this thread points out you can also look for the get_ipython function in your script to not only check if you are running from IPython, but also to check what configuration IPython has.

方法3

您还可以使用模块来检查堆栈并找出你是否从交互式解释器等运行。

You can also use the inspect module to inspect the stack and find out if you are running from the interactive interpreter etc.

所以一个示例文件:

# test.py
import inspect

for frame in inspect.stack():
    print frame

从<$>命令行运行时c $ c> python test.py 输出为:

(<frame object at 0x100378530>, 'test.py', 3, '<module>', ['for frame in inspect.stack():\n'], 0)

当来自交互式口译员的 execfile 'd时:

When execfile'd from the interactive interpreter:

>>> execfile( "test.py" )
(<frame object at 0x1003795e0>, 'test.py', 3, '<module>', ['for frame in inspect.stack():\n'], 0)
(<frame object at 0x100379430>, '<stdin>', 1, '<module>', None, None)

在IPython中运行时:

When run within IPython:

In [1]: %run test
(<frame object at 0x1029002a0>, '/Users/ebarr/Scripts/SO/test.py', 3, '<module>', ['for frame in inspect.stack():\n'], 0)
(<frame object at 0x102900020>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/utils/py3compat.py', 224, 'execfile', ['            builtin_mod.execfile(filename, *where)\n'], 0)
(<frame object at 0x101d78e20>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2537, 'safe_execfile', ['                py3compat.execfile(fname,*where)\n'], 0)
(<frame object at 0x101d78c30>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/magics/execution.py', 703, 'run', ['                                       exit_ignore=exit_ignore)\n'], 0)
(<frame object at 0x101d76390>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/magics/execution.py', 717, 'run', ['                            run()\n'], 0)
(<frame object at 0x101d61760>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/magic.py', 193, '<lambda>', ['        call = lambda f, *a, **k: f(*a, **k)\n'], 0)
(<frame object at 0x101d761a0>, '<string>', 2, 'run', None, None)
(<frame object at 0x101d603e0>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2126, 'run_line_magic', ['                result = fn(*args,**kwargs)\n'], 0)
(<frame object at 0x101d5f1f0>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2205, 'magic', ['        return self.run_line_magic(magic_name, magic_arg_s)\n'], 0)
(<frame object at 0x101d75e40>, '<ipython-input-1-59a1e9768ae2>', 1, '<module>', [u"get_ipython().magic(u'run test')\n"], 0)
(<frame object at 0x101d75990>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2883, 'run_code', ['                exec(code_obj, self.user_global_ns, self.user_ns)\n'], 0)
(<frame object at 0x101d75760>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2833, 'run_ast_nodes', ['                if self.run_code(code):\n'], 0)
(<frame object at 0x101d71950>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2741, 'run_cell', ['                                   interactivity=interactivity, compiler=compiler)\n'], 0)
(<frame object at 0x101d6ce10>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/terminal/interactiveshell.py', 567, 'interact', ['                    self.run_cell(source_raw, store_history=True)\n'], 0)
(<frame object at 0x101d6c870>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/terminal/interactiveshell.py', 443, 'mainloop', ['                    self.interact(display_banner=display_banner)\n'], 0)
(<frame object at 0x101716d60>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/terminal/ipapp.py', 371, 'start', ['            self.shell.mainloop()\n'], 0)
(<frame object at 0x1017006f0>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/config/application.py', 563, 'launch_instance', ['        app.start()\n'], 0)
(<frame object at 0x1014fbdd0>, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/__init__.py', 118, 'start_ipython', ['    return launch_new_instance(argv=argv, **kwargs)\n'], 0)
(<frame object at 0x100378560>, '/Library/Frameworks/Python.framework/Versions/2.7/bin/ipython', 11, '<module>', ['    sys.exit(start_ipython())\n'], 0)

这篇关于检测python脚本是从ipython shell运行还是从命令行运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:26