Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subprocess error file

I'm using the python module subprocess to call a program and redirect the possible std error to a specific file with the following command:

with open("std.err","w") as err:
    subprocess.call(["exec"],stderr=err)

I want that the "std.err" file is created only if there are errors, but using the command above if there are no errors the code will create an empty file. How i can make python create a file only if it's not empty?

I can check after execution if the file is empty and in case remove it, but i was looking for a "cleaner" way.

like image 795
Marco Avatar asked Apr 22 '15 23:04

Marco


People also ask

What is subprocess in Python?

Subprocess in Python is a module used to run new codes and applications by creating new processes. It lets you start new applications right from the Python program you are currently writing. So, if you want to run external programs from a git repository or codes from C or C++ programs, you can use subprocess in Python.

What is Popen in Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.

What is Popen in subprocess?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.


1 Answers

You could use Popen, checking stderr:

from subprocess import Popen,PIPE

proc = Popen(["EXEC"], stderr=PIPE,stdout=PIPE,universal_newlines=True)

out, err = proc.communicate()
if err:
    with open("std.err","w") as f:
        f.write(err)

On a side note, if you care about the return code you should use check_call, you could combine it with a NamedTemporaryFile:

from tempfile import NamedTemporaryFile
from os import stat,remove
from shutil import move

try:
    with NamedTemporaryFile(dir=".", delete=False) as err:
        subprocess.check_call(["exec"], stderr=err)
except (subprocess.CalledProcessError,OSError) as e:
    print(e)


if stat(err.name).st_size != 0:
    move(err.name,"std.err")
else:
    remove(err.name)
like image 159
Padraic Cunningham Avatar answered Oct 29 '22 08:10

Padraic Cunningham