检查subprocess.Popen是否创建了一些东西

时间:2015-12-23 12:45:24

标签: python subprocess

我尝试编写一个泛型函数“SubProcess_function()”我可以为不同的目的调用。

有没有办法检查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会。

但我希望能够使用相同的函数调用另一个不会创建任何内容的程序,然后我就可以管理我的错误消息了。 在当前状态下,如果使用例如Cowsay:

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

你按ctrl + c它会询问你是否要删除临时文件但是没有意义。

1 个答案:

答案 0 :(得分:1)

subprocess.Popen()不会告诉子进程是否创建了任何文件或目录。

第三方psutil.Popen()提供了更多信息,例如,.open_files() method会返回在此过程中打开的文件列表。

除了拦截创建目录或监视子进程可用的文件系统的系统调用之外,可能没有可靠的方法。