Monday, August 26, 2019

How to Run two python files Concurrently on Raspberry Pi 3

Running two python files concurrently can be useful when there are background processes, for example when there is a continuous data insert to a database table in the background and the main application has a GUI. This helps to segregate the code into sections and also to debug code separately. This also reduces the code complexity by reducing the number of lines as well as separating unrelated code into blocks.
It is particularly useful while opening a python app via desktop icon. As only the main python file needs to be mentioned in the .desktop file. More details read 
Python 2.7 has a library that can be imported called subprocess. You can view the details of this library in this link.
Use the Popen class to call the second background python file from the main python file as given below
subprocess.Popen() – This is the call to the Popen class
(“python /home/pi/Documents/insert_ras.py 0”, shell = True) – These are the popen class arguments that specify the file location and the command to be run on the shell script.
‘0’ represents the buffer size, for this particular case there is no buffer used as this is a background process to insert data to a database and there is no return output. shell  = True means that the string “python /home/pi/Documents/insert_ras.py 0” has to be executed as a shell command. 
It is important to note that #!/usr/bin/env python  must be included in both the python files the main python file and the sub processes python file.

No comments:

Post a Comment