'Run a while-loop as subprocess in background

Unhappily my last post was marked as duplicate and my problem wasn't solved. So I've to phrase it a little bit different.

Below you can see my main-file(SP_Test.py) which calls another python script with an argument.

#!/usr/bin/python

import subprocess

channels = input("")

subprocess.call(['python', '/Users/christian/pyth/term/helloworld.py', str(channels)])

print("Hello")

And here you can see my processing file which gets called by the main-file and should work in the background (The original file processes continuously audio inputs).

#!/usr/bin/python

import sys

print("Hello World!")
print(sys.argv[1])

while(1):
    x=1

Now the problem is that I want to run this while-loop in the background while my main program (SP_Test.py) continues. So far it gets stuck in the loop and won't come back, so that it will never print "Hello".

I didn't find a solution in this forum what works for me. So plz help me. Thanks.


PS: Is it also possible to call the "helloworld.py" in a conda environment from the main-file?



Solution 1:[1]

subprocess.call() will wait until the command is completed, therefore blocking your program. Instead you want to use subprocess.Popen, which will run the program in the background.

Solution 2:[2]

Make sure you are flushing the output from the buffer to the terminal. I think this is what you are looking for:

hello.py

import time
while True:
    time.sleep(1)
    print("hello",flush=True)

main.py

import subprocess
cmnd = ["python3","hello.py"]
p1 = subprocess.Popen(cmnd, stdout=subprocess.PIPE)
for line in iter(p1.stdout.readline, ''):
    print(line)

p1.stdout.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Golshani
Solution 2 Ethan Lee