Adding line breaks in ipython

If introduce a for loop in iPython, or any multi-line command, how do I go back and add lines to it? I ran this:

for row in table.find_all('tr'):
    cells = row.find_all('td')
    for c,cell in enumerate(cells):
        print c,":",cell.get_text().strip()
    try:
        this = cells[0]
        that = cells[1]
        the_docket = cells[2]
        other_thign = cells[3]
        jumble = re.sub('\s+',' ',str(cells[5])).strip()            
    except:
        "Nope"

And realized I need to add a line to it, but I can't just hit "enter" in iPython, b/c that runs the command. So can I edit that multi-line command w/in iPython?


Solution 1:

Been suffering this problem for a while. I just found that when using Ctrl-qCtrl-j (That's lowercase Q, J, no need to hold the shift key) will add a linefeed to an existing IPython edit session.

for li in some_list: print(li)    

Moving the cursor after the colon and pressing Ctrl-qCtrl-j

for li in some_list:
print(li)

IPython: 5.2.1, iTerm2: 3.0.15, macOS: 10.12.6

Solution 2:

The %edit magic function in iPython lets you edit code in your favorite editor and will then execute it as if it was typed directly. You can also edit code you've already typed into the repl since it's stored in a special variable, for example:

In [1]: def foo(x):
   ...:     print x
   ...:     
In [2]: %edit _i1

Solution 3:

There is also a way to add a newline directly in the repl: ctrl-v, ctrl-j

The ctrl-v basically lets you send a control code and then the ctrl-j is the code for a newline (line-feed). It's a bit awkward to type but has the advantage of also working in the regular Python shell as well as in Bash itself.

Edit: At least in iTerm2, you can assign it to a single hotkey as well. I set ctrl-enter to "Send hex codes" of 0x16 0x0a. Could also use cmd-enter or whatever else.