How to add a custom flag to IPython's magic commands? (.ipy files)

允我心安 提交于 2019-12-06 15:59:49

As indicated in the comments, this question isn't just about handling commandline arguments in a Python script. It's about handling them in an .ipy file run via %run.

If I create test.ipy as

import sys
print(sys.argv)

and run it from shell, I see the commandline arguments:

1223:~/mypy$ python3 test.ipy -test foo
['test.ipy', '-test', 'foo']

but from a ipython session, I don't

In [464]: %run test.ipy --flag test
['/usr/bin/ipython3']

If I make a copy with a py name

In [468]: %run testipy.py --flag test
['testipy.py', '--flag', 'test']

So the %run ...ipy behaves differently. This is a ipython issue, not a general Python commandline one.

================

The %run doc has this point:

There is one special usage for which the text above doesn't apply: if the filename ends with .ipy[nb], the file is run as ipython script, just as if the commands were written on IPython prompt.

In that case, the test.ipy script is seeing the same sys.argv as I do when I type:

In [475]: sys.argv
Out[475]: ['/usr/bin/ipython3']

So if I modify sys.argv in the current session, such as by appending a couple of strings:

In [476]: sys.argv += ['--flag','test']

In [477]: sys.argv
Out[477]: ['/usr/bin/ipython3', '--flag', 'test']

In [479]: %run test.ipy
['/usr/bin/ipython3', '--flag', 'test']

my ipy script now sees them.

So that's the answer - put the commandline arguments in the sys.argv prior to using %run ...ipy.

(I've done this sort of fiddling with the sys.argv when doing advanced things with argparse.)

More ipython magic

In [480]: %run??

shows me both its doc and its code. I can thus see how it is treating a .ipy file special. Since it's so easy to find, I'll refrain from copying it here.

There's another solution - don't try to use the commandline style of coding with ipy files.

If I add a

print(x)

line to that test file, and have an x defined in my Ipython session, I see that print. But I put that same print in a .py, I'll get a Nameerror. When they say the ipy is run as though it were typed in, they mean it. Running an ipy is, in effect, an alternative to %paste from the clipboard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!