In Ipython, how can I pass arguments to a cell as though it were its own script?
Asked Answered
R

0

4

For instance, say I have some snippet of self-contained code in a cell,

In [1]
from sys import argv
print(argv[1])

I want to be able to pass a value to the code in that cell, presumably through magic, so that

In [2]
%expelliarmus "In [1]" 69105

outputs

69105

Is there any simple way for me to do this, ideally without having to write the cell to my disk as a script?

Edit: I can't just wrap it in a function because in the notebook I'm working in (not the example I posted above) I'm trying to test stuff out with the argparse module.

Ronnaronnholm answered 4/8, 2016 at 0:52 Comment(7)
What would prevent you from simply wrapping whatever is in cell 1 in a function def cell_one(x): ... then simply calling that from cell two?Crossbeam
Because I'm testing the argparse module; that wouldn't work with a function.Ronnaronnholm
I think you misunderstand the utility of IPython. You won't use it with argparse because you're not writing a command-line script.Risotto
The whole point of having an interactive environment is to be able to test things. I'm not writing a command line script you're right. If I were I'd be using emacs or something. I want to do multiple tests with using the module argparse itself. It's exactly what I'd use a python interpreter for if I were testing uses of any other thing.Ronnaronnholm
Even if there was a way to hack this together, it would be terrible practice. The name of each cell ("execution_count" is the label if you open an ipynb file in a text editor) has no meaning - run the cell again and that number changes. They also aren't necessarily unique - if you save a notebook with output already run, then open it again and re-run some cell block in the middle, it will be numbered "1", even though the first cell from before you saved will also still be numbered "1".Roeser
Could there be some way to persistently label a cell?Ronnaronnholm
I can't imagine how without fundamentally rewriting IPython notebooks. What your asking for reminds me a little of goto on line numbers when I was learning qBasic in middle school, in that your asking the code to do something that isn't consistently defined. It's not something you're going to find in many (any?) modern languages.Roeser

© 2022 - 2024 — McMap. All rights reserved.