1

We can use %run to execute a python script inside ipython console (not notebook). However, is there a way we can run the script and have each line of script load and execute as one cell of ipython input. For e.g. if the script is:

if a == b:
  print 2*a

if a == 2*b:
  print a

Then inside of ipython the script must load (and execute) like so:

In [1]: if a == b:
   ...:     print 2*a
   ...:

In [2]: if a == 2*b:
   ...:     print a
   ...:

I don't know if this is even possible, but if so, it will be really helpful as I can load the script and then execute whichever portion of code that I want to execute. A follow up question would be whether we can load the source code of an imported module recursively (like stepping inside a debugger). That way we can make develop and test from within ipython itself, without executing the entire code from scratch (since ipython saves state per cell).

tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72
  • 3
    If using iPython/Jupyter notebook you can copy+paste whole/partial scripts into the cells and run in whatever order you like. My $0.02: I typically develop in iPython cell's then move to standalone scripts once the code is proven to work. – tmthydvnprt May 13 '15 at 02:13

3 Answers3

1

You can try out following thing,
!python filename.py

There is another option also, you can copy paste your code into ipython using %cpaste and at the end ctrl+d to exit from
%cpaste

%edit
in ipython allows to type code, and saved in /tmp/ipython_edit_3xhsby0h/ipython_edit_*.py after exiting from the edit mode it executes the list of lines written in above file use :q to quit from the edit mode
And to go in debug mode you can try out this
python -m pdb filename.py

abhijeetmote
  • 131
  • 1
  • 10
0

Yes, I believe that this question provides an answer. To summarize, you want to use the magic command %load.

If you execute a cell containing:

%load filename.py

the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

Community
  • 1
  • 1
Ben
  • 61
  • 5
0

Go to script, ctrl+A then ctrl+c, go to terminal,type %paste Script is pasted and run

A.Raouf
  • 2,171
  • 1
  • 24
  • 36