2015-12-23 133 views
1

我嘗試編寫一個通用函數「SubProcess_function()」我可以爲不同的目的調用。檢查是否subprocess.Popen創建東西

有什麼辦法來檢查Subprocess是否創建任何文件或文件夾?如果是這樣,我想把它們放到一個臨時文件夾中,直到完成,否則我不想做任何事情。

以下是我已經(爲的HTTrack但是想象一下,我可以打電話給我想要的):

def SubProcess_function(logger, ProcessName, Arguments=" "): 
    """ 
    The subprocess tricks: 

    preexec_fn is an arg of subprocess.Popen() which let us catch signals sent to our main program before sending them to subprocesses. 
    os.setpgrp allow us to avoid any signal to be sent to subprocess. (No ctrl + C glitches anymore) 

    The while True loop let us tryNretry even if indecise user press Ctrl+C and then asks to continue a lot of time. 

    Inconvenience: We can't answer to yes/no questions. 
    subprocess should be called in quiet mode then. 

    Usage: SubProcess_function("MyProcess", (OPTIONAL)listofargs['-r', '-t', '-f', '-m'] 
    """ 

    import signal 

    tryAgain = True 
    while tryAgain == True: 
     try: 
      logger.info('creating ChildProcess') 
      ChildProcess = subprocess.Popen([ProcessName] + Arguments, 
              preexec_fn=os.setpgrp) 
      logger.info('Waiting %s end or KeyboardInterrupt' % ProcessName) 
      ChildProcess.wait() 
      return None 
     except KeyboardInterrupt: 
      logger.warning('KeyboardInterrupt during %s execution !' % ProcessName) 
      logger.warning('Send SIGSTOP to %s' % ProcessName) 
      os.kill(ChildProcess.pid, signal.SIGSTOP) 
      query_stopCont = queryUser("\n\nSeems like you want to exit before end, are you sure ? (Current process: %s)" % ProcessName) 
      if query_stopCont == True: #User wants to stop 
       logger.info('User wants to stop, send SIGINT to %s' % ProcessName) 
       os.kill(ChildProcess.pid, signal.SIGINT) 
       tryAgain == False 
       query_rm = queryUser("\n\nStopped !\nTemp files may have been created, want to remove it ?") 
       if query_rm == True: #User wants to rm temp files 
        logger.info('User wants to stop and rm temp files.') 
        return True 
       else: #Users wants to exit and keep temp files 
        logger.info('User wants to stop and keep temp files.') 
        return False 
      else: #User wants to continue 
       logger.info('User wants to continue') 
       continue 
     break 

def exec_httrack(URL, tempDir, saveDir, tempPath, savePath, logger): 
    """ 
    This function will execute httrack with all parameters. 
    tempDir, saveDir, tempPath, savePath are given in main() as a dictionnary. 
    """ 
    import shutil 

    #Execute httrack with -q "quiet" (don't ask any question) and -O "output to" (specifies path for mirror/logfiles cache) -v "verbose" 
    httrack_args = [URL, "-q", "-O", tempDir, "-v" "-n" "-p" "-F", 
        "Mozilla 1.0, Sparc, Solaris 23.54.34"] 
    logger.warning('launching SubProcess with args= %s', httrack_args) 
    processStatus = SubProcess_function(logger, "httrack", httrack_args) 

    #Handling execution returns 
    #Execution complete, moving from temp to saveDir, delete temp 
    if processStatus is None: 
     logger.info('Execution complete !') 
     copyDirectory_function(tempPath, savePath, logger) 
     logger.info('deleting %s' % tempPath) 
     shutil.rmtree(tempPath) 
    #Execution cancelled 
    #User wants to remove temp files 
    elif processStatus is True: 
     logger.warning('Execution Cancelled !\nDeleting %s' % tempPath) 
     shutil.rmtree(tempPath) 
     #if saveDir is empty, it will be removed 
     if not os.listdir(savePath): 
      logger.warning('Execution Cancelled.') 
      logger.info('%s is empty, deleting it' % saveDir) 
      shutil.rmtree(savePath) 
     print "Temp files cleared !" 
    #User wants to quit but keep his temp files 
    else: 
     logger.info('Execution Cancelled, keeped all temp files in %s' % tempDir) 
     print("Temp files saved at: %s" % (tempDir)) 

編輯工作:改寫如下: 我希望能知道在SubProcess_function中調用的程序是否創建一些文件或某個文件夾。 在我的例子中,Httrack會。

但我想能夠使用相同的函數調用另一個不會創建任何內容的程序,那麼我可以管理我的錯誤消息。 在當前狀態下,如果調用Subprocess_function用,例如,Cowsay:

args = ["Hello world"] 
Subprocess_function(logger, "cowsay", args) 

你按CTRL + C,它會問你,如果你想刪除臨時文件,但有沒有意義。

+0

細節很重要。你能限制程序只寫入一個目錄,否則限制文件系統的區域?或者,您是否可以承受ptrace式追蹤的嚴重性能損失(如'strace'所做的那樣),還是安裝和特權升級要求來運行諸如sysdig之類的高性能追蹤工具?只是偶爾輪詢打開的文件是否可以接受,即使這意味着如果在輪詢之間創建並關閉,您可能會錯過一個文件。 –

+0

...因爲如果以上所有答案都是「否」,那麼這就是整個問題的答案。 –

+0

(如果您只是擔心清理臨時文件,您可能還會考慮您的程序是否會遵守環境變量,比如'TMPDIR'來在您指定的臨時目錄中生成內容)。 –

回答

1

subprocess.Popen()不會告訴子進程是否創建了任何文件或目錄。

存在提供更多信息的第三方psutil.Popen(),例如存在.open_files() method,其返回在過程中打開的文件的列表。

除了創建目錄或監視子進程可用的文件系統的攔截系統調用之外,可能沒有可靠的方法。

相關問題