Is it possible to add a custom flag to IPython's magic command? To be more specific, I want to use the %run command with a homemade flag:
%run script.ipy --flag "option"
and be able to use "option" inside the script.
For .py files, the answer is provided here: Command Line Arguments In Python
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.
来源:https://stackoverflow.com/questions/38210320/how-to-add-a-custom-flag-to-ipythons-magic-commands-ipy-files