HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
PY_Python.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * COMMENTS:
7  * This file contains functions to run python code.
8  */
9 
10 #ifndef __PY_Python_h__
11 #define __PY_Python_h__
12 
13 #include "PY_API.h"
14 #include "PY_Result.h"
15 #include <UT/UT_String.h>
16 #include <UT/UT_UniquePtr.h>
17 #include <UT/UT_WeakPtr.h>
18 
20 class UT_Thread;
21 
22 /// Callback class for PY_Result notifications
23 /// See PYregisterResultClient, PYnotifyResultClients
25 {
26  public:
27  PY_ResultClient() = default;
28  virtual ~PY_ResultClient() = default;
29 
30  virtual void onNotifyPYResult(PY_Result const & result, const char* user_data) = 0;
31 };
32 
33 /// Expressions cannot contain multiple statements (defs, classes, print
34 /// statements, etc.) and they cannot contain multiple expressions. The
35 /// *InNewContext version creates a new PY_EvaluationContext, run the Python
36 /// code inside it, and destroys the context afterward.
37 /// @{
39  const char *python_code, PY_Result::Type desired_result_type,
42  const char *python_code, PY_Result::Type desired_result_type);
43 /// @}
44 
45 /// Evaluate a Python expression that should not generate any exceptions. If an
46 /// exception is raised the traceback will be displayed to the user, prefixed by
47 /// the specified heading.
49  const char *python_code,
50  PY_Result::Type desired_result_type,
51  const char *heading = NULL,
53 
54 /// Evaluate a Python expression that should not generate any exceptions and
55 /// should evaluate to an exact type. If an exception is raised a traceback
56 /// is displayed with the specified heading. If the wrong type is returned,
57 /// the specified error message is displayed with the heading. Returns true
58 /// on success and stores the result in "result".
60  const char *python_code,
61  PY_Result::Type desired_result_type,
62  PY_Result &result,
63  const char *error_heading,
64  const char *error_for_wrong_type,
66 
67 /// The result type from running statements in the current thread can be none
68 /// (indicating normal completion), error, or exit. The *InNewContext version
69 /// creates a new PY_EvaluationContext, run the Python code inside it, and
70 /// destroys the context afterward.
71 ///
72 /// If `as_file` is not null, then `as_file` is used as the filename
73 /// that appears in syntax errors.
74 /// @{
76  const char *python_code,
78  const char *as_file=nullptr);
80  const char *python_code, const char *as_file=nullptr);
81 /// @}
82 
83 /// This version of PYrunPythonStatements will set Python's sys.argv to the
84 /// arguments you supply. argv[0] will be the name of the Python file.
86  const char *python_code,
87  int argc, char *argv[],
89  bool update_path=true);
90 
91 /// Run Python code that should not generate any exceptions. If an exception
92 /// is raised the traceback will be displayed to the user, prefixed by the
93 /// specified heading.
94 ///
95 /// If `as_file` is not null, then `as_file` is used as the filename
96 /// that appears in syntax errors.
97 /// @{
99  const char *python_code,
100  const char *heading = NULL,
102  const char *as_file=nullptr);
104  const char *python_code,
105  const char *heading = NULL,
106  const char *as_file=nullptr);
107 /// @}
108 
109 /// The argv version of PYrunPythonStatementsFromFile will set Python's sys.argv
110 /// to the arguments you supply. argv[0] will be the name of the Python file.
111 /// @{
113  const char *filename,
114  PY_EvaluationContext *context = NULL);
116  int argc, char *argv[],
118  bool update_path=true);
119 /// @}
120 
121 /// Run python code asynchronously and return the started thread if
122 /// successfully scheduled. If there are parse errors, a new thread could not
123 /// be started, or the file could not be loaded, then errors will be set to the
124 /// reason.
125 /// @{
127  const char *python_code, UT_String &errors);
129  const char *file_name, UT_String &errors);
131  int argc, char *argv[], UT_String &errors, bool update_path=true);
132 /// @}
133 
134 /// Return the python result containing a stack trace and exception information.
135 /// If no exception occurred, the result type is none.
137 
138 /// Given a python object and a desired type, try to convert it to that type.
139 /// python_object should be a PyObject*, but it's a void* to avoid having to
140 /// include Python.h from here.
141 ///
142 /// There are two versions: a performance-sensitive version that takes the
143 /// return PY_Result object by reference, and a convenience version one that
144 /// returns it by value.
145 /// @{
147  void *opaque_python_object, PY_Result::Type desired_result_type);
149  void *opaque_python_object, PY_Result::Type desired_result_type,
150  PY_Result &result);
151 /// @}
152 
153 /// Given an (opaque) Python object, call one of its methods with no arguments
154 /// and return its result, converting to the desired type.
156  void *opaque_python_object, const char *method_name,
157  PY_Result::Type desired_result_type);
158 
159 /// Given an (opaque) callable Python object, call it with no arguments and
160 /// return its Python object result. If an exception occurred, it remains set
161 /// in the Python interpreter and this function returns null. This function
162 /// behaves much like calling PyObject_CallObject with a null argument
163 /// parameter, but the difference is that if calling the code generates a crash,
164 /// the signal is caught, an exception is set, and this function returns null.
165 PY_API void *PYcallObjectAndCatchCrashes(void *callable);
166 
167 /// We don't want to have to prefix things with "hou." in expressions.
168 /// So, we create a separate evaluation context for expressions where
169 /// "from hou import *" has been run.
171 
172 /// Given a string containing the contents of a module and the module's name,
173 /// compile the string and import that as a module. If no exception occurred,
174 /// the result type is none.
176  const char *module_name, const char *module_contents);
177 
178 /// Return a PyCodeObject * corresponding to the frame before the current eval
179 /// frame.
181 
182 /// Return a PyCodeObject * corresponding to the specified PyObject
183 PY_API void *PYgetCodeObjectForFunction(void *opaque_python_object);
184 
185 /// Set a callback that will be invoked by PYrunPython*AndExpectNoErrors
186 /// whenever an error occurs. If this callback is not set, the errors will
187 /// be printed to the console. This callback provides an opportunity to
188 /// pop up a dialog to display the errors.
190  void (*callback)(const char *heading, const char *error_message));
191 
192 /// Display a Python traceback with a given heading. If the traceback display
193 /// callback was set, it will be used to display the traceback.
195  const char *heading, const char *traceback_message);
196 
197 /// This function controls whether running Python code automatically sets the
198 /// HOM_Module implementation (by importing the hou Python module). Call
199 /// PYsetAutoInitializeFromPython to false if you don't hou to be imported
200 /// automatically; otherwise, it will. You must call this static method
201 /// before running any Python code. Once any Python code is run, this
202 /// setting has no effect.
203 PY_API void PYsetAutoInitializeFromPython(bool auto_initialize);
204 
205 /// This function is used by PY_InterpreterAutoLock to determine if
206 /// it should automatically import the hou module
208 
209 
210 /// Returns the absolute path to Houdini's Python modules.
211 PY_API const char *PYgetHoudiniModulePath();
212 
213 /// Bind and return a PY_Object 'function' from a specific module. The caller
214 /// is responsible for incrementing the Python object ref count.
215 PY_API PY_Result PYbindFunctionFromModule(const char* module_name, const char *func_name);
216 
217 /// Log result on std error, doesn't print anything if result is not an ERR
218 /// type. The error message is based on the format returned by
219 /// PYgetErrorFormat()
220 /// params:
221 /// result: PY_Result object
222 /// title: title to use for building the error message
223 PY_API void PYlogError(PY_Result const & result, const char* title);
224 
225 /// Return a formatted error message filled with a title and the detailed error
226 /// message set in the PY_Result object. Returns an empty string if the
227 /// PY_Result object is not an ERR type.
228 /// params:
229 /// result: PY_Result object
230 /// title: title to use for building the error message
231 /// format: error message format. Must be of the form "%s %s". See
232 /// PYgetErrorFormat for an example.
234  PY_Result const & result,
235  const char* title,
236  const char* format );
237 
238 /// Returns the default error format string "%s\n%s\n" usable with
239 /// PYformatError and PYprocessError.
240 PY_API const char* PYgetErrorFormat();
241 
242 /// Register a callback function to be executed at exit time immediately before
243 /// Python shuts down.
244 PY_API void PYregisterAtExitCallback(std::function<void(void)> func);
245 
246 /// Process a python error object with a user function. PYprocessError creates
247 /// an error message and passes it to process_func for processing. The
248 /// process_func function would typically log the error on the console, in a
249 /// file or throw an exception.
250 ///
251 /// params:
252 /// result: PY_Result object set to ERR. Function does nothing if not set to
253 /// ERR.
254 /// title: title of the error message
255 /// format: error message format. Must be of the form "%s %s". See
256 /// PYgetErrorFormat for an example.
257 /// process_func: user function to process the error, takes a pre-formatted
258 /// error string of type const char*.
259 
260 template<typename FUNC>
262  PY_Result const & result,
263  const char* title,
264  const char* format,
265  FUNC const& process_func )
266 {
267  if (result.myResultType != PY_Result::ERR)
268  {
269  // just return if the result is not an error
270  return;
271  }
272 
273  auto && errmsg = PYformatError(result, title, format);
274  process_func(errmsg.c_str());
275 }
276 
277 /// Registers a client interested in Python script evaluation results.
279 
280 /// Notifies registered PY_ResultClient objects about the result of a
281 /// python script or statement evaluation.
282 ///
283 /// results: Python result structure.
284 /// user_data: A string passed to the clients that can be used for
285 /// interpreting the type of notification.
286 PY_API void PYnotifyResultClients(PY_Result const & result, char const * script_event);
287 
288 #endif
PY_API void PYsetAutoInitializeFromPython(bool auto_initialize)
PY_API PY_Result PYextractResultFromPythonObject(void *opaque_python_object, PY_Result::Type desired_result_type)
GT_API const UT_StringHolder filename
PY_API PY_Result PYrunPythonStatementsFromFile(const char *filename, PY_EvaluationContext *context=NULL)
PY_API void PYlogError(PY_Result const &result, const char *title)
PY_API void PYdisplayPythonTraceback(const char *heading, const char *traceback_message)
PY_API bool PYautoInitializeFromPython()
PY_API void * PYgetCodeObjectForFunction(void *opaque_python_object)
Return a PyCodeObject * corresponding to the specified PyObject.
PY_API UT_UniquePtr< UT_Thread > PYrunPythonStatementsFromFileInNewThread(const char *file_name, UT_String &errors)
PY_API PY_Result PYcallMethodOnPythonObject(void *opaque_python_object, const char *method_name, PY_Result::Type desired_result_type)
GLint GLint GLsizei GLsizei GLsizei GLint GLenum format
Definition: glew.h:1254
PY_API bool PYrunPythonExpressionOfExactType(const char *python_code, PY_Result::Type desired_result_type, PY_Result &result, const char *error_heading, const char *error_for_wrong_type, PY_EvaluationContext *context=NULL)
PY_API PY_Result PYrunPythonStatementsInNewContext(const char *python_code, const char *as_file=nullptr)
PY_API bool PYrunPythonStatementsAndExpectNoErrors(const char *python_code, const char *heading=NULL, PY_EvaluationContext *context=NULL, const char *as_file=nullptr)
std::unique_ptr< T, Deleter > UT_UniquePtr
A smart pointer for unique ownership of dynamically allocated objects.
Definition: UT_UniquePtr.h:33
PY_API PY_Result PYrunPythonExpressionAndExpectNoErrors(const char *python_code, PY_Result::Type desired_result_type, const char *heading=NULL, PY_EvaluationContext *context=NULL)
PY_API void PYnotifyResultClients(PY_Result const &result, char const *script_event)
PY_API void PYsetPythonTracebackDisplayCallback(void(*callback)(const char *heading, const char *error_message))
PY_API const char * PYgetErrorFormat()
#define PY_API
Definition: PY_API.h:10
void PYprocessError(PY_Result const &result, const char *title, const char *format, FUNC const &process_func)
Definition: PY_Python.h:261
PY_API UT_UniquePtr< UT_Thread > PYrunPythonStatementsInNewThread(const char *python_code, UT_String &errors)
PY_API void * PYcallObjectAndCatchCrashes(void *callable)
PY_API PY_Result PYbindFunctionFromModule(const char *module_name, const char *func_name)
PY_API PY_Result PYrunPythonExpressionInNewContext(const char *python_code, PY_Result::Type desired_result_type)
PY_API PY_EvaluationContext & PYgetPythonExpressionEvaluationContext()
GLenum func
Definition: glcorearb.h:782
PY_API PY_Result PYrunPythonStatements(const char *python_code, PY_EvaluationContext *context=NULL, const char *as_file=nullptr)
std::weak_ptr< T > UT_WeakPtr
Definition: UT_WeakPtr.h:17
PY_API PY_Result PYextractPythonException()
GLuint64EXT * result
Definition: glew.h:14007
PY_API void PYregisterAtExitCallback(std::function< void(void)> func)
PY_API const char * PYgetHoudiniModulePath()
Returns the absolute path to Houdini's Python modules.
PY_API PY_Result PYimportModuleFromString(const char *module_name, const char *module_contents)
PY_API void PYregisterResultClient(UT_WeakPtr< PY_ResultClient > result_client)
Registers a client interested in Python script evaluation results.
PY_API void * PYgetCodeObjectForPrevFrame()
Type myResultType
Definition: PY_Result.h:44
PY_API UT_StringHolder PYformatError(PY_Result const &result, const char *title, const char *format)
PY_API PY_Result PYrunPythonExpression(const char *python_code, PY_Result::Type desired_result_type, PY_EvaluationContext *context=NULL)
PY_API bool PYrunPythonStatementsInNewContextAndExpectNoErrors(const char *python_code, const char *heading=NULL, const char *as_file=nullptr)