2011-04-04 11 views
8

Tengo problemas al ejecutar python incorporado. Resulta que no puedo capturar esa excepción SystemExit planteada por sys.exit();Cómo evitar que python integrado salga() de mi proceso

Esto es lo que tengo hasta ahora:

$ cat call.c 
#include <Python.h> 
int main(int argc, char *argv[]) 
{ 
    Py_InitializeEx(0); 
    PySys_SetArgv(argc-1, argv+1); 
    if (PyRun_AnyFileEx(fopen(argv[1], "r"), argv[1], 1) != 0) { 
     PyObject *exc = PyErr_Occurred(); 
     printf("terminated by %s\n", 
       PyErr_GivenExceptionMatches(exc, PyExc_SystemExit) ? 
       "exit()" : "exception"); 
    } 
    Py_Finalize(); 
    return 0; 
} 

Además, mi guión es:

$ cat unittest-files/python-return-code.py 
from sys import exit 
exit(99) 

Ejecutarlo:

$ ./call unittest-files/python-return-code.py 
$ echo $? 
99 

I debo ejecutar un archivo, no es un comando.

Respuesta

5

PyRun_SimpleFileExFlags función (y todas las funciones que lo utilizan, incluido PyRun_AnyFileEx) maneja las excepciones a sí mismo al salir de SystemExit o impresión de rastreo. Use la familia de funciones PyRun_File* para manejar excepciones en el código circundante.

+1

Buena solución. Ahora usa PyRun_FileEx() y verifica PyErr_Occurred() antes de PyErr_GivenExceptionMatches(). Gracias. – Caruccio

Cuestiones relacionadas