Search code examples
pythonshellsubprocesspopen

run a shell command in the background and pipe stdout to a logfile with python


I have a .war file I'd like to launch via python. I want it to run in the background so no log messages appear in my terminal. Also I would love to have the actual log output put into a logfile. This is the python code I use to solve this.

I had no luck yet. The process is not detached because I cannot run other shell commands after executing the script. The logfile is created but no log-output is appended there.

EDIT: To make things more clear. I want to enhance this script to run multiple java processes in the end. Therefore this python script should spawn those java processes and die in the end. How to achieve exactly that including the functionality of redirecting stdout to a file?

#!/usr/bin/env python3
import subprocess
import re

platformDir = "./platform/"

fe = "frontend-webapp-0.5.0.war"
logfile = open("frontend-log", 'w')

process = subprocess.Popen(['java', '-jar', platformDir + fe], 
stdout=subprocess.PIPE)

for line in process.stdout:
        logFile.write(line)

Solution

  • I actually just simply had to give stdout the file handle like stdout=logFile. The solution with the for loop through the stdout would leave me in the python script process all the time

    import sys
    from subprocess import Popen, PIPE, STDOUT
    
    platformDir = "./platform/"
    
    fe = "frontend-webapp-0.5.0.war"
    
    logfile = open("frontend-log", 'ab')
    
    p = Popen(['java', '-jar', platformDir + fe], stdout=logfile, stderr=STDOUT, bufsize=1)