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_Function.h>
18 
20 class UT_Thread;
21 
22 /// Expressions cannot contain multiple statements (defs, classes, print
23 /// statements, etc.) and they cannot contain multiple expressions. The
24 /// *InNewContext version creates a new PY_EvaluationContext, run the Python
25 /// code inside it, and destroys the context afterward.
26 /// @{
28  const char *python_code, PY_Result::Type desired_result_type,
29  PY_EvaluationContext *context = NULL);
31  const char *python_code, PY_Result::Type desired_result_type);
32 /// @}
33 
34 /// Evaluate a Python expression that should not generate any exceptions. If an
35 /// exception is raised the traceback will be displayed to the user, prefixed by
36 /// the specified heading.
38  const char *python_code,
39  PY_Result::Type desired_result_type,
40  const char *heading = NULL,
41  PY_EvaluationContext *context = NULL);
42 
43 /// Evaluate a Python expression that should not generate any exceptions and
44 /// should evaluate to an exact type. If an exception is raised a traceback
45 /// is displayed with the specified heading. If the wrong type is returned,
46 /// the specified error message is displayed with the heading. Returns true
47 /// on success and stores the result in "result".
49  const char *python_code,
50  PY_Result::Type desired_result_type,
51  PY_Result &result,
52  const char *error_heading,
53  const char *error_for_wrong_type,
54  PY_EvaluationContext *context = NULL);
55 
56 /// The result type from running statements in the current thread can be none
57 /// (indicating normal completion), error, or exit. The *InNewContext version
58 /// creates a new PY_EvaluationContext, run the Python code inside it, and
59 /// destroys the context afterward.
60 ///
61 /// If `as_file` is not null, then `as_file` is used as the filename
62 /// that appears in syntax errors.
63 /// @{
65  const char *python_code,
66  PY_EvaluationContext *context = NULL,
67  const char *as_file=nullptr);
69  const char *python_code, const char *as_file=nullptr);
70 /// @}
71 
72 /// This version of PYrunPythonStatements will set Python's sys.argv to the
73 /// arguments you supply. argv[0] will be the name of the Python file.
75  const char *python_code,
76  int argc, char *argv[],
77  PY_EvaluationContext *context = NULL,
78  bool update_path=true);
79 
80 /// Run Python code that should not generate any exceptions. If an exception
81 /// is raised the traceback will be displayed to the user, prefixed by the
82 /// specified heading.
83 ///
84 /// If `as_file` is not null, then `as_file` is used as the filename
85 /// that appears in syntax errors.
86 /// @{
88  const char *python_code,
89  const char *heading = NULL,
90  PY_EvaluationContext *context = NULL,
91  const char *as_file=nullptr);
93  const char *python_code,
94  const char *heading = NULL,
95  const char *as_file=nullptr);
96 /// @}
97 
98 /// The argv version of PYrunPythonStatementsFromFile will set Python's sys.argv
99 /// to the arguments you supply. argv[0] will be the name of the Python file.
100 /// @{
102  const char *filename,
103  PY_EvaluationContext *context = NULL);
105  int argc, char *argv[],
106  PY_EvaluationContext *context = NULL,
107  bool update_path=true);
108 /// @}
109 
110 /// Run python code asynchronously and return the started thread if
111 /// successfully scheduled. If there are parse errors, a new thread could not
112 /// be started, or the file could not be loaded, then errors will be set to the
113 /// reason.
114 /// @{
116  const char *python_code, UT_String &errors);
118  const char *file_name, UT_String &errors);
120  int argc, char *argv[], UT_String &errors, bool update_path=true);
121 /// @}
122 
123 /// Return the python result containing a stack trace and exception information.
124 /// If no exception occurred, the result type is none.
126 
127 /// Given a python object and a desired type, try to convert it to that type.
128 /// python_object should be a PyObject*, but it's a void* to avoid having to
129 /// include Python.h from here.
130 ///
131 /// There are two versions: a performance-sensitive version that takes the
132 /// return PY_Result object by reference, and a convenience version one that
133 /// returns it by value.
134 /// @{
136  void *opaque_python_object, PY_Result::Type desired_result_type);
138  void *opaque_python_object, PY_Result::Type desired_result_type,
139  PY_Result &result);
140 /// @}
141 
142 /// Given an (opaque) Python object, call one of its methods with no arguments
143 /// and return its result, converting to the desired type.
145  void *opaque_python_object, const char *method_name,
146  PY_Result::Type desired_result_type);
147 
148 /// Given an (opaque) callable Python object, call it with no arguments and
149 /// return its Python object result. If an exception occurred, it remains set
150 /// in the Python interpreter and this function returns null. This function
151 /// behaves much like calling PyObject_CallObject with a null argument
152 /// parameter, but the difference is that if calling the code generates a crash,
153 /// the signal is caught, an exception is set, and this function returns null.
154 PY_API void *PYcallObjectAndCatchCrashes(void *callable);
155 
156 /// We don't want to have to prefix things with "hou." in expressions.
157 /// So, we create a separate evaluation context for expressions where
158 /// "from hou import *" has been run.
160 
161 /// Given a string containing the contents of a module and the module's name,
162 /// compile the string and import that as a module. If no exception occurred,
163 /// the result type is none.
165  const char *module_name, const char *module_contents);
166 
167 /// Return a PyCodeObject * corresponding to the frame before the current eval
168 /// frame.
170 
171 /// Return a PyCodeObject * corresponding to the specified PyObject
172 PY_API void *PYgetCodeObjectForFunction(void *opaque_python_object);
173 
174 /// Set a callback that will be invoked by PYrunPython*AndExpectNoErrors
175 /// whenever an error occurs. If this callback is not set, the errors will
176 /// be printed to the console. This callback provides an opportunity to
177 /// pop up a dialog to display the errors.
179  void (*callback)(const char *heading, const char *error_message));
180 
181 /// Display a Python traceback with a given heading. If the traceback display
182 /// callback was set, it will be used to display the traceback.
184  const char *heading, const char *traceback_message);
185 
186 /// This function controls whether running Python code automatically sets the
187 /// HOM_Module implementation (by importing the hou Python module). Call
188 /// PYsetAutoInitializeFromPython to false if you don't hou to be imported
189 /// automatically; otherwise, it will. You must call this static method
190 /// before running any Python code. Once any Python code is run, this
191 /// setting has no effect.
192 PY_API void PYsetAutoInitializeFromPython(bool auto_initialize);
193 
194 /// This function is used by PY_InterpreterAutoLock to determine if
195 /// it should automatically import the hou module
197 
198 
199 /// Returns the absolute path to Houdini's Python modules.
200 PY_API const char *PYgetHoudiniModulePath();
201 
202 /// Bind and return a PY_Object 'function' from a specific module. The caller
203 /// is responsible for incrementing the Python object ref count.
204 PY_API PY_Result PYbindFunctionFromModule(const char* module_name, const char *func_name);
205 
206 /// Log result on std error, doesn't print anything if result is not an ERR
207 /// type. The error message is based on the format returned by
208 /// PYgetErrorFormat()
209 /// params:
210 /// result: PY_Result object
211 /// title: title to use for building the error message
212 PY_API void PYlogError(PY_Result const & result, const char* title);
213 
214 /// Return a formatted error message filled with a title and the detailed error
215 /// message set in the PY_Result object. Returns an empty string if the
216 /// PY_Result object is not an ERR type.
217 /// params:
218 /// result: PY_Result object
219 /// title: title to use for building the error message
220 /// format: error message format. Must be of the form "%s %s". See
221 /// PYgetErrorFormat for an example.
223  PY_Result const & result,
224  const char* title,
225  const char* format );
226 
227 /// Returns the default error format string "%s\n%s\n" usable with
228 /// PYformatError and PYprocessError.
229 PY_API const char* PYgetErrorFormat();
230 
231 /// Register a callback function to be executed at exit time immediately before
232 /// Python shuts down.
234 
235 /// Process a python error object with a user function. PYprocessError creates
236 /// an error message and passes it to process_func for processing. The
237 /// process_func function would typically log the error on the console, in a
238 /// file or throw an exception.
239 ///
240 /// params:
241 /// result: PY_Result object set to ERR. Function does nothing if not set to
242 /// ERR.
243 /// title: title of the error message
244 /// format: error message format. Must be of the form "%s %s". See
245 /// PYgetErrorFormat for an example.
246 /// process_func: user function to process the error, takes a pre-formatted
247 /// error string of type const char*.
248 
249 template<typename FUNC>
251  PY_Result const & result,
252  const char* title,
253  const char* format,
254  FUNC const& process_func )
255 {
256  if (result.myResultType != PY_Result::ERR)
257  {
258  // just return if the result is not an error
259  return;
260  }
261 
262  auto && errmsg = PYformatError(result, title, format);
263  process_func(errmsg.c_str());
264 }
265 
266 /// Add all the HOUDINI_PATH/pythonX.Ylibs entries to the python path.
267 /// For backwards compatibility, we also add HOUDINI_PATH/scripts/python
268 /// entries. We're careful to make sure the order of the entries in
269 /// sys.path matches the order in HOUDINI_PATH.
270 
271 // paths_to_remove: an optional array of paths to remove when updating
272 // the python path.
273 PY_API void PYupdatePythonPath(const UT_StringArray & paths_to_remove=UT_StringArray());
274 
275 /// Returns the Houdini python libs folder name e.g. "python3.7libs"
277 
278 #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)
PY_API UT_String PYgetPythonLibsSubdir()
Returns the Houdini python libs folder name e.g. "python3.7libs".
**But if you need a result
Definition: thread.h:613
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:39
PY_API void PYregisterAtExitCallback(UT_Function< void(void)> func)
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 PYsetPythonTracebackDisplayCallback(void(*callback)(const char *heading, const char *error_message))
PY_API const char * PYgetErrorFormat()
GLint GLint GLsizei GLint GLenum format
Definition: glcorearb.h:108
#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:250
PY_API UT_UniquePtr< UT_Thread > PYrunPythonStatementsInNewThread(const char *python_code, UT_String &errors)
std::function< T > UT_Function
Definition: UT_Function.h:37
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:783
PY_API PY_Result PYrunPythonStatements(const char *python_code, PY_EvaluationContext *context=NULL, const char *as_file=nullptr)
PY_API PY_Result PYextractPythonException()
PY_API void PYupdatePythonPath(const UT_StringArray &paths_to_remove=UT_StringArray())
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 * PYgetCodeObjectForPrevFrame()
Type myResultType
Definition: PY_Result.h:45
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)