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

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.

Related

Ipython. How to continue code on the next line?

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

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...')

Simultaneously displaying and capturing standard out in IPython?

I'm interested in implementing a behavior in IPython that would be like a combination of ! and !!. I'm trying to use an IPython terminal as an adjunct to my (Windows) shell. For a long running command (e.g., a build script) I would like to be able to watch the output as it streams by as ! does. I would also like to capture the output of the command into the output history as !! does, but this defers printing anything until all output is available.
Does anyone have any suggestions as to how to implement something like this? I'm guessing that a IPython.utils.io.Tee() object would be useful here, but I don't know enough about IPython to hook this up properly.
Here is a snippet of code I just tried in iPython notebook v2.3, which seems to do what was requested:
import sys
import IPython.utils.io
outputstream = IPython.utils.io.Tee("outputfile.log", "w", channel="stdout")
outputstream.write("Hello worlds!\n")
outputstream.close()
logstream=open("outputfile.log", "r")
sys.stdout.write("Read back from log file:\n")
sys.stdout.write(logstream.read())
The log file is created in the same directory as the iPython notebook file, and the output from running this cell is displayed thus:
Hello worlds!
Read back from log file:
Hello worlds!
I haven't tried this in the iPython terminal, but see no reason it wouldn't work as well there.
(Researched and answered as part of the Oxford participation in http://aaronswartzhackathon.org)

Erlide: how to set start module in run configuration?

I have problem with setting start module and function in "Run configuration"
I'm doing it that way:
"Run -> Run Configuration" and in "start" section I'm setting
Module: mod,
Function: hello
my code:
-module(mod).
-export([hello/0]).
hello()-> io:format("42").
Now, when I hit "Run" I would like mod:hello() to be execute automatically, but it doesn't work.
What am I doing wrong?
The code does get executed...
When you hit "Run", mod:hello() does get executed. The thing is, the execution of mod:hello() is meant for system initialization, like loading library code and initializing looping states. The side effect of mod:hello(), which is the string "42" as stdout will not be reflected in your Eclipse console. To prove my point, we can create some more explicit and more persistent side effects, like creating a file in the file system called output_file.txt. Change mod.erl to something like this:
-module(mod).
-export([hello/0]).
hello() ->
os:cmd("touch output_file.txt").
Hit "Run", and you will find a output_file.txt file being created under your workspace directory. This is an evidence for the execution of mod:hello().
To achieve what you want...
In an Unix shell:
$ erlc mod.erl
$ erl -noshell -s mod hello -s init stop
42
Depending on what you want to execute, there is an alternative to the answer above: the "live expressions". There is a view with this name in the same place as the console, where you can enter an expression and enable it for evaluation every time a module is recompiled.
This works nicely for expression that aren't heavy to evaluate and that are without side effects, can be used as a form of alternative to having a test suite.

Separate standard output from standard error when running a program in Eclipse

I am debugging a Java program in Eclipse. This program normally writes binary data to its standard output, but it can write error messages and stack traces to its standard error stream.
I would like to redirect the binary data to a file, while continuing to show the standard error output in a console. This is trivial when running from the command line. Is it possible under Eclipse?
So far I have only figured out how to redirect both standard output and standard error to the same file. I cannot see a way to separate the two other than adding a new command-line option to the program.
Related: I/O redirection in Eclipse?
Can you try to redirect your stream stdout to a custom View with a SWT Text in it, leaving stderr to the default console.
See this thread
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
public class ConsumeSysout {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Text text = new Text(shell, SWT.NONE);
shell.open();
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
text.append(Character.toString((char) b));
}
};
System.setOut(new PrintStream(out));
System.out.println("Hello World!");
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
From (http://www.eclipsezone.com/eclipse/forums/t52910.html):
If someone would like to see the strings written to System.out/System.err by an already deployed plugin in Eclipse, then it can be done by running Eclipse in debug mode from command prompt as eclipse.exe -debug.
Or else you can hack a little bit to capture the stderr/stdout of the JVM (running Eclipse) as described in Redirect stdout and stderr of Eclipse to a file (Eclipse 3.0 on WinXP)
If you run Eclipse in debug mode, you should be able to start it from a command line and include a stderr redirect. In Unix it would be "command 2> file".
This thread has some related content: Redirect STDERR / STDOUT of a process AFTER it's been started, using command line?
This link is more DOS/Windows specific: Stderr
The DOS shell, command.com, offers no
mean to redirect stderr. Because of
that, it's impossible to save to a
file, or pipe into a program, the
messages that a program prints to
stderr. "foo >out" only redirects
stdout of foo, not stderr. The latter
still goes to the console.
Since stderr is typically where
important error messages are printed,
this is extremely unfortunate, as this
makes us unable to detect errors in
unattended jobs.
So what do you do? One solution is to
switch to Unix, where the shell allows
one to redirect stderr. With sh and
its derivatives, use
foo >out 2>&1
to save both stdout and stderr of foo
to out. Similarly, use
foo 2>&1 | bar
to pipe both stdout and stderr of foo
into bar. If you're stuck with DOS,
Stderr is what you need.
Stderr runs a command and merges its
stderr into its stdout. Therefore,
redirecting or piping stdout is
equivalent to doing the same thing to
stderr as well.
I'll have to keep looking for Windows solutions. PowerShell has become popular, and it might be worth checking out.
Well, you can replace System.out with your own PrintStream that writes out to a file. I'm just writing this off the cuff, so maybe it's not exactly perfectly right, but you get the idea:
FileOutputStream fos = new FileOutputStream("c:\myfile.bin");
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintStream ps = new PrintStream(bos);
System.out = ps;
That, or something very similar should do the trick. All output that normally goes to standard out will now go into that file (don't forget to close() the Printstream when you shut your program down, or it won't always flush the last of the data out to the file.)
Of course, you can also do the same trick with System.err if you want.
Two solutions come to mind right now for filtering stdout/stderr in an independent console (but they are not for binary streams, hence the Community-Wiki mode):
Either do not redirect anything (all outputs are in the console), and use a plugin like Grep Console to highlight relevant outputs
And/or redirect everything in a file, and use a plugin like NTail and use some "Filter lines" to exclude selected lines from log file display (that may be closer to what you are looking for).
(You can define a many a NTail views as you need/want.)