Can I get just the raised error from a subprocess? - error-handling

I am using this to execute a command:
try:
subprocess.check_output(COMMAND)
except subprocess.CalledProcessError as e:
print(e.output)
Inside the COMMAND is raised an exception, after a lot of standard output. What gets returned in e.output is in fact ALL the output plus the thrown error.
Is there a method to only return the raised error?
In COMMAND the Message is raised like:
try:
for i in range(3):
print("i is {0}.".format(i))
x = 1/0
print("x is {0}".format(x))
except Exception as e:
print("Message")
raise
Only want the "Message" returned.
Thanks in advance.

Related

Is there a bgerror hook equivalent for uncaught errors out of the event loop in TCL?

In Tcl, when an uncaught error occurs in the background in the event loop, the function bgerror will be called if one exists (or any function registered via interp bgerror).
When an unknown command is encountered, the unknown command will be called.
Is there a similar mechanism for uncaught errors outside of the event loop that make their way to the top level? The default behavior from tclsh is just to print the error on stderr, but I would like a specific proc to be called instead without having to put the entire code in one big catch.
The default behaviour, if a Tcl error makes it's way to the top of the main execution path, is to print the errorInfo trace to standard error and, if running as a script, exit with a non-zero result code. If you want to override this, you need to either write your own entry code/main loop in C (when you can do anything you want when Tcl_Eval() returns TCL_ERROR), or wrap your code in a catch or try. You can use uplevel #0 within such Tcl code to ensure that the trapping code doesn't appear to be on the stack as seen by the rest of your code.
For example:
proc printStackOnError {script} {
try {
uplevel "#0" $script
} on error {msg opt} {
set stackinfo [dict get $opt -errorinfo]
# remove last three uninteresting lines; they're just part of this procedure's machinery
puts stderr [join [lrange [split $stackinfo "\n"] 0 end-3] "\n"]
}
}
Demonstrating (interactively, with Tcl 8.6):
% printStackOnError {eval {error foo}}
foo
while executing
"error foo"
("eval" body line 1)
invoked from within
"eval {error foo}"
You're advised to make sure you either print or log the errorInfo when an error is trapped at that level. Otherwise any bugs in your code are going to be unreasonably difficult to fix.

EOF error using input Python 3

I keep getting an EOF error but unsure as to why. I have tried with and without int() but it makes no difference. I'm using Pycharm 3.4 and Python 3.
Thanks,
Chris
while True:
try:
number = int(input("what's your favourite number?"))
print (number)
break
You must close a try statement because you are declaring that there might be an error and you want to handle it
while True:
try:
number = int(input("what's your favourite number?"))
print(number)
break
except ValueError as e:
print("Woah, there is an error: {0}".format(e))

How to debug the error thrown by Doctrine

What ?
This is the error thrown by my doctrine when writing my query
[Semantical Error] line 0, col 971 near '(\n ': Error: Class '(' is not defined.
How can i detect the exact position where the error occurs in my doctrine style of writing, in short how to read this error ?
my Query pattern
$qb1 = $this->_em->createQueryBuilder();
$qb1->select('
count(case when (boolShit) then id end)
')
->from(someTable);
$qb1->getQuery()->getResult();
Assuming that you have Symfony2, you can debug it with using app_dev.php. If you do so, you are able to press plus button beneath the error output that you've shown. This pus button is on the end of the line starting with [QueryException].
If you'll find this magic "plus button" you will find the exact line of getting result (i.e. getResult(), getArrayResult()...)
Example output with "plus button":

How to catch the error on screen into variable in TCL using catch

To grep the error on the screen though catch eg
puts $c
#error on terminal : can't read "c": no such variable
catch {puts $c} err
puts $err # value of err 1
Is there any way to catch actual error message in
TCL apart from signal in variable err.
Yes. Read the ::errorInfo or ::errorCode global variables to get the stack trace and a machine-parsable "POSIX error" three-element list, correspondingly.
Since Tcl 8.5, it's also possible to pass a name of a dictionary to catch after the name of the variable to receive the result, and that dictionary will be populated by much of what can be obtained via "classic" error variables I described above, and more.
This is all explained in the catch manual page.

Python 2.7.3 process.Popen() failures

I'm using python 2.7.3 on a Windows 7 64-bit machine currently (also developing in Linux 32 bit, Ubuntu 12.04) and am having odd difficulties getting python to communicate with the command prompt/terminal successfully. My code looks like this:
import subprocess, logging, platform, ctypes
class someClass (object):
def runTerminalCommand:
try:
terminalOrCmdLineCommand = self.toString()
process = subprocess.Popen(terminalOrCmdLineCommand, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output = process.stdout.readlines()
if len(output) < 1:
logging.exception("{} error : {}".format(self.cmd,process.stderr.readlines()))
raise ConfigError("cmd issue : {}".format(self.cmd))
return output
except ValueError as err:
raise err
except Exception as e:
logging.exception("Unexpected error : " + e.message)
raise ConfigError("unexpected error")
Now, I know that the self.toString() returned value will process correctly if I enter it manually, so I'm limiting this to an issue with how I'm sending it to the command line via the subprocess. I've read the documentation, and found that the subprocess.check_call() doesn't return anything if it encounters an error, so I'm using .Popen()
The exception I get is,
[date & time] ERROR: Unexpected error :
Traceback (most recent call last):
File "C:\[...]"
raise ConfigError("cmd issue : {}".format(self.cmd))
"ConfigError: cmd issue : [the list self.cmd printed out]"
What I am TRYING to do, is run a command, and read the input back. But I seem to be unable to automate the call I want to run. :(
Any thoughts? (please let me know if there are any needed details I left out)
Much appreciated, in advance.
The docs say:
Use communicate() rather than .stdin.write, .stdout.read or
.stderr.read to avoid deadlocks due to any of the other OS pipe
buffers filling up and blocking the child process.
You could use .communicate() as follows:
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout_data, stderr_data = p.communicate()
if p.returncode != 0:
raise RuntimeError("%r failed, status code %s stdout %r stderr %r" % (
cmd, p.returncode, stdout_data, stderr_data))
output_lines = stdout_data.splitlines() # you could also use `keepends=True`
See other methods to get subprocess output in Python.