Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython: run script starting from a specific line

Tags:

ipython

I am writing my script interactively with IPython. This is what I currently do:

  1. write a chunk of code,
  2. run in ipython with "run -i file_name.py".
  3. make changes and repeat 2 until I think it is OK .
  4. comment out the entire previous chunk.
  5. write new chunk of code that is based on the previous one.
  6. go back to step 2.
  7. ......

Is there more efficient way? Can I start a script from a specific line while using all the variables in current namespace?

like image 283
fast tooth Avatar asked Jul 16 '14 23:07

fast tooth


3 Answers

I'd personally also use the ipython notebook, but you call also use you favorite text editor and always copy out the chunk of code you want to run and use the magic command %paste to run that chunk in the ipython shell. It will take care of indentation for you.

like image 102
Magellan88 Avatar answered Oct 16 '22 06:10

Magellan88


Use the magic of %edit stuff.py (first use) and %ed -p (after the first use) and it will invoke your $EDITOR from inside of ipython. Upon exiting from the editor ipython will run the script (unless you called %ed -x). That is by far the fastest way I found to work in CLI-ipython. The notebooks are nice, but I like having a real editor for code.

like image 25
Marcin Avatar answered Oct 16 '22 04:10

Marcin


Use ipdb ("pip install ipdb" on the command line to install it).

Suppose you want to run script "foo.py" from line 18 to 23. You'll want to start like this:

ipdb foo.py

Now, let's jump to line 18 (i.e., ignore all the lines before the 18th):

ipdb> j 18

Next, we set a breakpoint at line 23 (we don't want to go further):

ipdb> b 23

Finally, let's execute:

ipdb> c

Job done :)

like image 29
lev Avatar answered Oct 16 '22 04:10

lev