Mar-18-2025, 09:54 AM
Hi all. I'm complete newbie on Python. I'd like to write code to connect and communicate an RPi ZeroW (with Camera) with an Android smartphone (with App Inventor app) via Bluetooth. Currently my code is very simple but seems to work:
Is there a way to catch the FileNotFoundError, then client_sock.send a message like 'command not found' and, mainly, keep the python script alive?
import bluetooth, time
from subprocess import Popen, PIPE, run
server_sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 1
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Connected to:", address)
while True:
recvdata = client_sock.recv(1024)
stringdata = recvdata.decode('utf-8')
print ("Received data:", stringdata)
# client_sock.send("data from RPi zero\n")
if (stringdata == "ipaddress"):
command = ['hostname', '-I']
result = run(command, stdout=PIPE, stderr=PIPE, text=True)
print(result.returncode, result.stdout, result.stderr)
client_sock.send("RPi IP address: ")
client_sock.send(result.stdout)The App Inventor app sends a string and listen for RPi feedback. I started by trying to send requests for line commands execution, like the 'hostname -I' as in my code above. It works fine, as soon as I run commands correctly written but if the command is an invalid command string the program exits with: File "/usr/lib/python3.11/subprocess.py", line 548, in run
with Popen(*popenargs, **kwargs) as process:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/subprocess.py", line 1024, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.11/subprocess.py", line 1901, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'hostnam'In this case the BT connection gets lost.Is there a way to catch the FileNotFoundError, then client_sock.send a message like 'command not found' and, mainly, keep the python script alive?
