Basic usage of the Python Bridge
Assuming everything went well with Getting started with the Python Bridge, we can now test the infrastructure in several ways, all of which compute the same result.
There is a simple fraction that approximates π surprisingly well.
333/106 closeTo: Float pi
Programmatic Usage
Let's find out if Python thinks the same. Here we use a resultExpression .
PBApplication do: [ :application | application newCommandStringFactory resultExpression: '333/106'; sendAndWait ]
Notice how we get a native Float
back.
Using a script you can send several lines of Python code, though only the resultExpression is used to compute the value to return.
PBApplication do: [ :application | application newCommandStringFactory script: 'pi = 333/106'; resultExpression: 'pi'; sendAndWait ]
Another interface works with Python AST structures instead of textual source code.
PBApplication do: [ :application | application newCommandFactory << (P3GBinaryOperator new left: 333; right: 106; operator: $/; yourself); sendAndWait ]
Do note that LanguageLinkApplication>>#do:
will use the unique instance when it is up and running, otherwise it will open and close a connection for single use which would be less efficient. The expressions above are way slower when the global unique instance is not yet running.
The fastest way to test the working of the bridge infrastructure is probably PBApplication>>#isWorking
which tests the global unique instance.
PBApplication isWorking
Python Snippets
Yet another way to use the Python Bridge is through Python Snippets in a Lepiter page. These are like Pharo Snippets. The contain execute Python code.
333/106
Python snippets always use the global PBApplication instance. You can see the exact Python server port being used in the top right. Clicking on that indicator brings up a tool that shows some details about the PythonBridge as well as buttons: a start/stop toggle, a restart and inspect button.
Notice how the result of the expression is not a native Float
but a proxy object. Using the down arrow action button at the top right you can convert primitive objects into their native equivalent.
Snippets on a page can share variables. Consider the following Pharo assignments.
numerator := 333. denominator := 106.
Now we can refer to them from Python (after you run the assignments).
fraction = numerator / denominator str(fraction)
There is another page about the Python snippet.