Subprocess Error File

I use the python subprocess module to invoke a program and redirect a 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 the std.err file to be created only if there are errors, but using the above command, if there are no errors, the code will create an empty file. How can I make python create a file only if it is not empty?

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

+6
source share
2 answers

You can use Popen by 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 the side of the note, if you need a return code, you should use check_call , you can combine it with 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) 
+2
source

You can create your own context manager to handle the cleanup for you — you cannot really do what you describe here, and it comes down to asking how you can see in the future. Something like this (with better error handling, etc.):

 import os from contextlib import contextmanager @contextmanager def maybeFile(fileName): # open the file f = open(fileName, "w") # yield the file to be used by the block of code inside the with statement yield f # the block is over, do our cleanup. f.flush() # if nothing was written, remember that we need to delete the file. needsCleanup = f.tell() == 0 f.close() if needsCleanup: os.remove(fileName) 

... and then something like:

 with maybeFile("myFileName.txt") as f: import random if random.random() < 0.5: f.write("There should be a file left behind!\n") 

either leaves a file with one line of text, or nothing remains.

0
source

Source: https://habr.com/ru/post/985727/


All Articles