Execute external Python script
The following article describes how an external Python script located on the control cabinet can be executed directly via horstOS.
The following steps serve as an exemplary approach. Further actions may need to be carried out.
1. Making the Python script executable
To make the created Python script executable, the first step is to find the installation path of Python. This can be done by using the following command in the console:
which python3Next, the path obtained should be added to the Python script in the top line as the following command:
#!“PFAD“Replace "PFAD" with the output obtained from the command "which python3". Therefore, the command could look like this:
#!/usr/bin/python3Next, you can test if the Python script can be started via the console.
If you encounter the error "python linux bad interpreter ^M no such file or directory," it means that the line endings are not interpreted correctly. Unix is looking for ^M in the file or path. This issue can occur when the Python script is created on a Windows PC.
To resolve this, you can make the Python script Unix-compatible by installing dos2unix on the control panel.
To do this, log in as the root user:
su -l rootPlease request the password directly from fruitcore.
To install dos2unix:
apt-get install dos2unixThe script can be converted by using the following command:
dos2unix FILENAMEReplace FILENAME with the name of the Python script and its corresponding path.
2. Starting the script via horstOS
The script can be started via horstOS using the following commands: You will need to specify the name of the Python script along with its path.
// Windows PC via console
var PyScript = "cmd /c start python C:\\Test_py.py";
p = java.lang.Runtime.getRuntime().exec(PyScript);
// With Linux terminal opening:
var PyScript = "xterm -e python /home/fruitcore/Test_py.py";
p = java.lang.Runtime.getRuntime().exec(PyScript);
// The error code of the execute method can be viewed with show_info(p).When executing the script, the synchronization between the Python script and the horstOS/FX script must be observed. After the Python script is executed, the horstOS/FX script is immediately continued at the same time. This means that if, for example, a socket connection is used for communication between the scripts, in most cases a sleep(1000); must be used after the execute method. This gives the server enough time to request the connection from the client. If horstOS/FX is to wait until the Python script has finished executing, the command
p = p.waitFor(); can be used.