[Tutor] Subprocess.Popen process seems to be outputting to stdout even though redirected ?

2012-06-10 Thread dave selby
I have a simple script to tail a log file for an error string, it
works AOK but there is an unexpected side effect, when I run it in a
shell.

if I

echo "ERROR TEST" >> LOG

in a separate shell, I get the following from the script

ERROR TEST
GOT YA :)
ERROR TEST

So it looks like I am getting stdout from the tail -f, and two copies
of it ?, stdout should be piped to subprocess.stdout

tail = subprocess.Popen(['tail', '-f', LOG_FILE], shell=False,
stdout=subprocess.PIPE)

for out in iter(tail.stdout.readline, ''):

out_str = out.rstrip('\n')

if out_str.find('ERROR') != -1:
print 'GOT YA :)'

time.sleep(1)

Any ideas anyone ?

Cheers

Dave

-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Subprocess.Popen process seems to be outputting to stdout even though redirected ?

2012-06-10 Thread dave selby
This list is amazing, I scratch my head, think and think then finally
post a question, maybe its the act of spelling it out, ps ax showed 2
x 'tail' processes, I am guessing zombies of previous attempts, killed
them, all works AOK now


On 10 June 2012 10:06, dave selby  wrote:
> I have a simple script to tail a log file for an error string, it
> works AOK but there is an unexpected side effect, when I run it in a
> shell.
>
> if I
>
> echo "ERROR TEST" >> LOG
>
> in a separate shell, I get the following from the script
>
> ERROR TEST
> GOT YA :)
> ERROR TEST
>
> So it looks like I am getting stdout from the tail -f, and two copies
> of it ?, stdout should be piped to subprocess.stdout
>
> tail = subprocess.Popen(['tail', '-f', LOG_FILE], shell=False,
> stdout=subprocess.PIPE)
>
> for out in iter(tail.stdout.readline, ''):
>
>        out_str = out.rstrip('\n')
>
>        if out_str.find('ERROR') != -1:
>                print 'GOT YA :)'
>
>        time.sleep(1)
>
> Any ideas anyone ?
>
> Cheers
>
> Dave
>
> --
>
> Please avoid sending me Word or PowerPoint attachments.
> See http://www.gnu.org/philosophy/no-word-attachments.html



-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] properties beginner M Dawson book

2012-06-10 Thread Nicholas Harman
Hi,
I am teaching myself Python with the book :Python Programming for the Absolute 
Beginner, 3rd edition by M Dawson.  It is an excellent book and I am enjoying 
completing the challenges at the end of each chapter.  There are, 
unfortunately, no answers nor examples of good and bad code.  Honestly I don’t 
want to “cheat” but I have to teach Python to some young students in September, 
using this book, and I want all the responses to any doubts they have ready 
.
  
Here’s something specific:
chapter 8 challenge 2:  “ Write a program that simulates a television by 
creating it as an object. The user should be able to enter a channel number and 
raise or lower the volume.  Make sure that the channel number and volume level 
stay within valid ranges.”

I have done a little programming in BlueJ Java before but I decided to try the 
“Python style” as explained in the chapter, using properties rather than 
variables and getters and setters .
My main question is:  When using property and setter it seems I must use 
“__name” or “__volume” (Python’s version of private variables).  Is this true?

Here are parts of my code: - any comments about how bad / good this code is for 
the level in the book (NOT advanced stuff please) would be greatly appreciated. 
Thank you

class Television(object):


#Contstructor
def __init__(self, name, channel = 1, volume = 5):
print("A television has been made!")
#As I am using properties these assignments indirectly call the
#relevant property setter methods listed below
self.name = name
self.channel = channel
self.volume = volume
#Note:  "self.__name = name" works but then no call is made to the 
property setter method


@property
def name(self):
return self.__name

@name.setter
def name(self, newName):
if newName != "":
self.__name = newName
print("This TV is now called: ", self.__name)
else:
print("Sorry, empty string not allowed as a name.")
#If the setter was called in the middle of the program run
#that is it already has an attribute self.__name with a value
#So leave the namae as it was, unchanged.
try:
print("The name stays as: ", self.__name)
#This will generate an attribute error when called as part of 
the __init__
#because self.name has not yet been created nor assigned.
#So catch this error and give self.__name a "default name"
except AttributeError:
self.__name = "Default"
print("The TV is now called: ", self.__name)


and 

def main():

tv_name = input("What do you want to call your television?  ")
tv = Television(tv_name)


choice = None  
while choice != "0":
print \
("""
TV Maker

0 - Quit
1 - Television Details
2 - Set Channel
3 - Set Volume
4 - Chanage the name of the TV
""")

choice = input("Choice: ")
print()

# exit
if choice == "0":
print("Good-bye.")

# Print details of television
elif choice == "1":
print("Television details.")
print(tv)

# Change the channel
elif choice == "2":
amount = int(input("Enter 1 to 100 to choose a channel. "))
tv.channel = amount
 
# Change the volume
elif choice == "3":
amount = int(input("Enter 0 to 10 set the volume. "))
tv.volume = amount

elif choice == "4":
print("Choose a new name for your television but not nothing!")
tv.name = input("Enter a new name here: ")

# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] properties beginner M Dawson book

2012-06-10 Thread Steven D'Aprano

Nicholas Harman wrote:


I have done a little programming in BlueJ Java before but I decided to try
the “Python style” as explained in the chapter, using properties rather
than variables and getters and setters . My main question is:  When
using property and setter it seems I must use “__name” or “__volume”
(Python’s version of private variables).  Is this true?


Certainly not. Python doesn't enforce any naming convention on you. You can 
use any name you like. But you *should* use something like "__name" or 
"__volume", simply because that will be more sensible than most other names. 
But if you choose to use something else, Python won't stop you.


Note: you can also use just a single underscore, _name and _volume, to 
indicate that the attributes are private and should not be touched.



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] properties beginner M Dawson book

2012-06-10 Thread Steven D'Aprano

Nicholas Harman wrote:


class Television(object):
#Contstructor


Spelling error: Constructor.

Actually, technically __init__ is not the constructor. __init__ is the 
initializer, as the object has already been created before __init__ is called. 
__new__ is the constructor, although in this case it is unused.




def __init__(self, name, channel = 1, volume = 5):


Optional: it is the usual convention to declare default values without a 
space, that is, __init__(self, name, channel=1, volume=5).




def main():

tv_name = input("What do you want to call your television?  ")


Are you using Python 2, or Python 3?

If Python 3, this is fine. But in Python 2, you should use raw_input instead 
of input.




tv = Television(tv_name)


choice = None  
while choice != "0":

print \
("""
TV Maker

0 - Quit

1 - Television Details
2 - Set Channel
3 - Set Volume
4 - Chanage the name of the TV
""")


Spelling: Change, not Chanage.


The rest seems fine to me, assuming you are writing for beginners.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor