2015-04-22 65 views
6

我使用Python模塊subprocess調用程序,並使用以下命令重定向可能STD錯誤的特定文件:子進程錯誤文件

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

我想的是,「std.err」文件只有在出現錯誤時才被創建,但如果沒有錯誤,則使用上面的命令代碼將創建一個空文件。 我如何才能使python只創建一個文件,如果它不是空的?

我可以檢查執行後,如果該文件是空的,以防萬一刪除它,但我正在尋找一種「乾淨」的方式。

回答

2

你可以使用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) 
+0

感謝它的完美運作。唯一的辦法是命名與用於存儲錯誤的var不同的文件。 – Marco

+0

@Marco,真的,我只是複製粘貼,我總是通常使用'f'。 –

0

你可以創建你自己的上下文管理器來處理你的清理工作 - 你不能真正做你在這裏描述的東西,這些東西歸結爲問你如何看待未來。像這樣的東西(有更好的錯誤處理等):

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") 

將是文件的背後留下的文字中有一個單一的線,或者什麼也不留下。

相關問題