I'd like to include Python scripting in one of my applications, that is written in Python itself.
My application must be able to call external Python functions (written by the user) as callbacks. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that.
What is the best way to do this?
Thanks.
edit: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.
Python is one of the most ubiquitous development languages; it's used frequently by sysadmins, data scientists, back-end software developers, and web developers. Python has many use cases, and this tutorial explores how to use it for scripting common sysadmin tasks. Here's the environment used in this tutorial.
The most basic and easy way to run a Python script is by using the python command. You need to open a command line and type the word python followed by the path to your script file, like this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard and that's it.
Use __import__
to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file.
Use try..except
both on __import__
and on the actual call to catch errors.
Example:
m = None
try:
m = __import__("external_module")
except:
# invalid module - show error
if m:
try:
m.user_defined_func()
except:
# some error - display it
If you'd like the user to interactively enter commands, I can highly recommend the code module, part of the standard library. The InteractiveConsole and InteractiveInterpreter objects allow for easy entry and evaluation of user input, and errors are handled very nicely, with tracebacks available to help the user get it right.
Just make sure to catch SystemExit!
$ python
Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> shared_var = "Set in main console"
>>> import code
>>> ic = code.InteractiveConsole({ 'shared_var': shared_var })
>>> try:
... ic.interact("My custom console banner!")
... except SystemExit, e:
... print "Got SystemExit!"
...
My custom console banner!
>>> shared_var
'Set in main console'
>>> shared_var = "Set in sub-console"
>>> sys.exit()
Got SystemExit!
>>> shared_var
'Set in main console'
RestrictedPython provides a restricted execution environment for Python, e.g. for running untrusted code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With