Python snippet

The Python snippet allows you to write, execute and inspect Python code. It is currently supported on Mac and Linux. Windows is not yet supported.

The Python Snippet uses the PythonBridge library to communicate with a Python server via msgpack or HTTP over TCP/IP.

Variables defined in other code snippets, e.g. Pharo and JavaScript, that can be JSON encoded will be shared between snippets within a page.

Currently the global instance of PBApplication LanguageLinkApplication subclass: #PBApplication instanceVariableNames: '' classVariableNames: 'DebugMode' package: 'PythonBridge-Global' is always used.

Examples

1 + 2
  

Configuration

The location of pipenv and the PythonBridge runtime may be configured with:

"Set the Python runtime directory"
thisSnippet database properties pythonBridgeSettings 
	directory: '{imageDirectory}/PythonBridge' asFileReference
  
"Set the location of the pipenv executable"
thisSnippet database properties pythonBridgeSettings 
	pipenvPath: '/usr/bin/pipenv' asFileReference
  

After changing the configuration the python server will need to be restarted to pick up the new configuration:

PBApplication stop.
  

Path segments in curly-braces, e.g. {imageDirectory} are FileLocator AbstractFileReference subclass: #FileLocator instanceVariableNames: 'origin' classVariableNames: 'Resolver' package: 'FileSystem-Core-Public' known origins. For a full list see:

FileLocator supportedOrigins sorted
  

Installing Python modules

If you have a script that you want to keep standalone and doesn't require detailed module management, individual modules may be installed using #installModule:, e.g.:

PBApplication uniqueInstance installModule: 'MyModule'
  

If you want to manage the modules, e.g. update or specify versions, the environment's Pipfile file should be edited directly:

PBApplication uniqueInstance workingDirectory / 'Pipfile'
  

Debugger Integration

If PythonBridge is configured LePythonBridgeSettings>>#serverDebugMode: serverDebugMode: aBooleanOrNil "Set a boolean indicating whether the server should be started in debug mode" ^ self updateProperty: #serverDebugMode value: aBooleanOrNil with true, a python debugger will be opened in Gt. See Python Debugger Setup & Example for details.

Tips

If the Python server is restarted for any reason, all pages that have Python snippets that have been evaluated should be closed. This is required as the page bindings will have references to Python object registry IDs that no longer exist.