0

I am trying to write a Raspberry Pi Python-3 script that turns on an IR receiver using a call to os.system() with mode2 as the argument.

When this line of code executes, the mode2 process starts and runs properly (I can see it working in the open terminal) but the rest of the program stalls. There is additional code that needs to run after the os.system("mode2") call.

My question is: How do I start the mode2 process and still allow the rest of the python-3 code to continue executing?

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Carter ash
  • 67
  • 8
  • 2
    You're probably looking for [`subprocess`](https://docs.python.org/3/library/subprocess.html), which mostly replaces `os.system` functionality. `Popen` can be used to start processes, and by default you have to explicitly `.wait()` for a process to finish, otherwise it executes independently. – Alexander L. Hayes Nov 03 '22 at 19:30
  • @AlexanderL.Hayes thanks for the information. The command opens a running process of gathering any IR-sensor data that the sensor receives. Is there a way to make python call the command to the shell and then return to the python program and continue? – Carter ash Nov 07 '22 at 15:56
  • If you need to asynchronously poll the `mode2` process for data, there may be a few extra steps. I've added an answer that might solve this question. – Alexander L. Hayes Nov 07 '22 at 16:10

1 Answers1

0

Here is a minimal way to approach this:

A bash script my_process.sh sleeps for 10 seconds, then writes the string "Hello" into a world.txt file:

#!/usr/bin/env bash

sleep 10; echo 'Hello' > world.txt

A python script starts my_process.sh, and prints "Done from Python" when finished.

# File: sample_script.py
import subprocess

if __name__ == "__main__":
    subprocess.Popen(["bash", "my_process.sh"])
    print("Done from Python.")

Running sample_script.py will write "Done from Python" to the console, and the world.txt file will appear about ten seconds later.

Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34