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: <a href="https://stackoverflow.com/questions/1009860/command-line-arguments-in-python" rel="nofollow">Command Line Arguments In Python</a>Answer1:
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
If I create
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 : %run test.ipy --flag test ['/usr/bin/ipython3']
If I make a copy with a
In : %run testipy.py --flag test ['testipy.py', '--flag', 'test']
%run ...ipy behaves differently. This is a
ipython issue, not a general Python commandline one.
%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.</blockquote>
In that case, the
test.ipy script is seeing the same
sys.argv as I do when I type:
In : sys.argv Out: ['/usr/bin/ipython3']
So if I modify
sys.argv in the current session, such as by appending a couple of strings:
In : sys.argv += ['--flag','test'] In : sys.argv Out: ['/usr/bin/ipython3', '--flag', 'test'] In : %run test.ipy ['/usr/bin/ipython3', '--flag', 'test']
ipy script now sees them.
So that's the answer - put the commandline arguments in the
sys.argv prior to using
(I've done this sort of fiddling with the
sys.argv when doing advanced things with
In : %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
If I add a
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.