PYPY translate exception - python

I'm trying to generate from a simple python named test.py script the c code,
the command that I'm using is:
python rpython --source ~/work/test.py.
I don't get what I'm doing wrong because from the exception that I received in the output I don't understand much :
Exception: file '/work/test.py' is not a valid targetxxx.py.
Any idea what should i do to avoid the exception?

I had a similar issue; what fixed it for me was adding the target function to my main script:
def target(*args):
return entry_point, None
hope it helps :)

Related

Can't seem to write error to output file if a script doesn't run correctly

I've written a function which reads and runs a python script, then sends it's output to a text file.
I'm trying to get it to write a simple string, or the error in question, to the text file if the script it ran is broken/doesn't work.
Below is the code in question:
file_dir = a_dir[0]
file_name = a_dir[1][:-3]
with open(f'{self.output_directory}\\output_{file_name}.txt', 'w') as f:
try:
subprocess.call(
[sys.executable, file_dir], stdout=f)
except:
f.write("An error occured with the script")
The first part of it works fine - it does run a functioning file and writes the output.
Do I need to be more specific with the error exception? Any help would be greatly appreciated!
If your code works fine and sys.executable is being run then there will be no exception and so your f.write code won't be run. If there is an error in a program you run using subprocess this doesn't propagate to an exception in a program you run it from. You'd have to know something about this program to know that there was an error you could look at the [returncode][1] from the subprocess.call function call. Another option is that instead of running a new python interpreter you could load the module yourself and then run code from within it using try except blocks. If you can't rely on any structure to the file then you could read the file as text and then run the code within it using eval or exec within a try except structure, that being said if you don't know anything about the file in advance it is likely a massive security flaw for you to be executing it at all let alone within the context of your running application.
**late edit read the file as text vice test which was a typo
[1]: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.returncode

How to continue execution of a Python module which calls a failed C++ function?

I have a python file (app.py) which makes a call to a function as follows:
answer = fn1()
The fn1() is actually written in C++ and I've built a wrapper so that I can use it in Python.
The fn1() can either return a valid result, or it may sometimes fail and terminate. Now the issue is that at the times when fn1() fails and aborts, the calling file (i.e. app.py) also terminates and does not go forward to the error handling part.
I would like the calling file to move to my error handling part (i.e. 'except' and 'finally') if fn1() aborts and dumps core. Is there any way to achieve this?
From the OP:
The C++ file that I have built wrapper around aborts in case of exception and dumps core. Python error code is not executed
This was not evident in your question. To catch this sort of error, you can use the signal.signal function in the python standard library (relevant SO answer).
import signal
def sig_handler(signum, frame):
print("segfault")
signal.signal(signal.SIGSEGV, sig_handler)
answer = fn1()
You basically wrote the answer in your question. Use a try except finally block. Refer also to the Python3 documentation on error handling
try:
answer = fn1()
except Exception: # You can use an exception more specific to your failing code.
# do stuff
finally:
# do stuff
What you need to do is to catch the exception in your C++ function and then convert it to a python exception and return that to the python code.

How to handle syntax Errors

So, we had instance in the past where code were broken in IOT devices because of syntax errors.
While there is exception handling in the code. I wanted to create a script to check and make sure that the codes compiles and run without syntax error, else the script replace the broken code by an earlier version.
I tried this
from delta_script import get_update
def test_function():
try:
get_update()
except SyntaxError as syntaxError:
replace_script("utility.py", syntaxError)
except Exception as ignored:
pass
However the problem it when it hit a SyntaxError, it just throw it on the screen and replace_script
because the exception happens on delta_script.py from which get_update() was imported.
So what's the solution in this case?
I have also another function
def compile():
try:
for file in compile_list:
py_compile.compile(file)
except Exception as exception:
script_heal(file, exception)
however in this one, it never report any exception, because I go and introduce syntaxError and the code still compile without reporting an error
Any one could help me figure out a better way to solve those two problems?
thanks,
SyntaxErrors occur at compile time, not run time, so you generally can't catch them. There are exceptions, involving run time compilation using eval/exec, but in general, except SyntaxError: is nonsensical; something goes wrong compiling the code before it can run the code that sets up the try/except to catch the error.
The solution is to not write syntactically invalid code, or if you must write it (e.g. to allow newer Python syntax only when supported) to evaluate strings of said code dynamically with eval (often wrapping compile if you need something more complicated than a single expression) or exec.

Fatal Python error: Can't initialize threads for interpreter when calling python from c

I tried to call python code from c, the example runs ok for sample code on my environment(python3.6), but when I integrate it into my program, I got following error when I call Py_Initialize();:
...
sem_init: Success
Fatal Python error: Can't initialize threads for interpreter
Could you provide some clues to solve this problem?
It seems the error comes from here, but I am still not sure how to avoid this.
The failing code is
if (head_mutex == NULL)
Py_FatalError("Can't initialize threads for interpreter");
Searching the code back for head_mutex references finds
#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
which is called right before the failing code.
So, the reason is that PyThread_allocate_lock returns NULL. There are a few different implementations for it in Python codebase depending on the OS and build flags, so you need to debug it or otherwise figure out which one is used in your case to track the error further to an OS call.
There is a function named sem_init in my program, which may conflict with the system library, the program runs ok after I modify the name of this function(but still not sure the reason).

handling of view syntax error vs exceptions in django

I am using django 1.2.7 and python 2.6.
If I use this code: (with an identation error on porpuse)
def myview(request):
try:
if x:
print 'x'
except:
return HttpResponseServerError('bazinga')
then I don't get my response. I get django 500 response.
but if I change the code to this:
def myview(request):
try:
if x:
print 'x'
except:
return HttpResponseServerError('bazinga')
now I get my own 500 with the bazinga written.
How can I catch the identation error in the first example ?
Just as my try-except catch the exception in the 2nd example.
Don't try to make Django return a nice response in the case of a syntax error. That will be difficult, and will involve having code of your own just for this case, and that code itself will need to be error-free, etc.
Instead, put that effort into an automated test suite that will make it easy to find those errors before you deploy your code.
Syntax errors can be detected trivially as you don't need to run the code but only to import it.
There's no reason you should try to catch them, just fix them.
You can catch syntax (And Indentation) errors out of your code.
Look here for more info:
How to catch IndentationError
Syntax errors are not run time errors, they occur at compile time. As far as I know, you can't catch them with a try/except block.

Categories