Ipython. How to continue code on the next line? - ipython

I've recently installed Ipython version 7.0.1 and I can't figure how to continue writing code on the next line.
E.g. the following executes upon pressing enter after the print statement.
def greeting():
print("hi")
My previous version would have given me an indented newline, and upon pressing enter again(leaving the prior line blank) would then execute. I could then continue to write code within the function such as:
def greeting():
print("hi")
lst = []
return lst
As it stands, I am simply unable to enter the second version of my function into ipython because it executes after the print statement.
; and \ do not work.
E.g.
def greeting():
print("hi")\
def greeting():
print("hi");

As of version 7.1.1 this issue appears to have been resolved. I was on version 7.0.1.
pip install ipython --upgrade

Related

How do I cleanly remove fzf integration from fish?

I installed fzf (https://github.com/junegunn/fzf#fish-shell) using brew on Mac. The other day I removed it using brew.
Now I get the following message whenever I open a fish shell:
fish:
fzf_key_bindings
^
in function '__original_fish_user_key_bindings'
called on line 46 of file ~/.local/share/omf/init.fish
in function 'fish_user_key_bindings'
in function '__fish_reload_key_bindings'
called on line 228 of file /usr/local/Cellar/fish/3.1.2/share/fish/functions/__fish_config_interactive.fish
in function '__fish_config_interactive'
called on line 170 of file /usr/local/Cellar/fish/3.1.2/share/fish/config.fish
in function '__fish_on_interactive'
in event handler: handler for generic event 'fish_prompt'
How do I cleanly remove the fzf integration from here?
fzf installs itself in fish shell by appending to fish_user_key_bindings.
You can remove its integration by editing ~/.config/fish/functions/fish_user_key_bindings.fish and deleting the call to fzf_key_bindings.
If you have installed fzf by running its install script, you can also run its uninstall script of course.

problems exiting from Python using iPython/Spyder

This question has been asked before, but I have tried the solutions in related questions such as this to no avail.
I am having problems with Python's exit command, and I have ruled out a problem with my code as run by vanilla Python 3. The problem comes when I run it with iPython or in Spyder's iPython console.
When I use just a simple exit command, I get the error:
NameError: name 'exit' is not defined
I have already imported sys as suggested by the other link. The only thing that kind of works is to try sys.exit() in which case I get:
An exception has occurred, use %tb to see the full traceback.
SystemExit
C:\Users\sdewey\AppData\Local\Continuum\Anaconda3\lib\site-
packages\IPython\core\interactiveshell.py:2870: UserWarning: To exit: use
'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
I only say that that "kind of works" because the error message is smaller so it's less annoying :).
Any ideas? Seems like an issue with iPython. I have encountered a different issue in Jupyter (which uses iPython) where quit was ignored entirely, which I posted about separately here
I've run into the same issue while running scripts containing exit() in Pycharm's IPython shell.
I learned here, that exit is intended for interactive shells, so behaviour will vary depending on how the shell implements it.
I could figure out a solution which would...
not kill the kernel on exit
not display a traceback
not force you to entrench code with try/excepts
work with or without IPython, without changes in code
Just import 'exit' from the code beneath into scripts you also intend to run with IPython and calling 'exit()' should work. You can use it in jupyter as well (instead of quit, which is just another name for exit), where it doesn't exit quite as silent as in the IPython shell, by letting you know that...
An exception has occurred, use %tb to see the full traceback.
IpyExit
"""
# ipython_exit.py
Allows exit() to work if script is invoked with IPython without
raising NameError Exception. Keeps kernel alive.
Use: import variable 'exit' in target script with 'from ipython_exit import exit'
"""
import sys
from io import StringIO
from IPython import get_ipython
class IpyExit(SystemExit):
"""Exit Exception for IPython.
Exception temporarily redirects stderr to buffer.
"""
def __init__(self):
# print("exiting") # optionally print some message to stdout, too
# ... or do other stuff before exit
sys.stderr = StringIO()
def __del__(self):
sys.stderr.close()
sys.stderr = sys.__stderr__ # restore from backup
def ipy_exit():
raise IpyExit
if get_ipython(): # ...run with IPython
exit = ipy_exit # rebind to custom exit
else:
exit = exit # just make exit importable
You can use system warnings to set those warning that you do not need as ignored. Example:
the function that you call from somewhere else:
def my_function:
statements
if (something happened that you want to exit):
import warnings
warnings.filterwarnings("ignore")
sys.exit('exiting...')

Python 'unexpected EOF while parsing' eclipse pydev run selected code

If I select the following code and click "Run selected Code" in eclipse, it will give me an error.
class abc(object):
def __init__(self):
print 'base'
def run(self):
print 'run'
Error message:
class abc(object):
def __init__(self):
print 'base'
def run(self):
print 'run'
File "<ipython-input-22-8e1ec627fd90>", line 1
def run(self):
^
SyntaxError: unexpected EOF while parsing
run
However, if I remove the space between the two functions then it will run Ok(see below), is this a bug in pydev? Any way I can over come this issue?
class abc(object):
def __init__(self):
print 'base'
def run(self):
print 'run'
Versions:
Eclipse 4.4.2
LiClipse 2.0.0.201504092214
Subclipse (Required) 1.10.13
I think what you're seeing is the result of using the interactive console to run your code (i.e.: http://www.pydev.org/manual_adv_interactive_console.html).
The issue is that when you send the code to the console through that action, it won't do any edit to your code, and when the console sees a line with 0-width, it'll conclude that the Python block is finished.
So, there are some workarounds for that:
Don't right-trim your blocks (i.e.: leave spaces to the block indent instead of a 0-width line).
If you don't want to run just a section of your code, deselect all the code and execute the whole file with Ctrl+Alt+Enter.
Deselect the code, go to the first line and send the contents to the console line-by-line with F2 (F2 will send the current line and will move the cursor to the next line with contents and may even fix the indents, so, it should be easy to select the block you want to send to the console).
Don't use the interactive console and do a plain run with F9 (although in this case as it'll launch in a new non-interactive console, the symbols won't be available for inspection afterwards).
If you work using TDD (test driven development), then run the test code with Ctrl+F9 (see http://www.pydev.org/manual_adv_pyunit.html for details) -- again, in this mode it won't be using the interactive console.

Is there an IPython equivalent to Bash's semicolon?

I use IPython as my interactive shell and I almost always run two commands at the start - something like:
%run helper_functions.py
data = import_data('file_with_data')
I would like a notation to run these two at the same time (so I could recall them with an "up" arrow from history) akin to what echo 1 ; echo 2 does in Bash.
I am aware that I can start IPython running with a script as per How can I start IPython running a script?.
Semicolon is a valid statement separator in Python, the same as the newline, so you can use it with regular commands:
a=5; a=a+1; print "This is a: %s" % a
Anyway, as pointed out by tobias_k, this is not working with "run" which is a special IPython macro (see the IPython built-in magic commands) and changes the command line interpretation. Instead of %run helper_functions.py; data = import_data('file_with_data'), you could use something almost equivalent:
__builtin__.execfile('helper_functions.py') ; data = import_data('file_with_data')
You don't have the trace in IPython, but still your script is executed and the variables are in your interactive namespace.

Tab completion with Python's Cmd.cmd

After testing a while with the Cmd.cmd framework in python, I noticed a problem I don't know what to do about. Plus I believe to have this working some hours before (or I'm just crazy), so this is even more weird.
I have the following example code, tested on both Windows and Linux systems (so it's not a Windows problem), but tab completion simply doesn't work.
If I use the exact same code in Python 2 it does work on the Linux system (not on the Windows one though)
import cmd
class Shell ( cmd.Cmd ):
def do_test ( self, params ):
print( 'test: ' + params )
def do_exit ( self, params ):
return True
def do_quit ( self, params ):
return True
if __name__ == '__main__':
x = Shell()
x.cmdloop()
Do you know why this happens, or what I can do, to make tab completion possible?
It actually works for me on Linux on both Python 2 and 3. However, my python setup was compiled with readline support, which is required for it to be automatic per the cmd documentation. I suspect your Linux Python 3 wasn't compiled with it.
Unfortunately, readline is Unix-specific. See python tab completion in windows for a discussion of other options on Windows.
I got it to work on windows after I installed the pyreadline module from here https://pypi.python.org/pypi/pyreadline/2.0
On Mac there is the Stand-alone GNU readline module.
You can get it with pip install gnureadline.
It has been tested with Python 2.6, 2.7, 3.2 and 3.3.