B4J Code Snippet [IoT] RaspBerry: Execute Python script with parameters from B4J

KMatle

Expert
Licensed User
With this snippet you can

- call a Python script (command line) on you Raspberry (or other programs by changing the parameters)
- with parameters
- in "sh_ProcessCompleted" you will get the command line output in "StdOut"

You need the "jShell" library (libs tab in b4j -> add it)

B4X:
Sub AppStart (Args() As String)
   Dim sh As Shell
   sh.Initialize("sh", "python", Array As String("gpio.py", "w", "B4J is", "great"))
   sh.WorkingDirectory = "/home/"
   sh.Run(10000)

   StartMessageLoop
End Sub

Sub sh_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
   If Success And ExitCode = 0 Then
     Log("Success")
     Log(StdOut)
   Else
     Log("Error: " & StdErr)
   End If
   'ExitApplication
End Sub
Above you see that the call is done by giving 4 parameters.

The first one is the name of the script you want to call. All others will be given to the script as input.

Working dicrectory: Where your script is...

In Python you can get them with:

B4X:
import sys

#put the parameters in a list called "argv"
from sys import argv

print ("Start")

#first parameter is always the script's name
first, second, third, fourth = argv 
print (first)
print (second)
print (third)
print (fourth)

if second=="xxx":
    do1
if second=="yyy":
    do2
if second=="zzzz":
    print (third)

print ("End")
Note: Python is a funny language. Spaces are used to indicate if a line is corresponding to the one before. So there is no End If. Leading spaces = the code after belongs to the IF...
 
Last edited:
Top