Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
Using a `with` context for closing the file automatically; added line breaks for easy reading
Source Link
jdi
  • 93k
  • 20
  • 174
  • 208

I see that this is a rather old post but just in case someone is still searching for a way to do this:

proc = subprocess.Popen(["ping", "localhost"],  stdout=subprocess.PIPE,  stderr=subprocess.PIPE) log_file =with open("logfile.txt", "w") as log_file:  while proc.poll() is None:   line = proc.stderr.readline()   if line:   print "err: " + line.strip()   log_file.write(line)   line = proc.stdout.readline()   if line:   print "out: " + line.strip()   log_file.write(line) log_file.close() 

I see that this is a rather old post but just in case someone is still searching for a way to do this:

proc = subprocess.Popen(["ping", "localhost"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) log_file = open("logfile.txt", "w") while proc.poll() is None: line = proc.stderr.readline() if line: print "err: " + line.strip() log_file.write(line) line = proc.stdout.readline() if line: print "out: " + line.strip() log_file.write(line) log_file.close() 

I see that this is a rather old post but just in case someone is still searching for a way to do this:

proc = subprocess.Popen(["ping", "localhost"],  stdout=subprocess.PIPE,  stderr=subprocess.PIPE) with open("logfile.txt", "w") as log_file:  while proc.poll() is None:   line = proc.stderr.readline()   if line:   print "err: " + line.strip()   log_file.write(line)   line = proc.stdout.readline()   if line:   print "out: " + line.strip()   log_file.write(line) 
Source Link
Ben
  • 63
  • 1
  • 7

I see that this is a rather old post but just in case someone is still searching for a way to do this:

proc = subprocess.Popen(["ping", "localhost"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) log_file = open("logfile.txt", "w") while proc.poll() is None: line = proc.stderr.readline() if line: print "err: " + line.strip() log_file.write(line) line = proc.stdout.readline() if line: print "out: " + line.strip() log_file.write(line) log_file.close() 
Post Made Community Wiki by Ben