How do I get cpu_times of process run with psutil.Popen after it is finished but before it is terminatedHow to get the ASCII value of a character?How to get the current time in PythonHow do I check what version of Python is running my script?How do I get the number of elements in a list in Python?Python: How to determine subprocess children have all finished runningTerminal text becomes invisible after terminating subprocessGetting stdout from a tcpdump subprocess after terminating itWhy does Popen.terminate() terminate subprocess run with command interpreter (cmd.exe) on Windows?p.wait() does not wait for child process to terminate! Python 2.7Python wait for subprocess to finish before terminating

Malcev's paper "On a class of homogeneous spaces" in English

Find the result of this dual key cipher

Could an aircraft fly or hover using only jets of compressed air?

Does an object always see its latest internal state irrespective of thread?

How to draw a waving flag in TikZ

How does one intimidate enemies without having the capacity for violence?

Has there ever been an airliner design involving reducing generator load by installing solar panels?

Theorems that impeded progress

How to format long polynomial?

Can you really stack all of this on an Opportunity Attack?

Add text to same line using sed

What does "Puller Prush Person" mean?

How do I gain back my faith in my PhD degree?

Is it possible to record a short contained sound no longer than 60 milliseconds?

Client team has low performances and low technical skills: we always fix their work and now they stop collaborate with us. How to solve?

How to efficiently unroll a matrix by value with numpy?

LWC SFDX source push error TypeError: LWC1009: decl.moveTo is not a function

What is a clear way to write a bar that has an extra beat?

What's the output of a record needle playing an out-of-speed record

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Why can't we play rap on piano?

Languages that we cannot (dis)prove to be Context-Free

Replacing matching entries in one column of a file by another column from a different file

tikz convert color string to hex value



How do I get cpu_times of process run with psutil.Popen after it is finished but before it is terminated


How to get the ASCII value of a character?How to get the current time in PythonHow do I check what version of Python is running my script?How do I get the number of elements in a list in Python?Python: How to determine subprocess children have all finished runningTerminal text becomes invisible after terminating subprocessGetting stdout from a tcpdump subprocess after terminating itWhy does Popen.terminate() terminate subprocess run with command interpreter (cmd.exe) on Windows?p.wait() does not wait for child process to terminate! Python 2.7Python wait for subprocess to finish before terminating






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I would like to use the cpu_times() method of a psutil.Popen object to find the cumulative values after it has finished. I first tried the following:



p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
p.wait()
cpuTimes = p.cpu_times()


However, this results in a NoSuchProcess exception because wait() doesn't return until the process is terminated. I next tried putting the call to cpu_times() before the call to wait():



p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
cpuTimes = p.cpu_times()
p.wait()


However, this yields a response of all zeros. I presume this is because it gets called immediately after the process starts. So, I added a call to time.sleep() that would just outlast the process:



p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
time.sleep(15.) # b/c -t 15 in subprocess means it will take 15 seconds
cpuTimes = p.cpu_times()
p.wait()


This actually yields the expected value of 45 seconds (3 CPUs at 100% utilization for 15 seconds).



For a general process, however, I will not know how long it will take to finish. I would like to avoid adding an arbitrarily large sleep time just to make sure the process has finished before I make my query.



Is there a way to know that the process is done without calling wait() or other such methods upon whose return the process has terminated?










share|improve this question




























    1















    I would like to use the cpu_times() method of a psutil.Popen object to find the cumulative values after it has finished. I first tried the following:



    p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
    p.wait()
    cpuTimes = p.cpu_times()


    However, this results in a NoSuchProcess exception because wait() doesn't return until the process is terminated. I next tried putting the call to cpu_times() before the call to wait():



    p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
    cpuTimes = p.cpu_times()
    p.wait()


    However, this yields a response of all zeros. I presume this is because it gets called immediately after the process starts. So, I added a call to time.sleep() that would just outlast the process:



    p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
    time.sleep(15.) # b/c -t 15 in subprocess means it will take 15 seconds
    cpuTimes = p.cpu_times()
    p.wait()


    This actually yields the expected value of 45 seconds (3 CPUs at 100% utilization for 15 seconds).



    For a general process, however, I will not know how long it will take to finish. I would like to avoid adding an arbitrarily large sleep time just to make sure the process has finished before I make my query.



    Is there a way to know that the process is done without calling wait() or other such methods upon whose return the process has terminated?










    share|improve this question
























      1












      1








      1


      1






      I would like to use the cpu_times() method of a psutil.Popen object to find the cumulative values after it has finished. I first tried the following:



      p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
      p.wait()
      cpuTimes = p.cpu_times()


      However, this results in a NoSuchProcess exception because wait() doesn't return until the process is terminated. I next tried putting the call to cpu_times() before the call to wait():



      p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
      cpuTimes = p.cpu_times()
      p.wait()


      However, this yields a response of all zeros. I presume this is because it gets called immediately after the process starts. So, I added a call to time.sleep() that would just outlast the process:



      p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
      time.sleep(15.) # b/c -t 15 in subprocess means it will take 15 seconds
      cpuTimes = p.cpu_times()
      p.wait()


      This actually yields the expected value of 45 seconds (3 CPUs at 100% utilization for 15 seconds).



      For a general process, however, I will not know how long it will take to finish. I would like to avoid adding an arbitrarily large sleep time just to make sure the process has finished before I make my query.



      Is there a way to know that the process is done without calling wait() or other such methods upon whose return the process has terminated?










      share|improve this question














      I would like to use the cpu_times() method of a psutil.Popen object to find the cumulative values after it has finished. I first tried the following:



      p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
      p.wait()
      cpuTimes = p.cpu_times()


      However, this results in a NoSuchProcess exception because wait() doesn't return until the process is terminated. I next tried putting the call to cpu_times() before the call to wait():



      p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
      cpuTimes = p.cpu_times()
      p.wait()


      However, this yields a response of all zeros. I presume this is because it gets called immediately after the process starts. So, I added a call to time.sleep() that would just outlast the process:



      p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
      time.sleep(15.) # b/c -t 15 in subprocess means it will take 15 seconds
      cpuTimes = p.cpu_times()
      p.wait()


      This actually yields the expected value of 45 seconds (3 CPUs at 100% utilization for 15 seconds).



      For a general process, however, I will not know how long it will take to finish. I would like to avoid adding an arbitrarily large sleep time just to make sure the process has finished before I make my query.



      Is there a way to know that the process is done without calling wait() or other such methods upon whose return the process has terminated?







      python subprocess psutil






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 23:03









      tintedFrantictintedFrantic

      356




      356






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Alright, I found a solution. It was actually pretty simple, so I probably should have thought of it before posting my question, but I guess that's the way these things sometimes go.



          p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
          cpuTimes = p.cpu_times()
          while True:
          time.sleep(1e-4)
          cpuTimes = p.cpu_times() # Make sure to do this before the call to poll()
          retCode = p.poll()
          if retCode is not None:
          break


          Here, I have added a loop after starting the subprocess that contains calls to the
          cpu_times() and poll() methods for the process.



          The poll() method is a non-blocking way to check whether the subprocess has finished. By calling cpu_times() right before the call to poll(), a minuscule amount of time will have passed, so we can, for all intents and purposes, consider the last call to cpu_times() to yield an accurate result.



          Note that we would get an exception when calling cpu_times() after poll() if the process has finished. This is another reason to put the call to cpu_times() before the call to poll().



          The argument to the sleep() method is not super important but does influence how much time will elapse after the subprocess finishes and before the loop will terminate. You could probably also add some sort of generous timeout to guard against an infinite loop if the subprocess never finishes.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55290505%2fhow-do-i-get-cpu-times-of-process-run-with-psutil-popen-after-it-is-finished-but%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Alright, I found a solution. It was actually pretty simple, so I probably should have thought of it before posting my question, but I guess that's the way these things sometimes go.



            p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
            cpuTimes = p.cpu_times()
            while True:
            time.sleep(1e-4)
            cpuTimes = p.cpu_times() # Make sure to do this before the call to poll()
            retCode = p.poll()
            if retCode is not None:
            break


            Here, I have added a loop after starting the subprocess that contains calls to the
            cpu_times() and poll() methods for the process.



            The poll() method is a non-blocking way to check whether the subprocess has finished. By calling cpu_times() right before the call to poll(), a minuscule amount of time will have passed, so we can, for all intents and purposes, consider the last call to cpu_times() to yield an accurate result.



            Note that we would get an exception when calling cpu_times() after poll() if the process has finished. This is another reason to put the call to cpu_times() before the call to poll().



            The argument to the sleep() method is not super important but does influence how much time will elapse after the subprocess finishes and before the loop will terminate. You could probably also add some sort of generous timeout to guard against an infinite loop if the subprocess never finishes.






            share|improve this answer





























              0














              Alright, I found a solution. It was actually pretty simple, so I probably should have thought of it before posting my question, but I guess that's the way these things sometimes go.



              p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
              cpuTimes = p.cpu_times()
              while True:
              time.sleep(1e-4)
              cpuTimes = p.cpu_times() # Make sure to do this before the call to poll()
              retCode = p.poll()
              if retCode is not None:
              break


              Here, I have added a loop after starting the subprocess that contains calls to the
              cpu_times() and poll() methods for the process.



              The poll() method is a non-blocking way to check whether the subprocess has finished. By calling cpu_times() right before the call to poll(), a minuscule amount of time will have passed, so we can, for all intents and purposes, consider the last call to cpu_times() to yield an accurate result.



              Note that we would get an exception when calling cpu_times() after poll() if the process has finished. This is another reason to put the call to cpu_times() before the call to poll().



              The argument to the sleep() method is not super important but does influence how much time will elapse after the subprocess finishes and before the loop will terminate. You could probably also add some sort of generous timeout to guard against an infinite loop if the subprocess never finishes.






              share|improve this answer



























                0












                0








                0







                Alright, I found a solution. It was actually pretty simple, so I probably should have thought of it before posting my question, but I guess that's the way these things sometimes go.



                p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
                cpuTimes = p.cpu_times()
                while True:
                time.sleep(1e-4)
                cpuTimes = p.cpu_times() # Make sure to do this before the call to poll()
                retCode = p.poll()
                if retCode is not None:
                break


                Here, I have added a loop after starting the subprocess that contains calls to the
                cpu_times() and poll() methods for the process.



                The poll() method is a non-blocking way to check whether the subprocess has finished. By calling cpu_times() right before the call to poll(), a minuscule amount of time will have passed, so we can, for all intents and purposes, consider the last call to cpu_times() to yield an accurate result.



                Note that we would get an exception when calling cpu_times() after poll() if the process has finished. This is another reason to put the call to cpu_times() before the call to poll().



                The argument to the sleep() method is not super important but does influence how much time will elapse after the subprocess finishes and before the loop will terminate. You could probably also add some sort of generous timeout to guard against an infinite loop if the subprocess never finishes.






                share|improve this answer















                Alright, I found a solution. It was actually pretty simple, so I probably should have thought of it before posting my question, but I guess that's the way these things sometimes go.



                p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
                cpuTimes = p.cpu_times()
                while True:
                time.sleep(1e-4)
                cpuTimes = p.cpu_times() # Make sure to do this before the call to poll()
                retCode = p.poll()
                if retCode is not None:
                break


                Here, I have added a loop after starting the subprocess that contains calls to the
                cpu_times() and poll() methods for the process.



                The poll() method is a non-blocking way to check whether the subprocess has finished. By calling cpu_times() right before the call to poll(), a minuscule amount of time will have passed, so we can, for all intents and purposes, consider the last call to cpu_times() to yield an accurate result.



                Note that we would get an exception when calling cpu_times() after poll() if the process has finished. This is another reason to put the call to cpu_times() before the call to poll().



                The argument to the sleep() method is not super important but does influence how much time will elapse after the subprocess finishes and before the loop will terminate. You could probably also add some sort of generous timeout to guard against an infinite loop if the subprocess never finishes.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 26 at 14:40

























                answered Mar 26 at 1:04









                tintedFrantictintedFrantic

                356




                356





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55290505%2fhow-do-i-get-cpu-times-of-process-run-with-psutil-popen-after-it-is-finished-but%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript