Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export command line output to a file in Python

Tags:

python

Here's my code to execute a jar file in Python:

import os
os.system("java -jar xyz.jar")

I can see the output on terminal, but want to store it in a file. How can I do that?

like image 927
dev Avatar asked Jun 10 '26 10:06

dev


1 Answers

With subprocess.call you can pipe outputs (stdout, stderr or both) directly into file:

import subprocess
subprocess.call("java -jar xyz.jar", shell=True, stdout=open('outfile.txt', 'wt'), stderr=subprocess.STDOUT)

Note that I added shell=True parameter, which is required if your application requires shell-specific variables (such as where Java is located).

Also note that in the above call, the output streams are handled as follows:

  • stderr stream is piped to stdout, and
  • stdout is piped to outfile

More details on stream configurations are available in subprocess manual page.

like image 56
jsalonen Avatar answered Jun 11 '26 22:06

jsalonen