[Tutor] Vol 127, Issue 15

Alan Gauld alan.gauld at btinternet.com
Sat Sep 6 00:11:48 CEST 2014


On 05/09/14 22:32, Crush wrote:

> count = 0
> while count < 3:
>      count += 1
>      Subprocess.Popen('command')

This is not real code since 'command' is presumably
not the real command and subprocess is not spelled with an 'S'...
Its usually better to post real code.

> if count == 3:
>      sys.exit()
>
> This does not work as I want it to;

No, it does what you asked it to.
Computers cannot guess your intentions, they
only do what you tell them.

> 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.

Let's translate that to Python

count = 1
error = subprocess.Popen('command')  # execute once
while error and count < 3:           # if error and less than 3
    error = subprocess.call('command')   # on success call() returns zero
    count += 1

 > If count equals 3, i want it to give up and exit or do something else.

else:
    raise SystemExit # or something else

Is that the sort of thing?

PS
If you really must use Popen then detecting the error condition is 
slightly more work: You need to explicitly assign the Popen object's 
returncode value to error.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list