[Tutor] Vol 127, Issue 15

Steven D'Aprano steve at pearwood.info
Sat Sep 6 03:26:47 CEST 2014


On Fri, Sep 05, 2014 at 05:32:34PM -0400, Crush wrote:

> Ok nevermind, I did not figure it out. My code...

You say "Never mind", which normally means the problem is solved, but 
then you say it doesn't do what you want. So do you want help or not? 
:-)


> count = 0
> while count < 3:
>     count += 1
>     Subprocess.Popen('command')
> if count == 3:
>     sys.exit()
> 
> This does not work as I want it to; it consecutively executes the 
> command three times in a row. I only want it to execute once. However, 
> if there is an error, I want it to try again, but only if count does 
> not equal 3. If count equals 3, i want it to give up and exit or do 
> something else.

Here is a sketch of what you can do (untested):

for count in range(3):
    result = subprocess.popen("command")
    if result == 0:
        # Success! We're done.
        break  # break out of the loop.
# Be careful of the indentation here. The next line needs to be
# lined up with the "for".
else:
    # We never escaped from the for loop, so the command
    # never ran successfully.
    print("Exiting with failure")
    sys.exit(1)
sys.exit(0)  # Zero, or blank, means success.


Strictly speaking, you don't even need that sys.exit, since Python will 
exit when it reaches the end of the program.

Please don't reply to digests without changing the subject line to 
something meaningful, and without trimming the unnecessary quoting. I've 
had to delete about nine pages of quoted text which is irrelevant to 
your post, all of which I've seen before.

The best way is to NOT use digests. They are more trouble than they are 
worth.



-- 
Steven


More information about the Tutor mailing list