To launch a program in a non blocking way but still being able to see the output of program, the program has to be launched in a separate thread or process. Ryan has posted a nice code sample here: Python Subprocess.Popen from a thread

Keep in mind that the last line print myclass.stdout will print the output how it appears at that time. If program is just being launched, it might not have output anything at all, so your code should probably read from myclass.stdout until it receives the line you need.

Answer from fest on Stack Overflow
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
1 day ago - The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions: ... Information about how the subprocess module ...
Top answer
1 of 2
1

To launch a program in a non blocking way but still being able to see the output of program, the program has to be launched in a separate thread or process. Ryan has posted a nice code sample here: Python Subprocess.Popen from a thread

Keep in mind that the last line print myclass.stdout will print the output how it appears at that time. If program is just being launched, it might not have output anything at all, so your code should probably read from myclass.stdout until it receives the line you need.

2 of 2
0

You can run it in a thread (so that it doesn't block your code from running), and get the output until you get the second line, then wait for it to terminate. This is an example that will read the output from the command dir /s on Windows to get all the directory listing.

import subprocess, thread, time

def run():
    global can_break

    args = ["dir", "/s"]
    shell = True

    count = 0
    popen = subprocess.Popen(args, shell=shell, stdout=subprocess.PIPE)
    while True:
        line = popen.stdout.readline()
        if line == "": continue
        count += 1
        if count == 2:
            do_something_with(line)
            break

    print "We got our line, we are waiting now"
    popen.wait()
    print "Done."
    can_break = True

def do_something_with(line):
    print '>>> This is it:', line

thread.start_new_thread(run, tuple())

can_break = False
while not can_break:
    print 'Wait'
    time.sleep(1)

print 'Okay!'

Output will look like:

Wait
>>> This is it:  Volume Serial Number is XXXX-XXXX

We got our line, we are waiting now
Wait
Wait
Wait
.
.
.
Done.
Wait
Okay!
Discussions

How to run Python's subprocess and leave it in background - Stack Overflow
I have seen A LOT of posts regarding my topic, but actually I didn't find a solution for my problem. I'm trying to run a subprocess in a background, without wait for subprocess execution. The called More on stackoverflow.com
🌐 stackoverflow.com
Start a background process in Python - Stack Overflow
I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I More on stackoverflow.com
🌐 stackoverflow.com
python - Execute Subprocess in Background - Stack Overflow
I have a python script which takes an input, formats it into a command which calls another script on the server, and then executes using subprocess: import sys, subprocess thingy = sys.argv[1] c... More on stackoverflow.com
🌐 stackoverflow.com
Explicit support for backgrounded subprocesses
Overview Kind of an odd duck, but this came out of an internal need at my dayjob and I think it's worth examining for public use. The tl;dr use case is to have a (long running in their case, bu... More on github.com
🌐 github.com
18
December 6, 2019
🌐
Reddit
reddit.com › r/learnpython › how can i make use subprocess to run process in background and write output to a file line by line?
r/learnpython on Reddit: How can I make use subprocess to run process in background and write output to a file line by line?
February 13, 2019 -

I am wondering if this can be achieved with subprocess. Run the process and write output

I have two files:

main.py:

import subprocess
import shlex


def main():
	command = 'python test_output.py'
	logfile =  open('output', 'w')
	proc = subprocess.Popen(shlex.split(command), stdout=logfile)


if __name__ == "__main__":
	main()

and test_output.py:

from time import sleep
import os

for i in range(0, 30):
	print("Slept for => ", i+1, "s")
	sleep(1)
os.system("notify-send completed -t 1500")

The output of the process is written to logfile once the child process is completed. Is there any way to:

  • Start child process from main and exit it (like it does now).

  • Keep running the child process in background.

  • As child process produces an output, write it immediately to logfile. (Don't wait for the child process to finish, as it does now.)

  • Or write to Named Pipes alternatively but don't keep it waiting to read (non-blocking)

Is it possible to do everything in background, without keeping main.py waiting?

🌐
Medium
medium.com › @maheshwar.ramkrushna › running-python-scripts-as-background-processes-using-subprocess-pythonw-exe-and-other-methods-ed5316dd5256
Running Python Scripts as Background Processes: Using subprocess, pythonw.exe, and Other Methods | by Ramkrushna Maheshwar | Medium
February 5, 2025 - Write a Python script to define the service behavior. Install and start the service by running the appropriate commands in the Command Prompt. This approach offers maximum control over how your script behaves when running as a background service. If your background script generates output, it’s a good idea to redirect that output to a log file so you can monitor it without needing a terminal window. import subprocess with open('script_output.log', 'w') as log_file: subprocess.Popen(['python', 'script.py'], stdout=log_file, stderr=log_file)
🌐
GitHub
gist.github.com › keymon › 1498154
Implements run a process in background from python, capturing the output in a buffer and allowing set callbacks for the output. · GitHub
Implements run a process in background from python, capturing the output in a buffer and allowing set callbacks for the output. - background_process.py
🌐
Dataquest
dataquest.io › blog › python-subprocess
Python Subprocess: The Simple Beginner's Tutorial (2023)
February 19, 2025 - The run function of the subprocess module in Python is a great way to run commands in the background without worrying about opening a new terminal or running the command manually.
🌐
DataCamp
datacamp.com › tutorial › python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - For example, you can use the subprocess ... data analysis, and machine learning tasks. You can use the subprocess module to run scripts as background processes so that they continue running after the main program exits....
Find elsewhere
Top answer
1 of 11
532

While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.

Example for your case:

import subprocess
subprocess.Popen(["rm","-r","some.file"])

This will run rm -r some.file in the background. Note that calling .communicate() on the object returned from Popen will block until it completes, so don't do that if you want it to run in the background:

import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate()  # Will block for 30 seconds

See the documentation here.

Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.

2 of 11
106

Note: This answer is less current than it was when posted in 2009. Using the subprocess module shown in other answers is now recommended in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(or, alternatively, you may try the less portable os.P_NOWAIT flag).

See the documentation here.

🌐
Digitaldesignjournal
digitaldesignjournal.com › python-subprocess-run-in-background-with-example
Python Subprocess Run In Background [With Example]
September 24, 2023 - If you don’t need to interact ... process in Python and not wait for it to finish, you can use the subprocess.Popen class and then simply not call the wait() method....
🌐
Python
docs.python.org › 3.2 › library › subprocess.html
17.1. subprocess — Subprocess management — Python v3.2.6 documentation
December 12, 2014 - Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command’s output. Example: ... Availability: UNIX. On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-subprocess-to-run-external-programs-in-python-3
How To Use subprocess to Run External Programs in Python 3 | DigitalOcean
July 30, 2020 - The input keyword argument can ... output of one program as the input to another. The subprocess module is a powerful part of the Python standard library that lets you run external programs and inspect their outputs easily....
🌐
YouTube
youtube.com › logicgpt
python subprocess run in background - YouTube
Instantly Download or Run the code at https://codegive.com in python, the subprocess module allows you to spawn new processes, connect to their input/output...
Published   February 23, 2024
Views   13
🌐
GitHub
github.com › pyinvoke › invoke › issues › 682
Explicit support for backgrounded subprocesses · Issue #682 · pyinvoke/invoke
December 6, 2019 - If one says pty=True, we get even stranger behavior where the subprocess appears to either not run or exit instantly (pending investigation - this is less critical for now) I've determined that the child process does actually get assigned as a child of init even in this scenario, but Invoke still "blocks" to completion because of those reader threads. If we temporarily neuter the reader threads, we get the same behavior as under Fabric 1 - control returns to the run caller immediately, and the Python process can even exit without affecting the now orphaned child.
Author   bitprophet
🌐
Indigodomo
forums.indigodomo.com › indigo home › board index › indigo help › extending indigo › plugin sdk and development
Starting and communicating with a background process - Indigo Domotics
January 11, 2021 - It appears that you need to tell the spawned python process to not buffer its output by passing the "-u" flag. My demo below works with the "-u" and it does nothing at all without the flag. Here is my quick example: ... [Aarons-MacBook-Pro:~/experiments/python_proc_comms] Aaron% cat runner.py import time def main(): while True: print(time.time()) time.sleep(1) if __name__ == "__main__": main() ... [Aarons-MacBook-Pro:~/experiments/python_proc_comms] Aaron% cat executor.py from subprocess import Popen, PIPE def main(): print("Starting runner...") p = Popen(["/usr/bin/python3", "-u", "runner.py"], stdout=PIPE, bufsize=1) # Note the "-u" flag...
🌐
Code Maven
code-maven.com › slides › python › subprocess-background.html
subprocess in the background
In this example we still collect the standard output and the standard error at the end of the process. examples/process/run_process_polling.py · import subprocess import sys import time def run_process(command, timeout): print("Before Popen") proc = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE, ) print("After Popen") while True: poll = proc.poll() # returns the exit code or None if the process is still running print(f"poll: {poll}") time.sleep(0.5) # here we could actually do something useful timeout -= 0.5 if timeout <= 0: break if poll is not None: break prin
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › python's-subprocess-run-method-is-held-up-by-stdout-4175613294
Python's subprocess.run() method is held up by stdout
September 5, 2017 - Hi all, Here are a few short scripts that demonstrate the issue that I had: Parent script: Code: #!/bin/bash echo "PARENT: about to start the
🌐
Stack Overflow
stackoverflow.com › questions › 42112112 › run-python-subprocess-in-background-with-log-output
Run python subprocess in background with log output - Stack Overflow
Change signal.SIGHUP to signal.SIGKILL if you like os.kill(int(pid), signal.SIGKILL) # Do something else here print("Killed Process") print(pid) print(process) return True return False if proc_check(processname): print("all good") else: with open('apiServer.log', 'w') as apiLog: with open('apiServer.err', 'w') as errLog: command = "cd /root/ProjectAthena/APIServer/" \ "&& . ./venv/bin/activate " \ "&& PYTHONPATH=. asphalt run /root/ProjectAthena/APIServer/config.yml" ApiHelp = subprocess.Popen(command, stderr=errLog,stdout=apiLog, shell=True) print("subprocces spawned!") ApiHelp.communicate() I want to run a server to supply a API to another program. As the server has to run all the time (with output to a file) I used a function to check if my asphalt server is already running.
🌐
Reddit
reddit.com › r/pythonhelp › making a subprocess run in the background so a loop can continue.
r/pythonhelp on Reddit: Making a subprocess run in the background so a loop can continue.
May 26, 2023 -

Hello,

 

Level: Beginner

 

The code below has a loop that listens out for keypresses from an attached 3x4 keypad. If certain keys are pressed it plays a sound from a local file using aplay, an audio stream from an URL using mplayer, or shutdowns the machine

 

When playing the .wav in aplay, once the sound is played the loop continues and restarts, monitoring for other keypad presses. This is fine. However when key 3 or 4 are pressed and the radio streams begin to play, they never end so, the loop never continues.

 

I would like to be able to switch between radio stations essentially. How can I achieve this in the most proper way? It goes without saying I only want one instance of mplayer to be playing one radio station at a time.

 

All help is appreciated.

 

import time
import digitalio
import board
import adafruit_matrixkeypad
import os
import subprocess



# rows and columns are mixed up for https://www.adafruit.com/product/3845
cols = [digitalio.DigitalInOut(x) for x in (board.D27,board.D4,board.D10)]
rows = [digitalio.DigitalInOut(x) for x in (board.D17,board.D11,board.D9,board.D22)]

keys = ((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12))

keypad = adafruit_matrixkeypad.Matrix_Keypad(rows, cols, keys)

print("Program is Running") #This is confirm that the program is running and ready for input
subprocess.run(['aplay', '/home/pi/Sounds/Ding.wav']) #This is confirm that the program is running and ready for input

while True:
    keys = keypad.pressed_keys
    if keys == [1]:
        subprocess.run(['aplay', '/home/pi/Sounds/Clapping.wav'])
    if keys == [2]:
        subprocess.run(['aplay', '/home/pi/Sounds/Cheering.wav'])
    if keys == [3]:
        subprocess.run(['mplayer', 'http://playerservices.streamtheworld.com/pls/WDUZFM.pls'])
    if keys == [4]:
        subprocess.run(['mplayer', 'https://live.wostreaming.net/direct/goodkarma-wktifmmp3-ibc2'])
    if keys == [10, 11, 12]: 
        os.system("sudo shutdown -h now")
    time.sleep(1.5)