[newbie] problem with if then

Roy Smith roy at panix.com
Sun Jun 9 16:23:55 EDT 2013


In article 
<cd1be83a-f560-4024-90b3-697a51bb1bb0 at g7g2000vbv.googlegroups.com>,
 Jean Dubois <jeandubois314 at gmail.com> wrote:

> I'm writing some code to check whether an url is available or not,
> therefore I make use of a wget-command in Linux and then check whether
> this is successful

In general, "shelling out" to run a command-line utility should be the 
last resort.  It's slower, and more complicated, than doing it in pure 
python.  You would only call a shell command if there was no other way.

Fortunately, in Python, there is another way.  Several, in fact.

The most straight-forward is to use the built-in urllib2 module 
(http://docs.python.org/2/library/urllib2.html).

If you're going to be doing anything complicated (i.e. setting optional 
headers, managing cookies, etc), you probably want to be looking at the 
excellent third-party module, requests (http://python-requests.org).

In any case, given your code:

> #!/usr/bin/env python
> import sys
> import os
> from datetime import datetime, timedelta
> today=datetime.now()
> yesterday= datetime.now() - timedelta(days=1)
> daybeforeyesterday= datetime.now() - timedelta(days=2)
> collection = [daybeforeyesterday,yesterday,today]
> for thisday in collection:
>      checkavailablestring='wget -q -O -
> http://www.deredactie.be/cm/vrtnieuws/videozone/programmas/journaal/EP_'+thisd
> ay.strftime("%y%m%d")+'_JO7
> >/dev/null ; echo $?'
>      if os.system(checkavailablestring)==0:
>           print thisday, 'stream is available'
>      else:
>           print thisday, 'stream is not available'

I would break the debugging down into several parts.  First, are you 
generating the command string properly?  Try printing out 
checkavailablestring before you call os.system() to make sure it's what 
you think it is.

Next, once you're sure you've got the correct string, run it manually in 
the shell and see what it does.

Next, are you sure you're using os.system() correctly?  Try running:

os.system("/bin/true")

and

os.system("/bin/false")

and make sure you get the results you think you should.  But, really, 
once you've done all that (and it's worth doing as an exercise), rewrite 
your code to use urllib2 or requests.  It'll be a lot easier.



More information about the Python-list mailing list