comparison pyexec.cc @ 307:b4e56f7255f7

Add option to specify namespace when calling pyexec and pyeval (fixes issue #25) * pyeval.cc, pyexec.cc: Use the second parameter (if supplied) as namespace to eval/exec the python code.
author Abhinav Tripathi <genuinelucifer@gmail.com>
date Tue, 09 Aug 2016 11:28:15 -0700
parents c02f0a4c92e7
children a140160b2319
comparison
equal deleted inserted replaced
306:2ecae5c6eeb6 307:b4e56f7255f7
32 32
33 #define PYTAVE_DO_DECLARE_SYMBOL 33 #define PYTAVE_DO_DECLARE_SYMBOL
34 #include "arrayobjectdefs.h" 34 #include "arrayobjectdefs.h"
35 #include "exceptions.h" 35 #include "exceptions.h"
36 #include "python_to_octave.h" 36 #include "python_to_octave.h"
37 #include "pytave_utils.h"
37 38
38 using namespace boost::python; 39 using namespace boost::python;
39 40
40 DEFUN_DLD (pyexec, args, nargout, 41 DEFUN_DLD (pyexec, args, nargout,
41 "-*- texinfo -*-\n\ 42 "-*- texinfo -*-\n\
42 @deftypefn {} {} pyexec (@var{expr})\n\ 43 @deftypefn {} {} pyexec (@var{expr})\n\
44 @deftypefn {} {} pyexec (@var{expr}, @var{localNS})\n\
43 Execute a Python expression or block of code.\n\ 45 Execute a Python expression or block of code.\n\
46 You can supply a 'localNS' to enforce all changes in that namespace.\n\
44 \n\ 47 \n\
45 Examples:\n\ 48 Examples:\n\
46 @example\n\ 49 @example\n\
47 @group\n\ 50 @group\n\
48 pyexec (\"print(42)\")\n\ 51 pyexec (\"print(42)\")\n\
54 { 57 {
55 octave_value_list retval; 58 octave_value_list retval;
56 59
57 int nargin = args.length (); 60 int nargin = args.length ();
58 61
59 if (nargin != 1) 62 if (nargin < 1 || nargin > 2)
60 { 63 {
61 print_usage (); 64 print_usage ();
62 return retval; 65 return retval;
63 } 66 }
64 67
66 69
67 Py_Initialize (); 70 Py_Initialize ();
68 71
69 object main_module = import ("__main__"); 72 object main_module = import ("__main__");
70 object main_namespace = main_module.attr ("__dict__"); 73 object main_namespace = main_module.attr ("__dict__");
74 object local_namespace;
75 if (nargin > 1)
76 {
77 pytave::get_object_from_python (args(1), local_namespace);
78 if (local_namespace.is_none ())
79 error ("pyexec: NAMESPACE must be a string or a Python reference");
80 }
81 else
82 local_namespace = main_namespace;
71 83
72 try 84 try
73 { 85 {
74 // FIXME: figure out exec return code: 86 // FIXME: figure out exec return code:
75 // http://www.boost.org/doc/libs/1_38_0/libs/python/doc/v2/exec.html 87 // http://www.boost.org/doc/libs/1_38_0/libs/python/doc/v2/exec.html
76 exec (code.c_str (), main_namespace, main_namespace); 88 exec (code.c_str (), main_namespace, local_namespace);
77 } 89 }
78 catch (pytave::object_convert_exception const &) 90 catch (pytave::object_convert_exception const &)
79 { 91 {
80 error ("pyexec: error in return value type conversion"); 92 error ("pyexec: error in return value type conversion");
81 } 93 }