忽略python中的IPython魔术 [英] Ignore IPython magic in python

查看:72
本文介绍了忽略python中的IPython魔术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python解释器运行脚本时,忽略IPython魔术的最佳方法是什么?

What is the best way to ignore IPython magic when running scripts using the python interpreter?

我经常在脚本文件中包含IPython magic,因为它与代码交互工作.例如,使用autoreload魔术,在进行一些更改并修复错误之后,我不必保持reload -inging这些模块:

I often include IPython magic in my script files because it work with the code interactively. For example, with the autoreload magic, I don't have to keep reload-ing the modules after I make some changes and fix bugs:

%load_ext autoreload
%autoreload 2

但是,当我尝试使用常规的python解释器运行此脚本时,出现错误:

However, when I try to run this script using a usual python interpreter, I get an error:

  File "<string>", line 1
    %load_ext autoreload
    ^
SyntaxError: invalid syntax

if语句中包装IPython魔术不起作用,因为在实际运行文件之前检测到错误的语法.

Wrapping IPython magic inside an if statement does not work, because incorrect syntax is detected before the file is actually ran.

那么让python忽略IPython魔术的最佳方法是什么?

So what is the best way to get python to ignore IPython magic?

每次在python,pdb,sphinx等中运行时都必须更改脚本,这很烦人.

It's annoying to have to change your scripts whenever you want to run then in python, pdb, sphinx, etc.

推荐答案

对于所有可以从标准输入中读取的工具,您可以使用grep删除任何魔术线并将结果通过管道传递到python中:

For all tools that can read from standard input you could use grep to remove any magic lines and pipe the result into python:

grep -v '^%' magicscript.ipy | python

作为bash别名很好用:

Works well as a bash alias:

alias pynomagic='( grep -v "^%" | python ) < '
pynomagic magicscript.ipy

像pdb这样仅接受文件名的工具可以这样调用(再次重击):

Tools like pdb that only accept filenames could be called like this (bash again):

pdb <(grep -v '^%' magicscript.ipy)

这篇关于忽略python中的IPython魔术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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