子进程错误文件
问题描述:
我使用Python模块subprocess
调用程序,并使用以下命令重定向可能STD错误的特定文件:子进程错误文件
with open("std.err","w") as err:
subprocess.call(["exec"],stderr=err)
我想的是,“std.err”文件只有在出现错误时才被创建,但如果没有错误,则使用上面的命令代码将创建一个空文件。 我如何才能使python只创建一个文件,如果它不是空的?
我可以检查执行后,如果该文件是空的,以防万一删除它,但我正在寻找一种“干净”的方式。
答
你可以使用POPEN,检查标准错误:
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)
在一个侧面说明,如果你关心你应该使用check_call
返回代码,你可以用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)
答
你可以创建你自己的上下文管理器来处理你的清理工作 - 你不能真正做你在这里描述的东西,这些东西归结为问你如何看待未来。像这样的东西(有更好的错误处理等):
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)
...然后是这样的:
with maybeFile("myFileName.txt") as f:
import random
if random.random() < 0.5:
f.write("There should be a file left behind!\n")
将是文件的背后留下的文字中有一个单一的线,或者什么也不留下。
感谢它的完美运作。唯一的办法是命名与用于存储错误的var不同的文件。 – Marco
@Marco,真的,我只是复制粘贴,我总是通常使用'f'。 –