xetra11
xetra11

Reputation: 8855

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)

Upvotes: 5

Views: 3072

Answers (2)

xetra11
xetra11

Reputation: 8855

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)

Upvotes: 0

relay
relay

Reputation: 199

Here is how you can try it using Python 3:

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=PIPE, stderr=STDOUT, bufsize=1)

for line in p.stdout: 
    sys.stdout.buffer.write(line) 
    logfile.write(line)

Upvotes: 1

Related Questions