Re: [Tutor] Importing modules/classes

2005-08-25 Thread Alan Gauld
> class show_num(threading.Thread):
>
>def __init__(self, num):
>print "__init__: Num = ", num
>
> show_num_thread = show_num(742)
> show_num_thread.start()
>
> ---><-
>
> Throws an error
>

> __init__: Num =  742
>
> Traceback (most recent call last):
>  File "H:/Docs/PyScripts/test_thread_1.py", line 12, 
> in -toplevel-
>show_num_thread.start()
> AssertionError: Thread.__init__() not called

>
> Which __init__ method is it referring to?

You need to call the init method of the inherited class(es) from
within your init. It's conventional to call the superclass 
constructor
before doing your own initialisation so it should look like:

def __init__(self, num):
Thread.__init__(self)
print "__init__: Num = ", num

There is a new technique for doing this in recent Python version
(v2.2 onwards?) using the super keyword, but I've still to get
my own head around it... :-)

By calling the superclass first that means that your init code 
can
safely call features of the superclass, sure that they are going 
to work OK.

HTH,


-- 
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling binary file

2005-08-25 Thread Alan Gauld
> I have opened a file in binary mode.
> The 9th, 10th and 11th bytes contain the time in seconds.
> In order to get this value in decimal I did the following:
>
> timeinsec = bytes[9] * 65536 + bytes[10] * 256 + bytes{11]
>
> Would someone please advise if there is a better way to do 
> this?

You could use:

timeinsec = bytes[9:12]

which gets you the three bytes as a sequence.

You should be able to use the struct module to convert that into
a number except that struct expects an integer to be 4 bytes so
you probably need to add a zero in front. It also depends on
issues like big-endian v little endian (ie right or left hand 
alignment)
etc.

If your method works I wouldn't worry too much!

Alan G




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Differences in running a multithreaded script under IDLEand otherwise

2005-08-25 Thread Alan Gauld
>   While running the foll script by double-clicking it (under 
> WinXP), it
> runs as expected. However, when I run it via IDLE, it hangs 
> after a few
> secs (no runtime errors - just hangs). Why does this happen?

My guess is that IDLE is already runnning threads of its own and 
may
not like it when threads start running more threads... But I 
don't know.,
I've never used IDLE for any threading, I'm a vim and console man 
myself!

Alan G. 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] checking substrings in strings

2005-08-25 Thread Alan G
> I would like to check if a certain word exists in a given string.  
> since I learned to love lists, I used
> 
> if myword in mystring:
> 
> ...didnt work. I have now resorted to
> 

Which version of Python?

>>> 'boo' in 'mybigbooboo'
True
>>>

Works for me in Python 2.4...

Alan G.
(Regular readers will note I now have 2.4 installed! :-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] checking substrings in strings

2005-08-25 Thread John Fouhy
On 8/25/05, Frank Hoffsümmer <[EMAIL PROTECTED]> wrote:
> Hello,
> I would like to check if a certain word exists in a given string.
> since I learned to love lists, I used
> 
> if myword in mystring:
> 
> ...didnt work.

What version of python are you using? This was introduced in Python 2.3.

ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on
Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 'bar' in 'foobarbaz'
True

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Source PC MAC address

2005-08-25 Thread Pierre Barbier de Reuille
The problem is: you cannot do that using the socket interface as the OS
IP stack will drop all the ethernet informations. However, you can ask
the network explicitly for the MAC address handling some IP address: the
protocol is called ARP (RFC 826). To do so, the Python package dpkt
(http://www.monkey.org/~dugsong/dpkt/) might be interesting for you
(although I never used it ...) as it includes a module to handle ARP
requests.

Pierre

PS: do not forget to send your answers to Python Tutor also ... BTW,
could it be possible de configure the list so that the "reply-to" field
is set to the Python Tutor list instead of the sender ?

Johan Geldenhuys a écrit :
> Is there a other way of doing this? Getting the MAC. I am on a ethernet
> network.
> 
> Johan 
> 
> 
> 
> 
> 
> 
> 
> Sujet:
> Re: [Tutor] Source PC MAC address
> Expéditeur:
> Pierre Barbier de Reuille <[EMAIL PROTECTED]>
> Date:
> Wed, 24 Aug 2005 17:00:46 +0200
> Destinataire:
> Python Tutor 
> 
> Destinataire:
> Python Tutor 
> 
> Return-Path:
> <[EMAIL PROTECTED]>
> Received:
> from earth.accesstel.co.za ([unix socket]) by earth (Cyrus v2.1.9) with
> LMTP; Wed, 24 Aug 2005 16:59:09 +0200
> X-Sieve:
> CMU Sieve 2.2
> Received:
> by earth.accesstel.co.za (Postfix, from userid 65534) id F00D011DD9;
> Wed, 24 Aug 2005 16:59:08 +0200 (SAST)
> Received:
> from localhost.localdomain (localhost [127.0.0.1]) by
> earth.accesstel.co.za (Postfix) with ESMTP id 11EF911DD9 for
> <[EMAIL PROTECTED]>; Wed, 24 Aug 2005 16:59:08 +0200 (SAST)
> Received:
> from smtp-vbr1.xs4all.nl (smtp-vbr1.xs4all.nl [194.109.24.21]) by
> gateway.azitech.co.za (8.11.6/8.11.6) with ESMTP id j7OEnmr23311 for
> <[EMAIL PROTECTED]>; Wed, 24 Aug 2005 16:49:49 +0200
> Received:
> from bag.python.org (bag.python.org [194.109.207.14]) by
> smtp-vbr1.xs4all.nl (8.13.3/8.13.3) with ESMTP id j7OEvApb033830; Wed,
> 24 Aug 2005 16:57:10 +0200 (CEST) (envelope-from [EMAIL PROTECTED])
> Received:
> from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with
> ESMTP id DA7B61E400F; Wed, 24 Aug 2005 16:57:15 +0200 (CEST)
> X-Original-To:
> tutor@python.org
> Received:
> from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with
> ESMTP id 5382C1E4003 for ; Wed, 24 Aug 2005 16:57:13
> +0200 (CEST)
> Received:
> from bag (HELO bag.python.org) (127.0.0.1) by bag.python.org with SMTP;
> 24 Aug 2005 16:57:13 +0200
> Received:
> from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by
> bag.python.org (Postfix) with ESMTP for ; Wed, 24 Aug
> 2005 16:57:13 +0200 (CEST)
> Received:
> from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by
> auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsnoG028104 for
> ; Wed, 24 Aug 2005 16:54:49 +0200
> Received:
> from [195.221.175.162] ([EMAIL PROTECTED] [195.221.175.162]) by
> auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsmMS028090 for
> ; Wed, 24 Aug 2005 16:54:48 +0200
> ID du Message:
> <[EMAIL PROTECTED]>
> Agent utilisateur:
> Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050817
> Thunderbird/1.0.2 Mnenhy/0.7
> X-Accept-Language:
> fr, en
> Version de MIME:
> 1.0
> Références:
> <[EMAIL PROTECTED]>
> In-Reply-To:
> <[EMAIL PROTECTED]>
> X-Enigmail-Version:
> 0.91.0.0
> X-BeenThere:
> tutor@python.org
> X-Mailman-Version:
> 2.1.6
> Precedence:
> list
> List-Id:
> Discussion for learning programming with Python 
> List-Unsubscribe:
> ,
> 
> List-Archive:
> 
> List-Post:
> 
> List-Help:
> 
> List-Subscribe:
> ,
> 
> Content-Type:
> text/plain; charset="iso-8859-15"
> Expéditeur:
> [EMAIL PROTECTED]
> Errors-To:
> [EMAIL PROTECTED]
> X-Virus-Scanned:
> by XS4ALL Virus Scanner
> X-Accesstel-MailScanner-Information:
> Please contact Accesstel for information
> X-Accesstel-MailScanner:
> Found to be clean
> X-MIME-Autoconverted:
> from quoted-printable to 8bit by gateway.azitech.co.za id j7OEnmr23311
> X-Fetched:
> by SuSE Linux Openexchange Server from
> [EMAIL PROTECTED] for [EMAIL PROTECTED] via pop
> X-Spam-Status:
> No, hits=-7.6 required=4.8
> tests=AWL,BAYES_01,IN_REP_TO,QUOTED_EMAIL_TEXT,REFERENCES,
> REPLY_WITH_QUOTES,SIGNATURE_LONG_SPARSE, USER_AGENT_MOZILLA_UA
> autolearn=ham version=2.55
> X-Spam-Checker-Version:
> SpamAssassin 2.55 (1.174.2.19-2003-05-19-exp)
> Content-Transfer-Encoding:
> 8bit
> 
> 
> Socket is built up on IP, not on Ethernet: you have no way of finding a
> MAC address using sockets simply because it may not exist one ! (if
> you're not on an Ethernet network) You need to access lower levels of
> network and probably access directly the network packet as your network
> card is sending it to your OS !
> 
> Pierre
> 
> Johan Geldenhuys a écrit :
> 
>>Hi List,
>>I am doing some

Re: [Tutor] Importing modules/classes

2005-08-25 Thread Johan Geldenhuys




import threading
self.thread = threading.Thread.__init__(self)
self.thread.start()







Johan














--- Begin Message ---
Me again :)

Just to make sure that I understand it right, 
  1) the __init__ method in a class is invoked when a object is
instantiated from a class
  2) the run method is invoked when a class derived from
"threading.Thread" is "start"ed
Is that right?

The snippet below,

><--

import threading

class show_num(threading.Thread):

def __init__(self, num):
print "__init__: Num = ", num

def run(self):
print "run"

show_num_thread = show_num(742)
show_num_thread.start()
 
---><-

Throws an error

>>> 
__init__: Num =  742

Traceback (most recent call last):
  File "H:/Docs/PyScripts/test_thread_1.py", line 12, in -toplevel-
show_num_thread.start()
AssertionError: Thread.__init__() not called
>>> 

Which __init__ method is it referring to?


Thanks in advance for your help (and time). U guys are awesome :)


-Original Message-
From: Danny Yoo [mailto:[EMAIL PROTECTED] 
Sent: Thursday, 25 August 2005 12:17 p.m.
To: Hans Dushanthakumar
Cc: Tutor
Subject: Re: [Tutor] Importing modules/classes



> class dummy_class:
> def __init__(self):
> print "__init__"
>
> def run(self):
> print "run"
>
>
> Now, I have another file test_dummy.py, which only has the foll 2 
> lines
>
> import dummy_class
> d=dummy_class()


Hi Hans,

In Python, modules are containers.  They can contain possibly more than
one thing, so you need to make sure to fully qualify the class:

import dummy_class
d = dummy_class.dummy_class()

Does this make sense?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

-- 
This E-Mail has been scanned.
Enjoy Your Day.

--- End Message ---
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Differences in running a multithreaded script under IDLE and otherwise

2005-08-25 Thread Kent Johnson
Hans Dushanthakumar wrote:
> Hi,
>While running the foll script by double-clicking it (under WinXP), it
> runs as expected. However, when I run it via IDLE, it hangs after a few
> secs (no runtime errors - just hangs). Why does this happen?

It works for me in IDLE with Python 2.4.1 on Win2k. What version of Python do 
you have? Do you get any output at all?

Kent

> 
> Cheers
> Hans
> 
> import threading
> 
> class incr_num(threading.Thread):
> num = ''
> 
> def __init__(self, local_num):
> global num
> threading.Thread.__init__(self)
> num = local_num
> print "__init__: ", num
> 
> def run(self):
> global num
> for k in range (20):
> print "run: ", num
> num = num + 1
> 
> incr_num_thread = incr_num(501)
> incr_num_thread.start()
> 
> print "Wait for thread to finish"
> incr_num_thread.join()
> print "Thread finished"
> 
> raw_input("Press enter")
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2005-08-25 Thread Jorge Louis de Castro
Hi,

I think I may have misinterpreted the syntax of cPickle. I have dumped data 
onto a file using:

output = codecs.open(".\\"+self.filename, "ab")
cPickle.dump(self.terms, output)
cPickle.dump(self.username, output)
cPickle.dump(self.age, output)
cPickle.dump(self.gender, output)
cPickle.dump(self.totalMsgs, output)
cPickle.dump(self.occurrences, output)

I thought I could unpickle this using the load feature, something like:
inFile = codecs.open(".\\"+self.filename, "r")
cPickle.load(self.terms, inFile)
cPickle.dump(self.username, inFile)
cPickle.dump(self.age, inFile)
cPickle.dump(self.gender, inFile)
cPickle.dump(self.totalMsgs, inFile)
cPickle.dump(self.occurrences, inFile)

Which would unpickle the data onto the variables. It does not work like 
that, unfortunately. When I try reading the whole file I only get the first 
object read as output.
Any ideas how to achieve what this?

chrs
j.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] cPickle usage

2005-08-25 Thread Jorge Louis de Castro
Hi,

[Sorry for the repost, there was a typo previously]

I think I may have misinterpreted the syntax of cPickle. I have dumped data 
onto a file using:

output = codecs.open(".\\"+self.filename, "ab")
cPickle.dump(self.terms, output)
cPickle.dump(self.username, output)
cPickle.dump(self.age, output)
cPickle.dump(self.gender, output)
cPickle.dump(self.totalMsgs, output)
cPickle.dump(self.occurrences, output)

I thought I could unpickle this using the load feature, something like:
inFile = codecs.open(".\\"+self.filename, "r")
cPickle.load(self.terms, inFile)
cPickle.load(self.username, inFile)
cPickle.load(self.age, inFile)
cPickle.load(self.gender, inFile)
cPickle.load(self.totalMsgs, inFile)
cPickle.load(self.occurrences, inFile)

Which would unpickle the data onto the variables. It does not work like 
that, unfortunately. When I try reading the whole file I only get the first 
object read as output.
Any ideas how to achieve what this?

chrs
j.
>
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cPickle usage

2005-08-25 Thread Pierre Barbier de Reuille


Jorge Louis de Castro a écrit :
> Hi,
> 
> [Sorry for the repost, there was a typo previously]
> 
> I think I may have misinterpreted the syntax of cPickle. I have dumped data 
> onto a file using:
> 
> [...]
> 
> I thought I could unpickle this using the load feature, something like:
> inFile = codecs.open(".\\"+self.filename, "r")
> cPickle.load(self.terms, inFile)
> cPickle.load(self.username, inFile)
> cPickle.load(self.age, inFile)
> cPickle.load(self.gender, inFile)
> cPickle.load(self.totalMsgs, inFile)
> cPickle.load(self.occurrences, inFile)

self.terms = cPickle.load(inFile)
self.username = cPickle.load(inFile)
...

should work better :)

> 
> Which would unpickle the data onto the variables. It does not work like 
> that, unfortunately. When I try reading the whole file I only get the first 
> object read as output.
> Any ideas how to achieve what this?
> 
> chrs
> j.
> 


-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cPickle usage

2005-08-25 Thread Kent Johnson
Jorge Louis de Castro wrote:
> Hi,
> 
> [Sorry for the repost, there was a typo previously]
> 
> I think I may have misinterpreted the syntax of cPickle. I have dumped data 
> onto a file using:
> 
> output = codecs.open(".\\"+self.filename, "ab")

Use plain open(), not codecs.open(), as you are not writing encoded character 
data. Why are you opening for append? Is the data in the file already? Are you 
skipping over it on the read? Otherwise use "wb" instead of "ab".

> cPickle.dump(self.terms, output)
> cPickle.dump(self.username, output)
> cPickle.dump(self.age, output)
> cPickle.dump(self.gender, output)
> cPickle.dump(self.totalMsgs, output)
> cPickle.dump(self.occurrences, output)
> 
> I thought I could unpickle this using the load feature, something like:
> inFile = codecs.open(".\\"+self.filename, "r")

Use open() and mode "rb".
> cPickle.load(self.terms, inFile)

Shoud be 
self.username = cPickle.load(inFile) etc. I think you will get a TypeError 
here...

Kent

> cPickle.load(self.username, inFile)
> cPickle.load(self.age, inFile)
> cPickle.load(self.gender, inFile)
> cPickle.load(self.totalMsgs, inFile)
> cPickle.load(self.occurrences, inFile)
> 
> Which would unpickle the data onto the variables. It does not work like 
> that, unfortunately. When I try reading the whole file I only get the first 
> object read as output.
> Any ideas how to achieve what this?
> 
> chrs
> j.
> 
>>
>>___
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IndexError and appending to lists [Was: Re: Need Helpon Assignment]

2005-08-25 Thread Tom Strickland
Alan,

Now I understand! Thanks again for the explanation!

Alan G wrote:

>> "for" loop as you suggest, the program won't enter the loop unless 
>> "s" is initialized so that it's in "input". How do I do that?
>
>
> for s in input:
>
> means that s takes on each value in input.
> input is your file. Thus s takes on the value of each line in
> the input file. You don't need to initialise s before entering
> the loop as you would with a while loop. Similarly you don't
> need to test for the end of the file, 'for' does all that too.
>
> Take a look at the 'Loops' topic and then the 'Handling Files' topic
> in my tutorial for more info on this.
>
>> Also, near the end of your remarks you say that the code at the 
>> bottom of my program doesn't do anything. It does for me.
>
>
> Lets take a look:
>
 print N
 for i in range(N):
T[i]< This does nothing
print T[i]
>>>
>
> The line that simply has the value in it will not do anything.
> It will not print out the value, you need to call print for that
> to happen.
>
>> put in those print statements to verify that the contents of those 
>> variables are what I expected them to be. That's all that mess is for.
>
>
> The debug/test print statements are fine, I was only pointing out
> that one line did nothing, not the entire block.
>
> HTH,
>
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello

2005-08-25 Thread Eric Walker
On Wednesday 24 August 2005 03:57 pm, Jesse Lands wrote:
Yes,
I think its well worth it. He's a great guy and you learn lots of python tips 
and stuff. I need to get something to do now...

...
> On Wed, 24 Aug 2005 16:49:17 -0700 (PDT)
>
> Eric Walker <[EMAIL PROTECTED]> wrote:
> > all,
> > Hello... I just finished a class given by Mark Lutz
> > and I love python. Now I need to find a project to
> > hone my skills. I am sure I will be sending lots of
> > questions to this list.  I used to use perl but now
> > Its gone. I am now a Python guy... Hail Guido
>
> How was the class?  I am taking a class that Mark Lutz is teaching in
> October. Is it worth it? Thanks

-- 
Eric Walker
EDA/CAD Engineer
Work: 208-368-2573
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2005-08-25 Thread Jorge Louis de Castro
Hi,

What is the best way to split a unicode string in its characters? 
Specifically, having this unicode chinese string

u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48

I want to either split all its characters:
[\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48]

or insert a space between each character:
\u8C01 \u4ECA \u5929 \u7A7F \u4EC0 \u4E48

Its not as easy as it looks, though.
chrs
j.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling binary file

2005-08-25 Thread John Purser



Julie,
 
I've had to work with some binary files with 3 byte data 
types.  They were generated by an application coded in Business 
Basic.  Like you I grabbed it as bytes and converted.  For clarity's 
sake I used powers of 2 instead of hard coding the numbers.  2^8 makes it 
pretty obvious why you're multiplying by 256 IMHO.  Look out for negative 
numbers though.  May not be applicable to "number of seconds" but as a 
general rule watch for it.  Incidentally when I had to read the same data 
with VBA I used the same technique to reverse the byte order from Unix to 
Windows.  Worked just fine.
 
John Purser


From: [EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED] On Behalf Of Julie LaiSent: 
Wednesday, August 24, 2005 18:20To: 
tutor@python.orgSubject: [Tutor] Handling binary 
file
I have opened a file in binary 
mode. The 9th, 
10th and 11th bytes contain the time in 
seconds. In order to 
get this value in decimal I did the 
following:   
timeinsec = bytes[9] * 65536 + bytes[10] * 256 + 
bytes{11]   
Would someone please advise if there is a better way to 
do this?   
Thanks, 
Julie.
___想即時收到新 email 通知?下載 Yahoo! 
Messenger http://messenger.yahoo.com.hk 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Splitting a unicode string into characters (was "(No Subject)")

2005-08-25 Thread Terry Carroll
Jorge, please include a subject line.

On Thu, 25 Aug 2005, Jorge Louis de Castro wrote:

> What is the best way to split a unicode string in its characters? 
> Specifically, having this unicode chinese string
> 
> u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48

I'm assuming you've actually got the close-quote there, i.e.:

>>> s=u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48'

> I want to either split all its characters:
> [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48]

>>> l=list(s)
>>> l
[u'\u8c01', u'\u4eca', u'\u5929', u'\u7a7f', u'\u4ec0', u'\u4e48']

> or insert a space between each character:
> \u8C01 \u4ECA \u5929 \u7A7F \u4EC0 \u4E48

>>> s_with_spaces = ' '.join(l)
>>> s_with_spaces
u'\u8c01 \u4eca \u5929 \u7a7f \u4ec0 \u4e48'


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-08-25 Thread Kent Johnson
Jorge Louis de Castro wrote:
> Hi,
> 
> What is the best way to split a unicode string in its characters? 
> Specifically, having this unicode chinese string
> 
> u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48
> 
> I want to either split all its characters:
> [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48]

 >>> s=u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48'
 >>> list(s)
[u'\u8c01', u'\u4eca', u'\u5929', u'\u7a7f', u'\u4ec0', u'\u4e48']
 
> or insert a space between each character:
> \u8C01 \u4ECA \u5929 \u7A7F \u4EC0 \u4E48

 >>> ' '.join(list(s))
u'\u8c01 \u4eca \u5929 \u7a7f \u4ec0 \u4e48'

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-08-25 Thread Alan G
I've not used pickle so don;t know if this is relevant but...

> output = codecs.open(".\\"+self.filename, "ab")
> cPickle.dump(self.terms, output)

> inFile = codecs.open(".\\"+self.filename, "r")
> cPickle.load(self.terms, inFile)

I notice you wrote in binary mode but are reading in text mode.

Does binary reading make a difference?

Guessing,

Alan G.

PS. Anyone else notice how some topics seem to come up in bunches. 
We haven't had any questions involving binary files for months and 
this last week we've had at least 3!


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Running a script not in the current directory

2005-08-25 Thread Arvind Raghavan
I'm using an XP platform and have both a Windows and Cygwin installation 
of Python. I store all my Python scripts in one directory, but would 
like to invoke the script from the command line without specifying the 
full path to this directory. i.e.,

Say all my scripts are in:

~/py_scripts/

My current directory is:
~

I want to be able to do this:

prompt>python myscript.py

and not:
prompt>python ~/py_scripts/myscript.py

Any way to do this? (I use PYTHONPATH for modules and that works correctly)

Arvind
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Should I be thinking of threads for this ?

2005-08-25 Thread Nick Lunt
Hello folks,

I have the following code taken from the Twisted examples -

[code]
# filewatcher.py
from twisted.application import internet

def watch(fp):
fp.seek(fp.tell())
for line in fp.readlines():
sys.stdout.write(line)

import sys
from twisted.internet import reactor
s = internet.TimerService(1.0, watch, file(sys.argv[1]))
s.startService()
reactor.run()
s.stopService()
[/code]

I find this piece of code amazing and I am keen to put it to use.
If I run './filewatcher.py myfile' it will print out any changes made to 
'myfile', very similar to 'tail -f' .

Now if I want to have this program monitor several files at once I could 
run './filewatcher.py file1 file2 filex' or './filewatcher.py file1 & 
./filewatcher file2 & etc' both with minor modifications to the code,  
but I think that could cause performance problems relating to the OS.
So I'm thinking I will need to learn python threads (no bad thing) 
instead, but Im hoping that someone could tell me if that seems the best 
way to go ?
I will be getting to grips with python threads anyway but I'd appreciate 
any input on this.

Many thanks,
Nick .
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Beautiful Soup / Unicode problem?

2005-08-25 Thread grouchy
Hi,

I'm having bang-my-head-against-a-wall moments trying to figure all of this out.

A word of warming, this is the first time I've tried using unicode, or
Beautiful Soup, so if I'm being stupid, please forgive me.  I'm trying
to scrape results from google as a test case. with Beautiful Soup. 
I've seen people recommend it here, so maybe somebody can recognize
what I'm doing wrong:

>>>from BeautifulSoup import BeautifulSoup
>>>file = urllib.urlopen("http://www.google.com/search?q=beautifulsoup";)
>>>file = file.read().decode("utf-8")
>>>soup = BeautifulSoup(file)
>>>results = soup('p','g') 
>>> x = results[1].a.renderContents()
>>> type(x)

>>> print x
Matt Croydon::Postneo 2.0 » Blog Archive » Mobile Screen Scraping ...

So far so good.  But what I really want is just the text, so I try
something like:

>>> y = results[1].a.fetchText(re.compile('.+'))
Traceback (most recent call last):
  File "", line 1, in ?
  File "BeautifulSoup.py", line 466, in fetchText
return self.fetch(recursive=recursive, text=text, limit=limit)
  File "BeautifulSoup.py", line 492, in fetch
return self._fetch(name, attrs, text, limit, generator)
  File "BeautifulSoup.py", line 194, in _fetch
if self._matches(i, text):
  File "BeautifulSoup.py", line 252, in _matches
chunk = str(chunk)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in
position 26: ordinal not in range(128)

Is this a bug?  Come to think of it, I'm not even sure how printing x
worked, since it printed non-ascii characters.

If I convert to a string first:
>>> filestr = file.encode("utf-8")
>>> soup = BeautifulSoup(filestr)
>>> soup('p','g')[1].font.fetchText(re.compile('.+'))
['Mobile Screen Scraping with ', 'BeautifulSoup', ' and Python for
Series 60. ', 'BeautifulSoup', ' 2', 'BeautifulSoup', ' 3. I
haven\xe2€™t had enough time to work up a proper hack for
', '...', 'www.postneo.com/2005/03/28/',
'mobile-screen-scraping-with-', 'beautifulsoup',
'-and-python-for-series-60 -  19k -  Aug 24, 2005 - ', ' ', 'Cached',
' - ', 'Similar pages']

The regex works, but things like "I haven\xe2€™t" get a bit
mangled :)  In filestr, it was represented as  haven\xe2\x80\x99t
which I guess is the ASCII representation for UTF-8.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Differences in running a multithreaded script under IDLE and otherwise

2005-08-25 Thread Hans Dushanthakumar
Kent,
   I'm using the same version (2.4.1) under Win XP. The program works as
expected (ie prints "run: " a few times, and then just goes dead - no
errors. Having said that, I did see one instance where it ran to
completion under IDLE. So looks like the behaviour is not consistent.
Cheers
Hans

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Thursday, 25 August 2005 11:23 p.m.
Cc: tutor@python.org
Subject: Re: [Tutor] Differences in running a multithreaded script under
IDLE and otherwise

Hans Dushanthakumar wrote:
> Hi,
>While running the foll script by double-clicking it (under WinXP), 
> it runs as expected. However, when I run it via IDLE, it hangs after a

> few secs (no runtime errors - just hangs). Why does this happen?

It works for me in IDLE with Python 2.4.1 on Win2k. What version of
Python do you have? Do you get any output at all?

Kent

> 
> Cheers
> Hans
> 
> import threading
> 
> class incr_num(threading.Thread):
> num = ''
> 
> def __init__(self, local_num):
> global num
> threading.Thread.__init__(self)
> num = local_num
> print "__init__: ", num
> 
> def run(self):
> global num
> for k in range (20):
> print "run: ", num
> num = num + 1
> 
> incr_num_thread = incr_num(501)
> incr_num_thread.start()
> 
> print "Wait for thread to finish"
> incr_num_thread.join()
> print "Thread finished"
> 
> raw_input("Press enter")
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Working with files

2005-08-25 Thread Scott Oertel
Bob Gailer wrote:

> At 02:55 PM 8/24/2005, Scott Oertel wrote:
>
>> How do I use the built in file objects to insert text into a file at a
>> certain location?
>>
>> i.e.
>>
>> something, 2, chance, weee
>> nothing, happened, crap, nice
>>
>>  need to search for "something" and insert, "what," before it
>
>
> Here's the algorithm. If you know enough Python you will be able to 
> code it. So put together a program, give it a try and come back with 
> questions.
>
> read the file into a string variable (assuming the file is not humungus)
> find the location of "something" in the string
> assemble a new string consisting of:
>   the original string up to the location (index) of "something"
>   "what"
>   the rest of the original string
> write the new string to the file
>
> Bob Gailer
> 303 442 2625 home
> 720 938 2625 cell

basically I took the idea and the code example given and wrote this 
little function, i stuck vars in this html page like #email# and just 
used it like this, " insertdata('#email#','[EMAIL PROTECTED]')

works perfect!

def insertdata(name, data):
file = open('template.html', 'r+')
contents = file.read()
pos = contents.index(name)
file.seek(pos)
file.write(data)
file.write(contents[pos + len(name):])
file.close()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-08-25 Thread John Fouhy
On 8/26/05, Jorge Louis de Castro <[EMAIL PROTECTED]> wrote:
> I think I may have misinterpreted the syntax of cPickle. I have dumped data
> onto a file using:
> 
> output = codecs.open(".\\"+self.filename, "ab")
> cPickle.dump(self.terms, output)
> cPickle.dump(self.username, output)
> cPickle.dump(self.age, output)
> cPickle.dump(self.gender, output)
> cPickle.dump(self.totalMsgs, output)
> cPickle.dump(self.occurrences, output)
> 
> I thought I could unpickle this using the load feature, something like:
> inFile = codecs.open(".\\"+self.filename, "r")
> cPickle.load(self.terms, inFile)
> cPickle.dump(self.username, inFile)
> cPickle.dump(self.age, inFile)
> cPickle.dump(self.gender, inFile)
> cPickle.dump(self.totalMsgs, inFile)
> cPickle.dump(self.occurrences, inFile)

Did you notice you have only one call to load() here? The others are
still dump().

>>> import pickle
>>> f = file('foo', 'ab')
>>> pickle.dump('foo', f)
>>> pickle.dump('bar', f)
>>> pickle.dump('baz', f)
>>> f.close()
>>> f = file('foo', 'rb')
>>> a = pickle.load(f)
>>> b = pickle.load(f)
>>> c = pickle.load(f)
>>> a,b,c
('foo', 'bar', 'baz')

Although, normally when I use pickle, I chuck everything into a tuple,
so I can store/retrieve it all with a single dump/load command..

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Source PC MAC address

2005-08-25 Thread Liam Clarke-Hutchinson


>PS: do not forget to send your answers to Python Tutor also ... BTW,
>could it be possible de configure the list so that the "reply-to" field
>is set to the Python Tutor list instead of the sender ?

I believe our list administrator has decided that reply-to munging can be
considered harmful.

http://www.unicom.com/pw/reply-to-harmful.html

Johan Geldenhuys a écrit :
> Is there a other way of doing this? Getting the MAC. I am on a ethernet
> network.
> 
> Johan 
> 
> 
> 
> 
> 
> 
> 
> Sujet:
> Re: [Tutor] Source PC MAC address
> Expéditeur:
> Pierre Barbier de Reuille <[EMAIL PROTECTED]>
> Date:
> Wed, 24 Aug 2005 17:00:46 +0200
> Destinataire:
> Python Tutor 
> 
> Destinataire:
> Python Tutor 
> 
> Return-Path:
> <[EMAIL PROTECTED]>
> Received:
> from earth.accesstel.co.za ([unix socket]) by earth (Cyrus v2.1.9) with
> LMTP; Wed, 24 Aug 2005 16:59:09 +0200
> X-Sieve:
> CMU Sieve 2.2
> Received:
> by earth.accesstel.co.za (Postfix, from userid 65534) id F00D011DD9;
> Wed, 24 Aug 2005 16:59:08 +0200 (SAST)
> Received:
> from localhost.localdomain (localhost [127.0.0.1]) by
> earth.accesstel.co.za (Postfix) with ESMTP id 11EF911DD9 for
> <[EMAIL PROTECTED]>; Wed, 24 Aug 2005 16:59:08 +0200 (SAST)
> Received:
> from smtp-vbr1.xs4all.nl (smtp-vbr1.xs4all.nl [194.109.24.21]) by
> gateway.azitech.co.za (8.11.6/8.11.6) with ESMTP id j7OEnmr23311 for
> <[EMAIL PROTECTED]>; Wed, 24 Aug 2005 16:49:49 +0200
> Received:
> from bag.python.org (bag.python.org [194.109.207.14]) by
> smtp-vbr1.xs4all.nl (8.13.3/8.13.3) with ESMTP id j7OEvApb033830; Wed,
> 24 Aug 2005 16:57:10 +0200 (CEST) (envelope-from [EMAIL PROTECTED])
> Received:
> from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with
> ESMTP id DA7B61E400F; Wed, 24 Aug 2005 16:57:15 +0200 (CEST)
> X-Original-To:
> tutor@python.org
> Received:
> from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with
> ESMTP id 5382C1E4003 for ; Wed, 24 Aug 2005 16:57:13
> +0200 (CEST)
> Received:
> from bag (HELO bag.python.org) (127.0.0.1) by bag.python.org with SMTP;
> 24 Aug 2005 16:57:13 +0200
> Received:
> from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by
> bag.python.org (Postfix) with ESMTP for ; Wed, 24 Aug
> 2005 16:57:13 +0200 (CEST)
> Received:
> from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by
> auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsnoG028104 for
> ; Wed, 24 Aug 2005 16:54:49 +0200
> Received:
> from [195.221.175.162] ([EMAIL PROTECTED] [195.221.175.162]) by
> auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsmMS028090 for
> ; Wed, 24 Aug 2005 16:54:48 +0200
> ID du Message:
> <[EMAIL PROTECTED]>
> Agent utilisateur:
> Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050817
> Thunderbird/1.0.2 Mnenhy/0.7
> X-Accept-Language:
> fr, en
> Version de MIME:
> 1.0
> Références:
> <[EMAIL PROTECTED]>
> In-Reply-To:
> <[EMAIL PROTECTED]>
> X-Enigmail-Version:
> 0.91.0.0
> X-BeenThere:
> tutor@python.org
> X-Mailman-Version:
> 2.1.6
> Precedence:
> list
> List-Id:
> Discussion for learning programming with Python 
> List-Unsubscribe:
> ,
> 
> List-Archive:
> 
> List-Post:
> 
> List-Help:
> 
> List-Subscribe:
> ,
> 
> Content-Type:
> text/plain; charset="iso-8859-15"
> Expéditeur:
> [EMAIL PROTECTED]
> Errors-To:
> [EMAIL PROTECTED]
> X-Virus-Scanned:
> by XS4ALL Virus Scanner
> X-Accesstel-MailScanner-Information:
> Please contact Accesstel for information
> X-Accesstel-MailScanner:
> Found to be clean
> X-MIME-Autoconverted:
> from quoted-printable to 8bit by gateway.azitech.co.za id j7OEnmr23311
> X-Fetched:
> by SuSE Linux Openexchange Server from
> [EMAIL PROTECTED] for [EMAIL PROTECTED] via pop
> X-Spam-Status:
> No, hits=-7.6 required=4.8
> tests=AWL,BAYES_01,IN_REP_TO,QUOTED_EMAIL_TEXT,REFERENCES,
> REPLY_WITH_QUOTES,SIGNATURE_LONG_SPARSE, USER_AGENT_MOZILLA_UA
> autolearn=ham version=2.55
> X-Spam-Checker-Version:
> SpamAssassin 2.55 (1.174.2.19-2003-05-19-exp)
> Content-Transfer-Encoding:
> 8bit
> 
> 
> Socket is built up on IP, not on Ethernet: you have no way of finding a
> MAC address using sockets simply because it may not exist one ! (if
> you're not on an Ethernet network) You need to access lower levels of
> network and probably access directly the network packet as your network
> card is sending it to your OS !
> 
> Pierre
> 
> Johan Geldenhuys a écrit :
> 
>>Hi List,
>>I am doing some networking programming and would like to limit access to
>>my socket server on the the source devices' MAC address.
>>I know the IP from where the connection is coming, but how could I find
>>out what the MAC of the source device is?
>>Any quick answers / ideas?
>>Is there a build-in functi

Re: [Tutor] (no subject)

2005-08-25 Thread Alan G
> What is the best way to split a unicode string in its characters? 
> Specifically, having this unicode chinese string
> 
> u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48
> 
> I want to either split all its characters:
> [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48]
> 

>>> s = u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48'
>>> list(s)
[u'\u8c01', u'\u4eca', u'\u5929', u'\u7a7f', u'\u4ec0', u'\u4e48']
>>>


What seemed to be the problem? Or am I missing something?

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beautiful Soup / Unicode problem?

2005-08-25 Thread Danny Yoo


On Thu, 25 Aug 2005, grouchy wrote:


> >>>file = urllib.urlopen("http://www.google.com/search?q=beautifulsoup";)
> >>>file = file.read().decode("utf-8")
> >>>soup = BeautifulSoup(file)
> >>>results = soup('p','g')
> >>> x = results[1].a.renderContents()
> >>> type(x)
> 
> >>> print x
> Matt Croydon::Postneo 2.0 � Blog Archive � Mobile Screen Scraping ...


Hi Grouchy,

So far, so good.  You were lucky to be able to print 'x' off-hand like
that.  When we str() a unicode string, Python will use the default
encoding scheme:

##
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
##

On my Linux machine, as long as that unicode string didn't include
anything that couldn't be encoded as ascii, I'm ok.


Of course, the flip side of this is that some unicode strings can't be
str()'ed right off the bat:

##
>>> nonasciiMsg = unicode(u'\xbb')
>>> nonasciiMsg
u'\xbb'
>>> str(nonasciiMsg)
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in
position 0: ordinal not in range(128)
##

Note here that we can still get a kind of string representation of the
nonasciiMsg here; it's when we use str() that bad things happen, and
that's because the print statement uses str() as a helper utility.



> So far so good.  But what I really want is just the text, so I try
> something like:
>
> >>> y = results[1].a.fetchText(re.compile('.+'))
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "BeautifulSoup.py", line 466, in fetchText
> return self.fetch(recursive=recursive, text=text, limit=limit)
>   File "BeautifulSoup.py", line 492, in fetch
> return self._fetch(name, attrs, text, limit, generator)
>   File "BeautifulSoup.py", line 194, in _fetch
> if self._matches(i, text):
>   File "BeautifulSoup.py", line 252, in _matches
> chunk = str(chunk)
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in
> position 26: ordinal not in range(128)


That's odd!  Ok, let's check why BeautifulSoup is str()-ing the chunk...

### in BeautifulSoup.py ###
#Now we know that chunk is a string
if not type(chunk) in types.StringTypes:
chunk = str(chunk)
if hasattr(howToMatch, 'match'):
# It's a regexp object.
return howToMatch.search(chunk)


Ok, that's surprising!  Isn't a unicode string's type in
types.StringTypes?

##
>>> import types
>>> types.StringTypes
(, )
##


Ok.  That, too, looks fine.  The error message implies that it goes into
line 252, where 'chunk' is a unicode string.  But from the experiments on
my system, running on Python 2.3.5, I don't see how this is doing that.
Mysterious.


If you have a moment, do you mind doing this on your system?

##
import types
print types.StringTypes
import sys
print sys.version()
print type(u'hello') in types.StringTypes
##

and show us what comes up?



Good luck to you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Remote Directory Reading

2005-08-25 Thread Daniel Watkins
I've run into a bit of trouble with my spider script. Thus far, it is
able to retrieve all of the data off the website that is contained
within standard HTML, downloading jpg, gif and bmp images that are
related to the files (this restriction only being set by a lack of
further definitions by myself). However, I have run into a problem with
one link that simply points to a folder (www.aehof.org.uk/forum) within
which is contained a phpBB forum.

I've attempted to use 'dircache' but couldn't find a way for it to
understand web addresses. However, I may not have hit upon the right
combination of syntax, so may be mistaken. I also considered 'os' but it
appears to require definition of a particular operating system, which is
a direction I'd prefer not to take unless I have to. In addition, the
error messages I received from using 'dircache' traced back into 'os' so
it is unlikely it would have been suitable for the purpose.

The variables at the top of the script will later be cleaned up so they
are defined by command line input, they're just there while I sort the
actual script itself out.

Succinctly, I'm looking for an addition to the following script (ideally
under 'default_defs') which will allow me to copy a directly-linked
folder and all its contents.

I hope I have expressed myself in a useful manner, and any help would be
appreciated, although I would prefer no comments on the script in
general as I would quite like to develop it myself as a learning project
(this being my first proper script).

Cheers muchly,
Dan

spider.py
"""
import re
import urllib
import distutils.dir_util

site = "http://www.aehof.org.uk";
localdir = "/home/daniel/test/"
default_defs='[cf]=".*html"|c=".*jpg"|c=".*gif"|c=".*bmp"'

if not re.search('/\Z',site):
site = site + "/"

def get_page_items (source, site = site, defs = default_defs):
next = []
text = urllib.urlopen(site+source).read()

if re.search(defs,text):
for i in re.findall(defs,text):
i = i[3:-1]
next.append(i)

src = [source] + next
return src

def get_list (source="index.html"):
items = []
next = get_page_items (source)
for i in next:
if i not in items:
items.append (i)
next.extend (get_page_items (i))
return items

def copy_items ():
items = get_list()
for i in items:
distutils.dir_util.create_tree(localdir, items)
original = urllib.urlopen(site+i)
local = open(localdir+i,'w')
body = original.read()
local.write(body)
local.close()

copy_items()
"""

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor