learning python

2005-09-04 Thread placid
Hi all,

I was just wondering about good books that teach python (either with
programming or no programming experience at all) ? Or some online
tutorial?

Thanks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learning python

2005-09-04 Thread placid

Christopher Culver wrote:
> "placid" <[EMAIL PROTECTED]> writes:
> > I was just wondering about good books that teach python (either with
> > programming or no programming experience at all) ? Or some online
> > tutorial?
>
> Did you even bother doing a web search? "Learn Python" or "Python
> tutorial" would be enough.

yeah, see i didnt even think of that. 

thanks man

> 
> Christopher

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learning python

2005-09-04 Thread placid

Benji York wrote:
> placid wrote:
> > Christopher Culver wrote:
> >>"placid" <[EMAIL PROTECTED]> writes:
> >>>I was just wondering about good books that teach python (either with
> >>>programming or no programming experience at all) ? Or some online
> >>>tutorial?
> >>
> >>Did you even bother doing a web search? "Learn Python" or "Python
> >>tutorial" would be enough.
> >
> >
> > yeah, see i didnt even think of that.
> >
> > thanks man
>
> That was either a very gracious way to take a public correction, or an
> expertly executed bit of sarcasm, either way, placid, I applaud you.

well thanks man, no sarcasm intended at all.

Sometimes when you concentrate on complicated problems your thinking of
a complicated solution and not a simple one. Christopher gave a really
simple solution.( C does that to people i think) 

> --
> Benji York

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determining if an object is a class?

2006-07-12 Thread placid

[EMAIL PROTECTED] wrote:
> I need to find out if an object is a class.  Using new style classes
> this is very easy:
>
> class Test(object): pass
>
> obj = Test
>or
> obj = Test()
>
> if type(obj) == type:
> # this is a class object..
> else:
> # this not a class object
>
> But this fails for old style classes.  For example:
>
> class OldStyleObject: pass
>

Why is there old and new classes? What are the differences?

--Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3d simulation

2006-07-13 Thread placid

Edmond Dantes wrote:
> placid wrote:
>
> >
> > alimoe wrote:
> >> > Genetic Programming or Genetic Algorithms?
> >>
> >> whats the difference?
> >
> >
> > Genetic Programming:
> > is an automated methodology inspired by biological evolution to find
> > computer programs that best perform a user-defined task.
> >
> > http://en.wikipedia.org/wiki/Genetic_Programming
> >
> > Genetic Algorithms: search technique used in computer science to find
> > approximate solutions to optimization and search problems.
> >
> > http://en.wikipedia.org/wiki/Genetic_algorithms
>
> I would tend to think that Lisp is more suited for Genetic Programming than
> Python is. However, it is possible to do. Heck, I even had the crazy idea
> of doing Genetic Programming in C++ once, however ugly that would've
> been!

My university (RMIT) has a framework for doing Genetic Programming in
C++ and it was really ugly at all.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wanting

2006-07-18 Thread placid

Steve Holden wrote:
> Bruno Desthuilliers wrote:
> > arsl89 wrote:
> >
> >>hy gys i m wanting python programming language.
> >>plz snd me the backup of python

this is one of my aims in life, to bloody understand this 1337 speak!


--Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Number combinations

2006-07-19 Thread placid
Hi all,

Just wondering if there is a better way of generating a 4 digit number
(that gets converted to a string), ive got the following code which
generates strings between -.



for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
print "%s%s%s%s" %(str(a), str(b), str(c),str(d)




--Cheers

http://bulkan.googlepages.com/python

-- 
http://mail.python.org/mailman/listinfo/python-list


subprocess module

2006-07-20 Thread placid
Hi all,

If someone could give me an example of creating a subprocess (on
Windows) using the subprocess module and Popen class and connecting to
its stdout/stdin file handles. I googled for a bit but the only example
i found was here ;

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438119


-- Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: upload a file

2006-07-25 Thread placid

[EMAIL PROTECTED] wrote:
> Dear all,
>
> could you give me an help ?
>
> I would to upload a file from web using Python. Is there a simple way to do
> this? I'm using the cgi module and python 2.3. The file to be uploaded is a 
> text
> file.
>

is this what your after?

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/273844

-- 
http://mail.python.org/mailman/listinfo/python-list


list problem

2006-07-25 Thread placid
Hi all,

I have two lists that contain strings in the form string + number for
example

>>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']

the second list contains strings that are identical to the first list,
so lets say the second list contains the following

>>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']

and now what ive been trying to do is find the first string that is
available,
i.e a string that is in neither of the two lists so the following code
should only print XXX4 then return.

for i in xrange(1,10):
numpart = str(1) + str("%04i" %i)
str = "XXX" + numpart

  for list1_elm in list1:
  if list1_elm == str:
   break
  else:
   for list2_elm in list2:
   if list2_elm == str:
  break
   else:
  print str
  return

Cheer

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-25 Thread placid

Simon Forman wrote:
> placid wrote:
> > Hi all,
> >
> > I have two lists that contain strings in the form string + number for
> > example
> >
> > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
> >
> > the second list contains strings that are identical to the first list,
> > so lets say the second list contains the following
> >
> > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
> >
> > and now what ive been trying to do is find the first string that is
> > available,
> > i.e a string that is in neither of the two lists so the following code
> > should only print XXX4 then return.
> >
> > for i in xrange(1,10):
> > numpart = str(1) + str("%04i" %i)
> > str = "XXX" + numpart
> >
> >   for list1_elm in list1:
> >   if list1_elm == str:
> >break
> >   else:
> >for list2_elm in list2:
> >if list2_elm == str:
> >   break
> >else:
> >   print str
> >   return
> >
> > Cheer
>
> Well first off, don't use 'str' for a variable name.
>
> Second, "%04i" % i creates a string, don't call str() on it.
>
> Third, str(1) will always be "1" so just add that to your format string
> already "1%04i" % i
>

thanks for the tips

> (And if the "XXX" part is also constant then add that too: "XXX1%04i" %
> i)
>
> Finally, you can say:
>
> for i in xrange(1,10):
> s = "XXX1%04i" % i
> if s not in list1 and s not in list2:
> print s
>

But there may be other characters before XXX (which XXX is constant). A
better example would be, that string s is like a file name and the
characters before it are the absolute path, where the strings in the
first list can have a different absolute path then the second list
entries. But the filenames are always exact. So you need to split the
entries bases on "\\" (windows machine) and match on this ?


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread placid
Thank you all for the replies, i now have a better solution.


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


subprocess module

2006-07-26 Thread placid
Hi all,

ive been trying to create a thumbnail using the ffmpeg converter
running the ffmpeg.exe using the subprocess module with the following
code

>>> import subprocess
>>> p = subprocess.Popen(["ffmpeg.exe -i video.mpg", "-f mjpeg  -ss 5 -vframes 
>>> 1 -s 160x120 -an video.gif"], shell=True, stdout=subprocess.PIPE)

but the ffmpeg complains about the input file being corrupter, whereas
when i run the same command via the command shell (cmd.exe) it works.
Does anyone know what the problem is?


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


non-blocking PIPE read on Windows

2006-07-27 Thread placid
Hi all,

I have been looking into non-blocking read (readline) operations on
PIPES on windows XP and there seems to be no way of doing this. Ive
read that you could use a Thread to read from the pipe, but if you
still use readline() wouldnt the Thread block too?

What i need to do is, create a process using subprocess.Popen, where
the subprocess outputs information on one line (but the info
continuesly changes and its always on the same line) and read this
information without blocking, so i can retrieve other data from the
line i read in then put this in a GUI interface.


readline() blocks until the newline character is read, but when i use
read(X) where X is a number of bytes then it doesnt block(expected
functionality) but i dont know how many bytes the line will be and its
not constant so i cant use this too.

Any ideas of solving this problem?


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-blocking PIPE read on Windows

2006-07-30 Thread placid

Dennis Lee Bieber wrote:
> On 27 Jul 2006 22:26:25 -0700, "placid" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> >
> > readline() blocks until the newline character is read, but when i use
> > read(X) where X is a number of bytes then it doesnt block(expected
> > functionality) but i dont know how many bytes the line will be and its
> > not constant so i cant use this too.
> >
> > Any ideas of solving this problem?
> >
>   Use a thread that reads one character at a time; when it sees
> whatever signals "end of line" (it sounds like you're reading a progress
> bar implemented via overwrite). Combine the characters into a
> string, return the string to the main program via a queue.
>

Yes it is a progress bar implemented via  overwrite. I will try
this.

>   If there is no such "end of line" character, but there IS a
> noticeable delay between "writes", a more complex method might suffice
> -- in which one thread does the byte reads, setting a time value on each
> read; a related thread then does a sleep() loop, checking the "last read
> time" against the pause length -- if close enough to the pause duration,
> combine and return...

i dont think there is a noticeable delay between "writes".


>   Alternatively, take a good old style terminal keyboard (a VT100
> Tempest-rated model should be ideal), and use it to beat Bill Gates over
> the head until he agrees to push a high-priority upgrade to the command
> line I/O system... or makes files work with select() (so you can combine
> the time-out with the byte read)

;)  Tsk Tsk

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-blocking PIPE read on Windows

2006-07-30 Thread placid

Dennis Lee Bieber wrote:
> On 30 Jul 2006 16:22:34 -0700, "placid" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> >
> > ;)  Tsk Tsk
>
>   Have you ever seen a Tempest VT-100? Lead shielding on the monitor
> FACE... Turn the brightness all the way up and it still looked dim.
> Fiber optic to the computer. And a shield keyboard about three inches
> thick and weighing 5 lbs.
>
>   All to keep "them" from using radio equipment to pick up key strokes
> or the display scan line radiation (use an external vertical/horizontal
> sweep generator to an oscilloscope, and a high-gain amplifier to detect
> the brightness variation of the CRT).


Nope, i have not seen one.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suppressing the console in a GUI program

2006-08-01 Thread placid

John Salerno wrote:
> John Salerno wrote:
> > Hi guys. I tried naming my file with a .pyw extension, but the console
> > still shows up. Why doesn't this work? And is there another, more
> > programmatic way to suppress it?
> >
> > Thanks.
>
> I just noticed that the console that opens isn't the normal one, it's
> IPython. Now how would I suppress that one as well? Again, any way to do
>   it in the program, or is that not a good idea for when it gets ported
> to another platform?



via Explorer --> File Options --> File Types find PYW entry in the list
and change the associated program to pythonw




Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: serial ports, threads and windows

2006-08-02 Thread placid

Tom Brown wrote:

> When it runs on Windows, could it be:
>
> 1) Just struggling to run inside of VMware?

i have gut feeling that it could be that this is the problem.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hiding Console Output

2006-08-02 Thread placid

Kkaa wrote:
> I'm using the os.system command in a python script on Windows to run a
> batch file like this:
>
> os.system('x.exe')
>
> The third-party program x.exe outputs some text to the console that I
> want to prevent from being displayed.  Is there a way to prevent the
> output of x.exe from python?

using the subprocess module to create a subprocess and piping the
stdout,stdin and stderr so you wont see any ouput from the process
unless you read from the PIPE's.


import subprocess
p = subprocess.Popen("x.exe", shell=True,
stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE)



Cheers

-
http://bulkan.googlepages.com/python/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie...No module named win32com.client

2006-08-02 Thread placid

[EMAIL PROTECTED] wrote:
> This is my very first time to use Phyton!
>
> I am getting a problem with win32com.client missing from some existinf
> scripts.
>
> >python
> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import win32com.client
> Traceback (most recent call last):
>   File "", line 1, in ?
> ImportError: No module named win32com.client
>
> I can see the packages in located in a lib.zip files.. how do I tell
> Phyton to use that zip file for it's packages?
>

you need the win32 extensions and install it.

http://www.python.net/crew/mhammond/win32/Downloads.html
https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063&release_id=432365

-- 
http://mail.python.org/mailman/listinfo/python-list


programming is hard

2006-08-03 Thread placid
Hi all,

this site is contains code snippets for various languages and python
does not have many code snippet posters. Just lettting you know

http://programmingishard.com


Cheers

P.S: I have no connection with this site!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: programming is hard

2006-08-03 Thread placid

Alas, all good arguments.

I rest my case.

:(


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: programming is hard

2006-08-03 Thread placid

[EMAIL PROTECTED] wrote:
> placid wrote:
> > Alas, all good arguments.
> >
> > I rest my case.
>
> After you've just been proven wrong?
>
> I wouldn't want you for my lawyer.

Aha, lucky i wont be a lawyer.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding console in wxpython app

2006-08-07 Thread placid

Philippe Martin wrote:
> Janto Dreijer wrote:
>
> > I'm writing a Linux filemanager using wxPython. I'd like to embed a
> > bash console inside it. I have found the Logilab pyqonsole
> > (http://www.logilab.org/projects/pyqonsole), but it uses PyQT.
> >
> > Does anyone know how to do this from wx?
> > Is it possible to embed a PyQT widget inside wxPython?
> >
> > Thanks!
> > Janto
>
>
> How about just using bash and rerouting stdin/stdout ?

What is that thing in Software Engineering (SE) ? that it is hard to
find simple solutions (or any problem in life for that matter)

I remember last year at uni we had to write this program (get
information from user save it somewhere) for a SE assignment. And half
the teams went off and used MySql to save data retrieved from the user
via a GUI. And in no part of the requirements document did it write ;

* Customer requires GUI frontend
* Customer needs MySql databases server usage to store data

So my team created a Command Line Program (i.e cmd module in python) as
the UI and used object Serialization (pickling in python) to files. So
we finished in half the time that other teams took (and many had to
drop the database server usage in the end) and stressed like tomorow
was Judgement Day. Oh yeah we designed our application so that it was
easy to create a GUI or change the Serialization to saving stuff into a
database and we had one of the top marks out of all the teams.

So OP, if you really dont need to embed bash inside wxPython, then dont
and use what Philippe suggested, unless its in the requirements :)

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


import help

2006-08-07 Thread placid
Hi all,

How do i import a module that has an hypen/dash (-) in its name ? I get
a SytaxError exception

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regd:Video Converter Programming

2006-08-08 Thread placid

Ch3ru5 wrote:
> Hi,
> I want to write an avi to flv converter in php but i am a complete
> newbie to it.
>
> I would like to know the basic flow of entire process of how a
> converter code is written
> (ie. the basic algorithm ) .
>
> Example: "You first create an flv stream , then compress the avi code ,
> then copy that code into the flv stream created ."
>
> The above flow may or may not be correct but what i want to know is
> this flow .
>
> Any good tutorials or resources where i can learn the basics.
>

via a Google search for "python video convert" i found the following

http://pymedia.org/

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regd:Video Converter Programming

2006-08-09 Thread placid

Grant Edwards wrote:
> On 2006-08-09, placid <[EMAIL PROTECTED]> wrote:
>
> >> I want to write an avi to flv converter in php but i am a complete
> >> newbie to it.
>
> > via a Google search for "python video convert" i found the following
> >
> > http://pymedia.org/
>
> Except he wants to write it in PHP.
>
> Not sure why he's asking us about it here in c.l.python.


well if i see a post on comp.lang.python, then i assume its related to
python and thats what my brain did!

-- 
http://mail.python.org/mailman/listinfo/python-list


loop until keypress (Windows XP)

2006-08-09 Thread placid
Hi all,


Im using the cmd module and i have command that loops and keeps on
printing text, what i want to be able to do is loop until the user
presses a particular key, say Q/q ? I tried the following code;


line = raw_input ("press q to abort")
while line[0] != "q":
""" keep printing text """
line = raw_input ("press q to abort")

but raw_input blocks for input until the newline char. So i then tried
the following code


import sys

chr = sys.stdin.read(1)
while chr != "q":
""" keep printing text """
chr = sys.stdin.read(1)

but again this blocks too.

is there a way to do this, wait for user input but dont block? I could
use a thread that just does the previous code block but i already have
three Thread classes, its just getting too complex with threads!

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: loop until keypress (Windows XP)

2006-08-09 Thread placid

Gabriel Genellina wrote:
> At Thursday 10/8/2006 02:19, placid wrote:
>
> >chr = sys.stdin.read(1)
> >while chr != "q":
> > """ keep printing text """
> > chr = sys.stdin.read(1)
> >
> >but again this blocks too.
> >
> >is there a way to do this, wait for user input but dont block? I could
> >use a thread that just does the previous code block but i already have
> >three Thread classes, its just getting too complex with threads!
>
> If your script only needs to be run on Windows -as the subject
> suggests- you can use the msvcrt module:
>
> from msvcrt import kbhit,getch
>
> stop = False
> while not stop:
>print "Hello world!"
>if kbhit(): stop = getch()=='q'
>
> kbhit() is used to detect when a keypress is waiting, so the next
> getch() will not block.

Thanks for the solution ive got it working.  You were correct, the
script needs to run only on Windows.

Cheers (and thanks all for the replies)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: loop until keypress (Windows XP)

2006-08-10 Thread placid

Thomas Guettler wrote:
> Am Wed, 09 Aug 2006 22:19:24 -0700 schrieb placid:
>
> > Hi all,
> >
> >
> > Im using the cmd module and i have command that loops and keeps on
> > printing text, what i want to be able to do is loop until the user
> > presses a particular key, say Q/q ? I tried the following code;
> >
>
> There is a portable getch() implementation:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
>
> It does not loop, it waits until the key is pressed. I hope that is what
> you want.


i want a read operation that doesn't block and im not concerned if my
program is Windows only, which is. (im using wmi module too).

msvcrt.kbhit() and msvcrt.getch() is what i need!


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ALLAH

2006-08-10 Thread placid

[EMAIL PROTECTED] wrote:
>
> Ey insanlar ve cinler ezeli ve ebedi cennete girmek,ebedi yaşamak,her
> istediğini yapmak ve Allah'ı görmek istemezmisiniz.
> Ey sevgili ruh,bunun için Allah'a şükretmeli ve  iman etmeli
> değilmisin.
>
> HULASA  :
> Allah,birdir, hiçbirşeye ihtiyacı yoktur,ne birbaşkası O'nu
> yaratmıştır nede O'nun bir çocuğu vardır.O'nun eşi ve
> benzeri yoktur.

I dont know why post a subject like this here! Anyway, the post is in
Turkish and talks about Islam, with the format, sub-heading (which is a
main topic in Islamic belief) and then a story relating to the
sub-heading, which is used to explain the topic.



Humans and ghosts(?translation) dont you want to enter infinite Heaven,
be immortal do anything you want and see God?

Beatiful soul! For this give thanks to God and pray

Thus;

God is single, needs nothing, no one has created God, and has no child.
God has no one like HIM.






Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: PyPsp 0.1

2006-08-12 Thread placid
First version of PyPsp is released. I have done limited testing as i
have limited free time to
devote to this project, but im doing my best.  There are a three
external modules that you need
to download see the README file for additional information.


Summary

  Playstation Portable(PSP) Video Manager written in Python. It
will use ffmpeg to do the conversion of video files. So basically it is
a framework around ffmpeg.It will provide better filename tracking on
both the PSP and the hard drive for firmware<=2.71


Getting It:

 http://sourceforge.net/projects/pypsp


Ideas, tips welcome!

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


pickling or xml or other?

2006-08-15 Thread placid
Hi all,

I have an application were i want the user to "configure" some settings
which are variables within different classes.

My question is should i just pickle out these variables to a file in
some particular order then read it back. Or use xml to save the config
values ? Which one scales better if settings increase?

Other sugestions? 

-Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


os.path.normpath

2006-08-17 Thread placid
Hi all,

I was just wondering if there is a anti-os.path.normpath function? For
example if i have the path "C:\Program Files\Games" i want to
anti-os.path.normpath is so that it becomes "C:\\Program Files\\Games"
?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.normpath

2006-08-17 Thread placid

placid wrote:
> Hi all,
>
> I was just wondering if there is a anti-os.path.normpath function? For
> example if i have the path "C:\Program Files\Games" i want to
> anti-os.path.normpath is so that it becomes "C:\\Program Files\\Games"
> ?
>
> Cheers

Ahh ignore my post. I was using abspath, and normpath is what i what.

Doh, stupid me!

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


BeautifulSoup problem

2006-10-20 Thread placid
Hi all,

Just wondering if anyone knows how to get the text between the tags of
the following Tag object? 

Hello

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BeautifulSoup problem

2006-10-20 Thread placid

Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, placid wrote:
>
> > Hi all,
> >
> > Just wondering if anyone knows how to get the text between the tags of
> > the following Tag object?
> >
> > Hello
>
> Are you looking for a way to search for tag *and* attributes?  What about
> this::
>
>   In [12]: soup.find('span', {'class': 'nametext'}).contents
>   Out[12]: [u'Hello']

No this wasnt what i was looking for because i didnt know you could do
this. Thanks for that, this is better.

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Python memory usage

2006-11-07 Thread placid
Hi All,

Just wondering when i run the following code;

for i in range(100):
 print i

the memory usage of Python spikes and when the range(..) block finishes
execution the memory usage does not drop down. Is there a way of
freeing this memory that range(..) allocated?

I found this document but the fix seems too complicated.

http://www.python.org/pycon/2005/papers/79/python-memory.pdf

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python memory usage

2006-11-07 Thread placid

William Heymann wrote:
> On Tuesday 07 November 2006 22:42, placid wrote:
> > Hi All,
> >
> > Just wondering when i run the following code;
> >
> > for i in range(100):
> >  print i
> >
> > the memory usage of Python spikes and when the range(..) block finishes
> > execution the memory usage does not drop down. Is there a way of
> > freeing this memory that range(..) allocated?
> >
> > I found this document but the fix seems too complicated.
> >
> > http://www.python.org/pycon/2005/papers/79/python-memory.pdf
> >
> > Cheers
>
> Change range to xrange. It will run faster and use up almost no memory by
> comparison. I know the point you are getting at for releasing memory however
> in this case there is no reason to allocate the memory to begin with.

Thanks for that it has fixed some of the memory problems.  Just
wondering if i continuously create different BeautifulSoup objects
within a xrange() block when does the memory get released for this
object, after the xrange() block, the next iteration of the xrange()
block ?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python memory usage

2006-11-07 Thread placid

Klaas wrote:
> placid wrote:
> > Hi All,
> >
> > Just wondering when i run the following code;
> >
> > for i in range(100):
> >  print i
> >
> > the memory usage of Python spikes and when the range(..) block finishes
> > execution the memory usage does not drop down. Is there a way of
> > freeing this memory that range(..) allocated?
>
> Python maintains a freelist for integers which is never freed (I don't
> believe this has changed in 2.5).  Normally this isn't an issue since
> the number of distinct integers in simultaneous use is small (assuming
> you aren't executing the above snippet).

Actually i am executing that code snippet and creating BeautifulSoup
objects in the range()  (now xrange() ) code block. 

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to access the content of notepad with Python?

2006-05-31 Thread placid

kepioo wrote:
> Hi,
>
> I have a software running on my computer that really looks like notepad
> ( same interface, different name). I need to write a script that will
> capture the content of this software --> the text written inside.
>

Dont know about win32, but if you want an easy solution then save the
text you want to capture and then read it via Python!

-- 
http://mail.python.org/mailman/listinfo/python-list


Is device Connected Windows?

2006-05-31 Thread placid
Hi all,

Just wondering is there a way (not brute force) to check if a usb
storage device is connected?

The brute force method im talking about is doing a os.path.isdir()  or
os.path.isdir() on all the drive letters from A-Z, because you know
that this usb device contains a folder called A or file called foo.txt.


Thanks in Advance

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is device Connected Windows?

2006-06-04 Thread placid

Tim Golden wrote:
> [placid]
>
> | Just wondering is there a way (not brute force) to check if a usb
> | storage device is connected?
>
> Hmmm. How do you identify "a usb storage device" to know that
> it is or isn't connected?
>
> You can certainly do something useful with wmi. eg,
>
> 
> import wmi
>
> c = wmi.WMI ()
> for usb_disk in c.Win32_DiskDrive (InterfaceType="USB"):
>   print usb_disk.Caption
>   print usb_disk.PNPDeviceID
>
> 
>
> Now, assuming that the PNPDeviceID is unique enough for
> your purpose, you could probably do something with it
> to keep hold of it and then check later whether the
> same device is still inserted. One possibility is
> to use a WMI watcher to spot when devices are removed:
>
> 
> import wmi
>
> c = wmi.WMI ()
> usb_watcher = c.watch_for (
>   notification_type="Deletion",
>   wmi_class="Win32_DiskDrive",
>   delay_secs=2,
>   InterfaceType="USB"
> )
>
> while True:
>   usb_removed = usb_watcher () # can optionally timeout
>   print usb_removed.PNPDeviceID
>
> 
>

Thanks mate, this is what i was after, i can work my way through here.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Question

2006-06-19 Thread placid

Saint Malo wrote:
> Thanks!  That helped a lot!  Now, lets say that I just want to display
> one or just a few of the items and not the whole line.  For example,
> the text file contains the following:
>
> red blue yello
> green purple brown
>
>
> If the program searches for blue, i just want it to print blue, not the
> whole line.  If i ask it to find blue and brown, i just want it to
> return those two values.
>
>

search_words = ["red", "brown"]

# Open a file for read
file=open(r'test.txt','r')

# Read each line in file
for line in file

   #Search each line
   for words in search_words:
  if words in line:
  print words

file.close()


* create a list containing search words
* open file for reading
* iterate through each line in the text file
* iterate though each word in search words
* check if the line contains the word your searching for
* print the word if it does
* close file


Cheers

>
>
>
> Andrew Robert wrote:
> > Saint Malo wrote:
> > > I am new to programming, and I've chosen python to start with. I wrote
> > > a simple program that asks several questions and assings each one of
> > > them a variable via raw_input command.  I then combined all the
> > > variables into one like this a = b + c + d.  After this I wrote these
> > > values to a file.  What I want to do now is be able to search through
> > > the file for any data in there.  Is this possible?
> > >
> > Most certainly.
> >
> > It depends on how you want to treat the read data.
> >
> > for example
> >
> >
> > # Open a file for read
> > file=open(r'test.txt','r')
> >
> > # Read each line in file
> > for line in file
> >
> >#Search each line
> >if "A" in line:
> > 
> > print "I found A"
> > 
> > file.close()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Question

2006-06-19 Thread placid

BartlebyScrivener wrote:
> Saint Malo wrote:
> > If the program searches for blue, i just want it to print blue
>
> Huh? Tell it to print whatever you want.
>
> for line in file:
> if 'blue' in line:
> print 'blue'
>
> for line in file:
> if 'brown' in line:
> print 'brown'
>
> for line in file:
> if 'red' in line:
> print 'weasels rip my flesh'

wow Dude, this is not efficient at all! You only need to read the file
once not as many times as there are words in your looking for in the
lines of the file

-- 
http://mail.python.org/mailman/listinfo/python-list


* in Python

2006-06-23 Thread placid
Hi all,

Can someone tell me what * in the following code means/does a Google
search didnt turn up anything as i dont know what the * is called
(related to Python and i dont think Python has pointers)

def test(*args):
 pass

and sometimes its;

def test(**args):
 pass


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * in Python

2006-06-23 Thread placid

Duncan Booth wrote:
> placid wrote:
>
> > Hi all,
> >
> > Can someone tell me what * in the following code means/does a Google
> > search didnt turn up anything as i dont know what the * is called
> > (related to Python and i dont think Python has pointers)
> >
> * is for variable number of positional arguments, ** is for variable
> keyword arguments. The syntax is symmetrical when defining functions and
> when calling them.
>
> See http://docs.python.org/ref/calls.html
> and http://docs.python.org/ref/function.html

so * basically means that args is a list containing more arguments that
can change in size, whereas ** means that args is a dictionary of
key=value arguments?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * in Python

2006-06-23 Thread placid

Bruno Desthuilliers wrote:
> placid wrote:
> > Duncan Booth wrote:
> >
> >>placid wrote:
> >>
> >>
> >>>Hi all,
> >>>
> >>>Can someone tell me what * in the following code means/does a Google
> >>>search didnt turn up anything as i dont know what the * is called
> >>>(related to Python and i dont think Python has pointers)
> >>>
> >>
> >>* is for variable number of positional arguments, ** is for variable
> >>keyword arguments. The syntax is symmetrical when defining functions and
> >>when calling them.
> >>
> >>See http://docs.python.org/ref/calls.html
> >>and http://docs.python.org/ref/function.html
> >
> >
> > so * basically means that args is a list
>
> A tuple IIRC
>
> > containing more arguments that
> > can change in size, whereas ** means that args is a dictionary of
> > key=value arguments?
> >
>
> Why don't you try by yourself in the Python shell ? One of the nice
> things with Python is that it's quite easy to explore and experiment.

i did try it in a  Python shell after i learnt what it was. Like i said
*args will be a list, but when i try **args with the following code it
doesnt work

def test(**args):
keys = args.keys()
for key in keys:
print key+"="+args(key)

>
>
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * in Python

2006-06-24 Thread placid

Bruno Desthuilliers wrote:
> placid wrote:
> > Bruno Desthuilliers wrote:
> >
> (snip)
> >>Why don't you try by yourself in the Python shell ? One of the nice
> >>things with Python is that it's quite easy to explore and experiment.
> >
> >
> > i did try it in a  Python shell after i learnt what it was. Like i said
> > *args will be a list, but when i try **args with the following code it
> > doesnt work
>
> "doesn't work" is the most useless description of a problem.
>
> > def test(**args):
> > keys = args.keys()
> > for key in keys:
> > print key+"="+args(key)
>
> you want args[key], not args(key)
>
> And you forget to tell how you called this code and what you got.

Too much world cup means sleepless nights down here in Australia or i
would have seen the error with args(key) which suppose to be args[key]
!

>
> FWIW:
> Python 2.4.3 (#1, Jun  3 2006, 17:26:11)
> [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def test(**kw):
> ... for item in kw.items():
> ... print "%s : %s" % item
> ...
> >>> test()
> >>> test(parrot="dead", walk="silly", nose="big")
> nose : big
> parrot : dead
> walk : silly
> >>> test(**{'answer':42})
> answer : 42
> >>>

Thanks for that now i know what * means.

-- 
http://mail.python.org/mailman/listinfo/python-list


HTTP server

2006-06-24 Thread placid
Hi all,

Ive been reading about creating a HTTP server like the one pydoc
creates (and studying pydoc source code). What i want to know, is it
possible to create server that creates a webpage with hyperlinks that
communicate back to the HTTP server, where each link accessed tells the
server to execute some arbitrary command on local machine its running
on?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: search engine

2006-06-24 Thread placid

George Sakkis wrote:
> vinodh kumar wrote:
> > hai all,
> >  i am student of computer science dept. i have planned to
> > design a search engine in python. i am seeking info about how to
> > proceed further.
> >   i need to know what r the modules that can be used.
>
> There is not a "search engine module" around AFAIK. You should do your
> homework first and learn about search engines in a language-independent
> way from some good textbook such as "Mining the Web"
> (http://http.cs.berkeley.edu/~soumen/mining-the-web/), break the
> problem into subparts and decide which ones you will implement. By then
> you should have a much better idea of what modules to look for.
>

Anyway, if you are going to design a new search engine and implement it
then you will probably need to use modules only as a helper to your
algorithm.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: search engine

2006-06-24 Thread placid

Daniel Nogradi wrote:
> > hai all,
> >  i am student of computer science dept. i have planned to
> > design a search engine in python. i am seeking info about how to
> > proceed further.
> >   i need to know what r the modules that can be used.
>
> There are these two guys Sacha or Sergey and Larry (if I remember
> correctly) who already wrote a cute search engine in python, perhaps
> you could ask them for some help.

Sergey and Larry youre not talking about Google are you? 

*wink* ;)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and cellular automata (It works this time!)

2006-06-24 Thread placid

defcon8 wrote:
> I thought people would be interested in this little script I wrote to
> reproduce the 256 simple automata that is shown in the first chapters
> of "A New Kind of Science". You can see a few results without running
> the script, at http://cooper-j.blogspot.com . And here is the code (You
> will need PIL (Python Imaging Library)):
> 
> import Image
>
> # Contract:
> # To simulate simple cellular automata.
>
> class calculations:
> def __init__(self,which):
>   self.against = self.array_maker_2()[which]
>   self.check = self.array_maker_1()
>   self.array = self.array_maker_3(311)
>   self.calculator()
>
> def binary(self, n, size): ## This is the Int -> str(BINARY)
> converter
>   assert n >= 0
>   bits = []
>   while n:
>   bits.append('01'[n&1])
>   n >>= 1
>   bits.reverse()
>   result = ''.join(bits) or '0'
>   for iteration in range(len(result),size):
>   result = "0" + result
>   return result
>
> def array_maker_1(self): # This makes the array that represents the
> 8 different permutations of 3 cells. Itself, its left and its right.
>   return [self.binary(n, 3) for n in range(8)]
>
> def array_maker_2(self): # This makes the array that represents
> every single different rule. If for instance the second element in one
> # of these rules is 1, then the corresponding permutation that may
> be found in the result array (array_maker_3), will be 1 (black).
>   return [self.binary(n, 8) for n in range(256)]
>
> def array_maker_3(self, y): # This is the array for all the
> results. The automaton starts from the middle of the first row
>   x = [["0" for x in range((2*y)+1)] for n in range(y)]
>   x[0][(2*y+1)/2] = "1"
>   return x
>
> def calculator(self): # This cycles over all of the cells, and
> scans one row at a time, and changes the next row according to the
> current cell.
>   self.buff_result = ["0","0","0"] # This is the current permutation
> buffer to be checked against the corresponding arrays.
>   for i in range(len(self.array)-1):
>   for j in range(1, len(self.array[0])-1):
>   self.step1(j,i)
>   self.step2(j,i)
>   self.step3(j,i)
>   y = self.check.index(''.join(self.buff_result))
>   self.array[i+1][j] = self.against[y]
>
> # The steps update the result buffer.
> def step1(self, step, y):
>   self.buff_result[0] = self.array[y][step-1]
>
> def step2(self, step, y):
>   self.buff_result[1] = self.array[y][step]
>
> def step3(self, step, y):
>   self.buff_result[2] = self.array[y][step+1]
>
> for number in range(256):
> objo = calculations(number)
> x = objo.array
> y = []
> for num,zo in enumerate(x):
>   for com,wo in enumerate(zo):
>   x[num][com] = int(wo)
>
> nim = Image.new("1", (623,311))
>
> for n in x: #converting the array of arrays into a single array so
> putdata can take it.
>   for p in n:
>   y.append(p)
> nim.putdata(y)
> nim.resize((6230/2,3110/2)).save("output" + str(number) + ".png")
> print number
> 

>

Ah, celular automata! Another of my on-off interest! I shall run this
as soon as posible.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP server

2006-06-25 Thread placid

Simon Forman wrote:
>
>
> Ok, seriously,  I don't know how pydoc does it, but when I need a
> quick-and-dirty http server [written in python] I use something like
> this:
>
> from BaseHTTPServer import HTTPServer
> from SimpleHTTPServer import SimpleHTTPRequestHandler
>
> HTTPServer(('', 8000), SimpleHTTPRequestHandler).serve_forever()
>
> For what you're asking about you'd probably want to use the
> CGIHTTPRequestHandler from the CGIHTTPServer module instead.  Check out
> http://docs.python.org/lib/module-CGIHTTPServer.html

This is what i was after, thanks for the tip.


> Then you'd just write one or more cgi scripts (they can be in python
> IIRC) to run the commands you want.

Im having trouble running the following cgi script on windows



#!c:/Python/python.exe -u

text = """Content-type: text/html

 CGI 101 
A Second CGI script

Hello, CGI World!
"""
print text




using this http server from
http://effbot.org/librarybook/cgihttpserver.htm



import CGIHTTPServer
import BaseHTTPServer

class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["/cgi"]

PORT = 8000

httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()



i get the error number 403, when i try to access the cgi script which
is located in a subdirectory called cgi where this file is (http
server). I have a feeling that i need to change the Handler class or
something, implement , but i couldnt find any examples other then this
from eff-bot.

It could also be this line of code, that a google search turned up, its
the way of running cgi scripts on windows

#!c:/Python/python.exe -u


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP server

2006-06-25 Thread placid

Simon Forman wrote:
> placid wrote:
> > Simon Forman wrote:
> > >
> ...
> > > For what you're asking about you'd probably want to use the
> > > CGIHTTPRequestHandler from the CGIHTTPServer module instead.  Check out
> > > http://docs.python.org/lib/module-CGIHTTPServer.html
> >
> > This is what i was after, thanks for the tip.
> >
>
> You're welcome, my pleasure.  : )
>
> ...
> >
> > Im having trouble running the following cgi script on windows
> >
> > 
> >
> > #!c:/Python/python.exe -u
> >
> > text = """Content-type: text/html
> >
> >  CGI 101 
> > A Second CGI script
> > 
> > Hello, CGI World!
> > """
> > print text
> >
> > 
> >
> >
> > using this http server from
> > http://effbot.org/librarybook/cgihttpserver.htm
> >
> > 
> >
> > import CGIHTTPServer
> > import BaseHTTPServer
> >
> > class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
> > cgi_directories = ["/cgi"]
> >
> > PORT = 8000
> >
> > httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
> > print "serving at port", PORT
> > httpd.serve_forever()
> >
> > 
> >
> > i get the error number 403, when i try to access the cgi script which
> > is located in a subdirectory called cgi where this file is (http
> > server). I have a feeling that i need to change the Handler class or
> > something, implement , but i couldnt find any examples other then this
> > from eff-bot.
> >
> > It could also be this line of code, that a google search turned up, its
> > the way of running cgi scripts on windows
> >
> > #!c:/Python/python.exe -u
> >
> >
> > Cheers
>
>
> Your cgi and server scripts look fine to me.
>
> Some diagnostic questions:
>
> What is the filename of your cgi script?
> (It must end in ".py" or ".pyw" for CGIHTTPRequestHandler to recognize
> it as a python script.  See the is_python() method in the handler
> class.  Also, in this case the "#!c:/Python/python.exe -u" line isn't
> needed, but it doesn't hurt.  CGIHTTPRequestHandler should find the
> python interpreter for you without it.)

The file was named test.cgi. I changed it too test.py and it worked

>
> What was the exact URL that you're using to try to reach your script?
> (It should look something like:
> "http://localhost:8000/cgi/myscript.py";)

i was trying to access it at http://localhost:8000/test.cgi
which i now know is wrong.

>
> What was the error message that accompanied the 403 error?


>
> Did you start the server script from the directory it's in?

i started the server one directory above the cgi directory

> What was the log output from your server script when you tried to
> access the cgi script?

The error message outputted by the server was
localhost - - [26/Jun/2006 09:56:53] code 403, message CGI script is
not a plain file ('/cgi/')


Thanks for the help. I got it to work now.

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP server

2006-06-26 Thread placid

Simon Forman wrote:
> ...
> >
>
> Awesome!  Glad to hear it.
>
> ...
> >
> > Thanks for the help. I got it to work now.
> >
>
> You're welcome.  I'm glad I could help you.  :-D
>

Im having trouble with the following code for handling GET requests
from a client to my HTTP server. What i want to do is restrict access
only to a folder and contents within this folder. But when trying to
open files (text files) i get file not found error from send_head()
method of SimpleHTTPServer. The reason behind this is when opening the
file the path to the file is only C:\file.txt when it should be
C:\folder\file.txt. And when i remove the code that checks if path
contains "txt" it works (i can access files without errors).

Any help will be greatly appreciated!


def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).

Return value is either a file object, or None (indicating an
error).  In either case, the headers are sent, making the
interface the same as for send_head().

"""
f = StringIO()

p = self.translate_path(self.path)
if p.find("txt") == -1:
f.write("httpserver.py: Access Denied" )
f.write("httpserver.py: Access Denied" )
else:
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None

list.sort(key=lambda a: a.lower())

displaypath = cgi.escape(urllib.unquote(self.path))
f.write("Directory listing for %s\n" %
displaypath)
f.write("Directory listing for %s\n" %
displaypath)
f.write("\n\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and
links with /
f.write('%s\n'
% (urllib.quote(linkname),
cgi.escape(displayname)))
f.write("\n\n")

length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you use this list ?

2006-06-27 Thread placid

Bo Yang wrote:
> Hi everyone ,
> I have join this list for about 4 months , and everyday I receive
> hundreds of
> mails . There is no means to read all of them , so I just read something
> interesting
> for me . But if so , there are too much mails pile up in my inbox , I
> want to ask
> how do you use this list , reading every mail come in or just read what
> you think
> interesting ?
>

your recieving those emails because you choose (in your My Account
settings) to received emails, you can deselect this and then just read
any post that interests you and ask questions of your own.

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


HTTP server

2006-06-27 Thread placid
Hi all,

Im having trouble with the following code for handling GET requests
from a client to my HTTP server. What i want to do is restrict access
only to a folder and contents(files) within this folder. But when
trying to
open files (eg text files) i get file not found error from send_head()
method of SimpleHTTPServer. The reason behind this is when opening the
file the path to the file is only C:\file.txt when it should be
C:\folder\file.txt. And when i remove the code that checks if path
contains "txt" it works (i can access files without errors).

Any help will be greatly appreciated!


def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).

Return value is either a file object, or None (indicating an
error).  In either case, the headers are sent, making the
interface the same as for send_head().

"""
f = StringIO()

p = self.translate_path(self.path)
if p.find("txt") == -1:
f.write("httpserver.py: Access Denied" )
f.write("httpserver.py: Access Denied" )
else:
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None

list.sort(key=lambda a: a.lower())

displaypath = cgi.escape(urllib.unquote(self.path))
f.write("Directory listing for %s\n"
%displaypath)
f.write("Directory listing for %s\n" %
displaypath)
f.write("\n\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and
links with /
f.write('%s\n'  %
(urllib.quote(linkname), \

cgi.escape(displayname)))
f.write("\n\n")

length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f


-- 
http://mail.python.org/mailman/listinfo/python-list


problem with http server

2006-06-27 Thread placid
Hi all,

Im having trouble with the following code for handling GET requests
from a client to my HTTP server. What i want to do is restrict access
only to a folder and contents(files) within this folder. But when
trying to
open files (eg text files) i get file not found error from send_head()
method of SimpleHTTPServer. The reason behind this is when opening the
file the path to the file is only C:\file.txt when it should be
C:\folder\file.txt. And when i remove the code that checks if path
contains "txt" it works (i can access files without errors).

Any help will be greatly appreciated!


def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).

Return value is either a file object, or None (indicating an
error).  In either case, the headers are sent, making the
interface the same as for send_head().

"""
f = StringIO()

p = self.translate_path(self.path)
if p.find("txt") == -1:
f.write("httpserver.py: Access Denied" )
f.write("httpserver.py: Access Denied" )
else:
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None

list.sort(key=lambda a: a.lower())

displaypath = cgi.escape(urllib.unquote(self.path))
f.write("Directory listing for %s\n"
%displaypath)
f.write("Directory listing for %s\n" %
displaypath)
f.write("\n\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and
links with /
f.write('%s\n'  %
(urllib.quote(linkname), \

cgi.escape(displayname)))
f.write("\n\n")

length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f




-Cheers

P.S:  ive posted this twice with the subject line HTTP Server, i
apoligise if this will annoy anyone.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python CGI Scripting Documentation

2006-07-02 Thread placid

Vlad Dogaru wrote:
> Hello,
>
> I would like to learn web scripting with Python (sure, everyone uses
> PHP, but I don't like the syntax and Python is more general-purpose
> and... well, I guess you people know the advantages better than me).
> Where can I get a thorough introduction to both CGI and using Python
> for CGI? That includes installing my own web server (at home, for
> testing) and starting from scratch (by that I mean I have near null
> experience with CGI).
>
> I have tried looking through the source code of MoinMoin, but it's just
> too advanced for me -- I simply don't know where to start. Right now,
> I'll take any and all suggestions. However, please suggest books or
> articles that are up-to-date on Python programming; I'd hate to see
> that I'm studying obsolete texts or the like.

Chapter 12 of Programming Python 2nd Edition by Mark Lutz

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread placid

Jim Segrave wrote:
> In article <[EMAIL PROTECTED]>,
> valpa <[EMAIL PROTECTED]> wrote:
> >I'm a net admin for about 20 unix servers, and I need to frequently
> >telnet on to them and configure them.
> >It is a tiring job to open a xterm and telnet, username, password to
> >each server.
>
> Don't use telnet. it's clumsy and has security issues.

if youre behind a firewall then it shouldnt matter.

>
> Use ssh with RSA or DSA keys. Then you simply do:
>
> ssh [EMAIL PROTECTED]
>
> in an xterm and you are loggedis as user username on server
> machinename. It's vastly more secure and more reliable.
>
> If you're talking about initial setup of a machine (OS installation or
> whatever), our solution was to have a post-install CD or floppy which
> fetched standard server configuration data. This included an ssh
> public key for our ssh-key distribution, so after running the
> post-install disc, we could push out staff ssh-keys and logins were
> available.

I dont think the OP wants to do post-install configuration (i may be
wrong! )  but to change for example some config file.

You should be able to create a dictionary containing username=password,
then iterate over this dictionary and use os.system("xterm -e telnet -u
%s -p %s") where -u is username and -p is password (im not quite sure
if telnet has these arguments or if it works like this too)

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads and time.strptime()

2006-07-03 Thread placid

Maximilian Michel wrote:
> Hi all,
>
> I have an interesting problem:
> I have written code, that reads a logfile and parses it for date string
> (Thu Jun 29 14:01:23 2006).
> Standalone everthing works fine, all is recognized.
>
> But if I let the same code run in a thread, with the same file as input
> I get the following error:

do you read the logfile in the thread too or pass the read that to the
thread?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to trap the event of a new process starting with wmi

2006-07-06 Thread placid

gel wrote:
> gel wrote:
>
> > Below is how it is down with vbscript.  What is the best way to convert
> > this to python?
> >
> > strComputer = "."
> > Set objWMIService = GetObject("winmgmts:" _
> > & "{impersonationLevel=impersonate}!\\" & strComputer &
> > "\root\cimv2")
> > Set colMonitoredProcesses = objWMIService. _
> > ExecNotificationQuery("select * from __instancecreationevent " _
> > & " within 1 where TargetInstance isa 'Win32_Process'")
> > i = 0
> >
> > Do While i = 0
> > Set objLatestProcess = colMonitoredProcesses.NextEvent
> > Wscript.Echo objLatestProcess.TargetInstance.Name
> > Loop
>
> A better question might be is there a method or guide for converting
> from vbs wmi to python wmi?

Dont know about converting vbs to python but using Tim Golden's wmi
module to trap the event of a new process starting is easy.

wmi module can be found at http://timgolden.me.uk/python/wmi.html

>>>  import wmi
>>>  c = wmi.WMI()
>>>  watcher = c.watch_for (
>>>   notification_type="Creation"
>>>   wmi_class="Win32_Process"
>>>   delay_secs=2,
>>>   Name='calc.exe'
>>>  )
>>>  calc_created = watcher ()
>>>  print calc_created

and if you want to trap closing down of processes then change
notification_type to "Deletion"


-Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to trap the event of a new process starting with wmi

2006-07-06 Thread placid

gel wrote:
> placid wrote:
>
> > gel wrote:
> > > gel wrote:
> > >
> > > > Below is how it is down with vbscript.  What is the best way to convert
> > > > this to python?
> > > >
> > > > strComputer = "."
> > > > Set objWMIService = GetObject("winmgmts:" _
> > > > & "{impersonationLevel=impersonate}!\\" & strComputer &
> > > > "\root\cimv2")
> > > > Set colMonitoredProcesses = objWMIService. _
> > > > ExecNotificationQuery("select * from __instancecreationevent " _
> > > > & " within 1 where TargetInstance isa 'Win32_Process'")
> > > > i = 0
> > > >
> > > > Do While i = 0
> > > > Set objLatestProcess = colMonitoredProcesses.NextEvent
> > > > Wscript.Echo objLatestProcess.TargetInstance.Name
> > > > Loop
> > >
> > > A better question might be is there a method or guide for converting
> > > from vbs wmi to python wmi?
> >
> > Dont know about converting vbs to python but using Tim Golden's wmi
> > module to trap the event of a new process starting is easy.
> >
> > wmi module can be found at http://timgolden.me.uk/python/wmi.html
> >
> > >>>  import wmi
> > >>>  c = wmi.WMI()
> > >>>  watcher = c.watch_for (
> > >>>   notification_type="Creation"
> > >>>   wmi_class="Win32_Process"
> > >>>   delay_secs=2,
> > >>>   Name='calc.exe'
> > >>>  )
> > >>>  calc_created = watcher ()
> > >>>  print calc_created
> >
> > and if you want to trap closing down of processes then change
> > notification_type to "Deletion"
> >
> >
> > -Cheers
>
> Great, thanks for that, where did you find details on using it.  I am
> already using it for another part, but could not find information on
> watching processes start and stop.

>>>  c=wmi.WMI()
>>>  help(c)

ive been using the wmi module for 1.5 months and i had some help from
the author of the module (Tim Golden).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to trap the event of a new process starting with wmi

2006-07-06 Thread placid

gel wrote:
> >
> > Do you have any docs that might help me?

the only information i have is from using help(wmi.WMI) and from the
examples on Tim Golden's website

>
>
> What would be the best way to watch for multiple pieces of software at
> the same time, eg. watching for the start up of calc.exe notepad.exe.

Well to watch for multiple process at the same time you need to use
Threads and have written one found at
http://www.google.com/notebook/public/14017391689116447001/BDUsxIgoQkcSO3bQh

> Or even how could I query what the value of the attribute Name is equal
> to in the object calc_created from the example above?

Im not quite sure what youre asking.

-Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multithreading and shared dictionary

2006-07-07 Thread placid

Stéphane Ninin wrote:
> Hello,
>
> Probably a stupid question, but I am not a multithreading expert...
>
> I want to share a dictionary between several threads.
> Actually, I will wrap the dictionary in a class
> and want to protect the "sensitive accesses" with locks.
>
> The problem is I am not sure which concurrent access to the dictionary
> could cause a problem.
>
> I assume that two write's on the same location would be,
> but what if one thread does
>
> mydict['a'] = something
>
>  and another thread:
>
> mydict['b'] = something else
>
> Is a lock required in such a case ?

i dont think you need to use a lock for these cases because mydict['a']
refers to mydict['b'] memory locations (i may be wrong because i dont
know Python implementation).

Just a recomendation, you could also use a Queue object to control
write access to the dictionary.

-Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multithreading and shared dictionary

2006-07-08 Thread placid

Alex Martelli wrote:
> Istvan Albert <[EMAIL PROTECTED]> wrote:
>
> > Stéphane Ninin wrote:
> >
> > > Is a lock required in such a case ?
> >
> > I believe that assignment is atomic and would not need a lock.
>
> Wrong, alas: each assignment *could* cause the dictionary's internal
> structures to be reorganized (rehashed) and impact another assignment
> (or even 'get'-access).


Oh yeah you are correct, i forgot about possible rehashing after
assignment operation, so to that means you do need to use a lock to
restrict only one thread at time from accessing the dictionary. Again i
recommend using a Queue to do this. If you need help with usage of
Queue object first see
http://www.google.com/notebook/public/14017391689116447001/BDUsxIgoQkcSO3bQh
or contact me

-Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that modifies a string

2006-07-09 Thread placid

greenflame wrote:
> I want to make a function that does the following. I will call it
> thefunc for short.
>
> >>> s = "Char"
> >>> thefunc(s)
> >>> s
> '||Char>>'
>
> I tried the following
>
> def thefunc(s):
> s = "||" + s + ">>"
>
> The problem is that if I look at the string after I apply the function
> to it, it is not modified. I realized that I am having issues with the
> scope of the variables. The string in the function, s, is local to the
> function and thus I am not changing the string that was inputed, but a
> copy. I cannot seem to figure out how to get what I want done. Thank
> you for your time.

quick hack

def thefunc(s):
return s = "||" + s + ">>"

>>> s = "hello"
>>> s = thefunc(s)
>>> print s
   ||hello>>


--Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add a method to the int class

2006-07-09 Thread placid

[EMAIL PROTECTED] wrote:
> How can I add a method to the int class?

sub class it

>>> class MyInt(int):
>>>def times(self,multiple):
>>> return self * multiple
>>>
>>>  a = 2
>>>  print a
2
>>>  a = MyInt(2)
>>>  print a
>>>  2
>>>  print a.times(2)
4


--Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3d simulation

2006-07-10 Thread placid

alimoe wrote:
> I am interested in coding an app which uses physics and 3d and neural
> nets and genetics. Any pointers?


Open GL Python programming

http://www.google.com/search?hl=en&rls=GGGL,GGGL:2006-22,GGGL:en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=opengl+python&spell=1
http://pyopengl.sourceforge.net/

Neural Nets

http://www.google.com/search?hl=en&lr=&rls=GGGL%2CGGGL%3A2006-22%2CGGGL%3Aen&q=neural+nets+python&btnG=Search

Genetic Programming or Genetic Algorithms?

http://sourceforge.net/projects/pygp/


--Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3d simulation

2006-07-10 Thread placid

alimoe wrote:
> > Genetic Programming or Genetic Algorithms?
>
> whats the difference?


Genetic Programming:
is an automated methodology inspired by biological evolution to find
computer programs that best perform a user-defined task.

http://en.wikipedia.org/wiki/Genetic_Programming

Genetic Algorithms: search technique used in computer science to find
approximate solutions to optimization and search problems.

http://en.wikipedia.org/wiki/Genetic_algorithms

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3d simulation

2006-07-10 Thread placid

alimoe wrote:
> I will create a "robot" that crawls over terrain that looks like the
> picture here:
>
> http://pygp.sourceforge.net/index.php3?name=runs

is this a real robot or a computer simulation?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3d simulation

2006-07-10 Thread placid

Erik Max Francis wrote:
> alimoe wrote:
>
> >> Genetic Programming or Genetic Algorithms?
> >
> > whats the difference?
>
> Genetic algorithms usually involve the manipulation of bit strings.

Where bit strings is the the "dna" and each bit in the string
represents some value

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error occurs when using wmi module in child thread

2006-07-11 Thread placid

Chen Houwu wrote:
> --sample code begin-
>
> import threading
>
> import wmi
>
> def run(*args):
>   c = wmi.WMI ()
>   memory=c.Win32_LogicalMemoryConfiguration()[0]
>   info='Total Virtual Memory: '\
>   +str(int(memory.TotalVirtualMemory)/1024)\
>   +'MB'
>   print info
>
> print  "Begin run() in main thread"
> run()
>
> print "Begin run() in child thread"
> thread=threading.Thread(target=run)
> thread.start()

I had the same problem and wmi module author (Tim Golden) gave me the
solution which;


import pythoncom

# call this function after the run function definition
pythoncom.CoInitialize()


So your function becomes;

 def run(*args):
pythoncom.CoInitialize()
c = wmi.WMI ()
memory=c.Win32_LogicalMemoryConfiguration()[0]
info='Total Virtual Memory: '\
+str(int(memory.TotalVirtualMemory)/1024)\
+'MB'
print info



-- Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: genetic algorithms package for python ?

2006-09-01 Thread placid

Thomas Samson wrote:
> Xiao Jianfeng <[EMAIL PROTECTED]> writes:
>
> > Hi all,
> >
> > I am looking for a genetic algorithms package for Python.
> >
> > I have googled the web before posting and found some links. The link
> > of  pygene(http://www.freenet.org.nz/python/pygene) cannot be opened.
>
> Strange, works for me...
>
> >
> > I also tried the recipe on ASPN, but it is too simple for my
> > application, and the ga model in SciPy, which is in testing in the
> > "sandbox".
> >
> > Are there any more genetic algorithms packages for Python ?
> >
>
> I am not (at all!) an specialist in genetic algorithms, but here are
> some links :
>
> http://pygp.sourceforge.net/
> http://packages.qa.debian.org/g/genetic.html
> and of course,
> http://www.freenet.org.nz/python/pygene/


GP: Genetic Programming
(http://en.wikipedia.org/wiki/Genetic_Programming)

this is different to Genetic Algorithms
(http://en.wikipedia.org/wiki/Genetic_algorithms)

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


HTTP Server Root Folder

2006-09-05 Thread placid
Hi All,

I have this BaseHTTPServer.HTTPServer that is located at C:\ (im on
Windows XP), when i run the program (httpserver.pyw) from the Run
Dialog as "C:\httpserver.pyw" the root folder ("\") for http server is
C:\, but when i add an entry to Registry Run so that it runs at boot
time, the root folder becomes "C:\Documents and Settings\" ?

Does anyone know what the problem is?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbe who is also senior having a senior moment

2006-09-06 Thread placid

stan wrote:
> I am a complete newbe to python and only got here because I am trying to set
> up iTunes in game Second Life.  Have followed all instructions but keep
> getting an error reading from my XP Pro OS as follows
>
> File "C:\Python24\2L file for iTunes", line 4, in -toplevel-
> import win32com.client
> ImportError: No module named win32com.client
>
> can someone pls point me in the right direction here as I am trying to
> urgently fix the file for someones birthday in game (I know pathetic)
>
> thanks
> Stan

you need the win32 python extensions

https://sourceforge.net/projects/pywin32/

-- 
http://mail.python.org/mailman/listinfo/python-list


Starting Win32 Service

2006-09-26 Thread placid
Hi all,

Using Tim Golden's wmi module you can get the service names

import wmi
c = wmi.WMI ()
stopped_services = c.Win32_Service (StartMode="Auto", State="Stopped")
if stopped_services:
  for s in stopped_services:
print s.Caption, "service is not running"
else:
  print "No auto services stopped"

http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services


but how do i start services that are stopped?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting Win32 Service

2006-09-27 Thread placid

Tim Golden wrote:
> [placid]
> | Using Tim Golden's wmi module you can get the service names
> |
> | import wmi
> | c = wmi.WMI ()
> | stopped_services = c.Win32_Service (StartMode="Auto", State="Stopped")
> | if stopped_services:
> |   for s in stopped_services:
> | print s.Caption, "service is not running"
> | else:
> |   print "No auto services stopped"
> |
> | but how do i start services that are stopped?
>
> 
> import wmi
> c = wmi.WMI ()
> for method in c.Win32_Service._methods:
>   print method
>
> #
> #... includes StartService
> #
>
> print c.Win32_Service.StartService
>
> #  (ReturnValue)>
>
> #
> # Therefore, to start all non-running auto services (!)
> #
> for service in c.Win32_Service (StartMode="Auto", State="Stopped"):
>   print service.Caption
>   service.StartService ()
>
> 
>
> TJG
>

Thanks for that.

Now i was trying to use service.ChangeStartMode but each time i pass in
an argument i get the error;

#TypeError: __call__() takes exactly 1 argument (2 given)

but;

>>> print service.ChangeStartMode
 (ReturnValue)>

ChangeStartMode needs an argument!

What im i doing wrong here?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting Win32 Service

2006-09-27 Thread placid

placid wrote:
> Tim Golden wrote:
> > [placid]
> > | Using Tim Golden's wmi module you can get the service names
> > |
> > | import wmi
> > | c = wmi.WMI ()
> > | stopped_services = c.Win32_Service (StartMode="Auto", State="Stopped")
> > | if stopped_services:
> > |   for s in stopped_services:
> > | print s.Caption, "service is not running"
> > | else:
> > |   print "No auto services stopped"
> > |
> > | but how do i start services that are stopped?
> >
> > 
> > import wmi
> > c = wmi.WMI ()
> > for method in c.Win32_Service._methods:
> >   print method
> >
> > #
> > #... includes StartService
> > #
> >
> > print c.Win32_Service.StartService
> >
> > #  (ReturnValue)>
> >
> > #
> > # Therefore, to start all non-running auto services (!)
> > #
> > for service in c.Win32_Service (StartMode="Auto", State="Stopped"):
> >   print service.Caption
> >   service.StartService ()
> >
> > 
> >
> > TJG
> >
>
> Thanks for that.
>
> Now i was trying to use service.ChangeStartMode but each time i pass in
> an argument i get the error;
>
> #TypeError: __call__() takes exactly 1 argument (2 given)
>
> but;
>
> >>> print service.ChangeStartMode
>  (ReturnValue)>
>
> ChangeStartMode needs an argument!
>
> What im i doing wrong here?

And to answer my own question, the way to pass in arguments is via the
key=value way so;

service.ChangeStartMode(StartMode = "Automatic")

Cheers

P.S: Dont you just love trial and error/brute force?

-- 
http://mail.python.org/mailman/listinfo/python-list


Password, trust and user notification

2006-12-11 Thread placid
Hi all,

I was going to write this script for a friend that notifies him via
logging onto his Gmail account and sending him an email to his work
email about some events occurring in the execution of the script.
If you enter your password into a script as input how can someone trust
the programmer that he will not send a email to himself containing his
password? Assuming this person does not know anything about programming
and this person knows nothing about programming ethics.

This is coming from the fact that i need to notify the user in someway
that does not require her to constantly watch the execution of the
script, for example when a user signs in to Windows Live Messenger pop
up.


Cheers


1. http://libgmail.sourceforge.net/  This is the library i use to
access a Gmail account via Python

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Password, trust and user notification

2006-12-13 Thread placid

Gabriel Genellina wrote:


> You DON'T need the password for the receiving account just to send him
> an email!
> And you don't even need that special Gmail library, smtplib should be
> fine.

Yes you dont need a password to receive email, but to access Gmail and
send an email you do. Yes you do need the Gmail library to access Gmail
because the script will run on a computer that doesnt have a smtp
server.

Is there other way's of notifying the user?


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Password, trust and user notification

2006-12-13 Thread placid

Gabriel Genellina wrote:
> At Wednesday 13/12/2006 21:44, Aidan Steele wrote:
>
> >While what you said is technically correct, I think you misread
> >their original question. They want to send email *from* the Gmail
> >account *to* the work account. I suggested that he use Gmail's SMTP
> >server to send the email.

This is correct.

> They were concerned about putting sensitive information (password)
> inside the script, in order to connect to Gmail to send the mail 
> notifications.
> I say that there is no need to use Gmail smtp services: to send mail
> *to* [EMAIL PROTECTED], you only have to connect to the right SMTP
> server for anywhere.com. The *from* email address is irrelevant and
> can even be faked.
> Of course a spam filter could block such mails, but you have to test it.

I was concerned that how does the person who will enter her password
trust the script or the developer in that the script will not create an
email containing her details i.e password and send it off to himself?
(See the assumptions i also posted above in my original post)

Is there any other way of notifying the user of events occurring in the
script which will run as a daemon process.


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Password, trust and user notification

2006-12-14 Thread placid

Dennis Lee Bieber wrote:
> On Thu, 14 Dec 2006 11:44:14 +1100, "Aidan Steele" <[EMAIL PROTECTED]>
> declaimed the following in gmane.comp.python.general:
>
> > While what you said is technically correct, I think you misread their
> > original question. They want to send email *from* the Gmail account *to* the
> > work account. I suggested that he use Gmail's SMTP server to send the email.
> >
>   The most confusing thing is that is sounds very much like they want
> to use the /recipient's/ Gmail account to send email to the
> /recipient's/ work email account -- rather than connecting directly to
> the recipient's work account mail server. (Of course, it may be that
> their own ISP blocks pass-through SMTP -- that's a different matter) --


Ok, everyone now forget that i even asked about connecting to Gmail and
sending an email back to the work email, for some reason you guys are
not answering my question.

Is there any other way (other than email's !) to notify a user of
events within a script?

Thanks for all the help.
Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I'm looking for a pythonic red-black tree...

2006-12-14 Thread placid

Just Another Victim of the Ambient Morality wrote:
> I need a red-black tree in Python and I was wondering if there was one
> built in or if there's a good implementation out there.  Something that,
> lets face it, does whatever the C++ std::map<> allows you to do...
> Thank you...


try,

http://py.vaults.ca/apyllo2.py/211227974


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to stop program when threads is sleeping

2006-12-26 Thread placid

many_years_after wrote:
> Carsten Haese wrote:
> > On Sun, 2006-12-24 at 22:55 -0800, many_years_after wrote:
> > > Hi, pythoners:
> > >
> > >   There is a problem I couldn't dispose. I start a thread in the my
> > > program. The thread will do something before executing time.sleep().
> > > When the user give a signal to the main thread (such as click the 'end'
> > > button or close the window), the thread should end it's running. But
> > > how to end the threading when it's sleeping? I set an flag to the
> > > thread, but it doesn't work.
> >
> > Is the thread supposed to do some additional work after being woken up?
> > If not, there is no point in going to sleep in the first place and the
> > thread should just terminate when it has completed its task. If yes, I'd
> > use a threading.Event object to .wait() on in the sub-thread rather than
> > putting it to sleep, and then .set() the event object in the main thread
> > when it's time to wake up the sub-thread.
> >
> > Hope this helps,
> >
> > Carsten.
>
> While , there is something wrong in my expression. What I mean is the
> thread will wait some time after doing some tasks. I want to know is
> there any method to end the thread or make it out of execution of
> waiting. I use time.sleep() to let the thread wait.

So you want a way of stopping a thread while its blocked (waiting) what
ever seconds in the time.sleep() method ?

> Thanks.

If the thread is supposed to do more operation then i would follow what
Carsten suggested.

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BeautifulSoup vs. loose & chars

2006-12-26 Thread placid

John Nagle wrote:
> I've been parsing existing HTML with BeautifulSoup, and occasionally
> hit content which has something like "Design & Advertising", that is,
> an "&" instead of an "&".  Is there some way I can get BeautifulSoup
> to clean those up?  There are various parsing options related to "&"
> handling, but none of them seem to do quite the right thing.
>
>If I write the BeautifulSoup parse tree back out with "prettify",
> the loose "&" is still in there.  So the output is
> rejected by XML parsers.  Which is why this is a problem.
> I need valid XML out, even if what went in wasn't quite valid.
>
>   John Nagle


So do you want to remove "&" or replace them with "&" ? If you want
to replace it try the following;

import urllib, sys

try:
  location = urllib.urlopen(url)
except IOError, (errno, strerror):
  sys.exit("I/O error(%s): %s" % (errno, strerror))

content = location.read()
content = content.replace("&", "&")


To do this with BeautifulSoup, i think you need to go through every
Tag, get its content, see if it contains an "&" and then replace the
Tag with the same Tag but the content contains "&"

Hope this helps.
Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatting a string to be a columned block of text

2006-12-26 Thread placid

Leon wrote:
> Hi,
>
> I'm creating a python script that can take a string and print it to the
> screen as a simple multi-columned block of mono-spaced, unhyphenated
> text based on a specified character width and line hight for a column.
> For example, if i fed the script an an essay, it would format the text
> like a newspaper on the screen. Text processing is very new to me, any
> ideas on how I could achieve a multi-columned text formatter. Are there
> any libraries that already do this?
>
> Thanks and happy holidays!
> Leon

I did something similar, read in text file format it to 79 characters
and print it out to a multiple images of 480x272 so i could read them
on my PSP. Anyway the code to handle the formatting (even though this
is one column of 78 characters with one character space from the top
and bottom, and sides)

corpus = open("essay.txt","r")

wordcount = 0
pctline = ""
pctlines = [

for line in corpus.readlines():
# i dont need the newline character as it will be printed onto
images
line = line[:-1]

# i want individual words where each word is separated by a space
character
words = line.split(" ")

for word in words:
if wordcount + len(word) + 1 < 78:
wordcount =  wordcount + len(word) + 1
pctline = pctline + word + " "
else:
wordcount = len(word)

pctlines.append(pctline)
pctline = None
pctline = word + " "

corpus.close()

what it does is keeps a list of words and iterate through it and see if
the length of that word and one space character and the line doesn't
exceed 78, if it doesnt then add it to the pctlines, add the count to
the wordcount + 1. If it does then we have one line either 78
characters long or less and add it to pctlines which is a list of all
the lines.

Hope this helps.
Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Calculating Download Rate

2007-01-05 Thread placid
Hi all,

I want be able to work the download rate for downloading HTML pages
using the urllib.urlopen(url). The way i thought i would do this is
start a timer (or log the current time) just before calling this
function and the stopping the timer (logging the current time again and
the working out the difference) this would give me duration that it
took to retrieve the web-page, not the download rate?

Thanks in advance.

-- 
http://mail.python.org/mailman/listinfo/python-list


path backslash escaping trouble

2007-07-09 Thread placid
Hi All,

I have these files; which are Merge Request (ClearCase) files that are
created by a Perl CGI script (being re-written in Python, as the HTML/
JavaScript have been mixed with Perl, maintainability is zero)

MergeTypecodefromlabel
BLnameBUILDMODS
OldLname
BaseVersion6.9.1.24A
RequiredRelease6.10.1.3
Description
FixRelation
Dependencies
LpAffectedNo
CodeReviewFirstName LastName
TestingCompile/Build;Designer;Smoketests;
OtherTesting
Vobsipsupport;
Elements\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3

i read this whole file into a string so i can search for the value of
Elements which is
\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3

but this path is escaped
\\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3

so when i try to escape a string containing that same path using any
of the os.path escaping methods doesnt
result in the correct escaped path. It either appends "C:\\" in front
of the string with all the backslashes escaped
or it converts the three(3) at then end to "x03" and a match doesnt
occur!

My question is, is there a function in Python that only escapes
backslashes?

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path backslash escaping trouble

2007-07-11 Thread placid
On Jul 11, 10:37 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Mon, 09 Jul 2007 22:40:04 -0300, placid <[EMAIL PROTECTED]> escribió:
>
>
>
> > I have these files; which are Merge Request (ClearCase) files that are
> > created by a Perl CGI script (being re-written in Python, as the HTML/
> > JavaScript have been mixed with Perl, maintainability is zero)
>
> > MergeTypecodefromlabel
> > BLnameBUILDMODS
> > OldLname
> > BaseVersion6.9.1.24A
> > RequiredRelease6.10.1.3
> > Description
> > FixRelation
> > Dependencies
> > LpAffectedNo
> > CodeReviewFirstName LastName
> > TestingCompile/Build;Designer;Smoketests;
> > OtherTesting
> > Vobsipsupport;
> > Elements\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3
>
> > i read this whole file into a string so i can search for the value of
> > Elements which is
> > \ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3
>
> > but this path is escaped
> > \\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3
>
> > so when i try to escape a string containing that same path using any
> > of the os.path escaping methods doesnt
> > result in the correct escaped path. It either appends "C:\\" in front
> > of the string with all the backslashes escaped
> > or it converts the three(3) at then end to "x03" and a match doesnt
> > occur!
>
> You may be confused about the actual string contents: "a\\b" contains
> exactly 3 characters, the second being a single backslash. The \ is the
> escape character; to include an actual \ inside a string, you have to
> double it. Another way is to use raw string literals (supressing escape
> processing): r"a\\b" contains four characters.
> See section 3.1.2 in the Python tutorial or the Reference (more
> technical):http://docs.python.org/ref/strings.html
>
> --
> Gabriel

When a user submits a merge request the Python script creats a
subprocess and reads the stdout via a pipe (cleartool find ...) which
returns elements that have a particular label. These elements appeared
like;

\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3

these elements are then checked againts previously submitted merge
requests to see if there are any merge requests that require the
same elements to be merged too. When the elements are read from the
stdout pipe of the subprocess the backslashes aren't escaped and
because these "paths" aren't real windows paths non of the os.path...
path escaping methods work!

Well i've solved the problem just by using pycleartool "links directly
against ClearCase libraries" which returns a tuple
containing (status,output,error) and the element paths in output are
properly escaped.

Thanks for the replies


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python cgi problem with textarea

2007-04-22 Thread placid
On Apr 22, 4:08 pm, Adrian Smith <[EMAIL PROTECTED]> wrote:
> This may be more a cgi thing than a Python one, but I'm trying to get
> this page:
>
> http://adrian10.phpwebhosting.com/trial.html
>
> consisting basically of this:
>
> 
> 
> 
> 
>
> ...to print out the contents of the textarea with this cgi script:
>
> #!/usr/bin/python
> import cgi
> print "Content-type: text/html\n"
> form = cgi.FieldStorage()
> print form["essay"].value
>
> ...and I get an internal server error if I have any spaces in the
> textarea, which is really going to limit its usefulness to me. Oddly,
> it seems to work for a friend in the UK who's looked at it, but it
> doesn't work for me here in Japan.

i just tried it and its working. here it is

http://yallara.cs.rmit.edu.au/~bevcimen/form.html

maybe the internal server error is because mod_python isn't installed
assuming your using Apache as your web server

Cheers


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python cgi problem with textarea

2007-04-23 Thread placid
On Apr 23, 1:01 am, Adrian Smith <[EMAIL PROTECTED]> wrote:
> On Apr 22, 10:09 pm, placid <[EMAIL PROTECTED]> wrote:
>
> > i just tried it and its working. here it is
>
> >http://yallara.cs.rmit.edu.au/~bevcimen/form.html
>
> > maybe the internal server error is because mod_python isn't installed
> > assuming your using Apache as your web server
>
> Yeah, but it wouldn't work *at all* in that case, would it? ATM it
> seems to work as long as the textarea input has no spaces.

it doest work because the "space" character isnt interpreted
correctly, you need
to change the space characters too  

Cheers


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python cgi problem with textarea

2007-04-24 Thread placid
On Apr 24, 4:52 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> placid <[EMAIL PROTECTED]> wrote:
> >On Apr 23, 1:01 am, Adrian Smith <[EMAIL PROTECTED]> wrote:
> >> On Apr 22, 10:09 pm, placid <[EMAIL PROTECTED]> wrote:
>
> >> > i just tried it and its working. here it is
>
> >> >http://yallara.cs.rmit.edu.au/~bevcimen/form.html
>
> >> > maybe the internal server error is because mod_python isn't installed
> >> > assuming your using Apache as your web server
>
> >> Yeah, but it wouldn't work *at all* in that case, would it? ATM it
> >> seems to work as long as the textarea input has no spaces.
>
> >it doest work because the "space" character isnt interpreted
> >correctly, you need to change the space characters too  
>
> What???  Did you even read the problem description?

oops...i did read the problem description, but i when i tried the code
it worked for me and when i put spaces into the TextArea it wasn't
reflected correctly back. So i thought this was the problem.

Adrian, can you still try replacing spaces with   via the
following;

#!/usr/bin/python
import cgi
import urllib
import cgitb
cgitb.enable()
print "Content-type: text/html\n"
form = cgi.FieldStorage()
#print urllib.quote_plus(form["essay"].value)

for char in form["essay"].value:
   if char == ' ':
  print " "
   else:
  print char


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread placid
On Apr 25, 4:40 pm, "Tennessee Leeuwenburg"
<[EMAIL PROTECTED]> wrote:
> Firstly, let me put up my hand and say that I would be happy to write
> Python articles for cash.
>

I would be happy to write Python articles for a T-shirt with the
Python logo printed on it. Maybe each article entrant can receive a t-
shirt?


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-26 Thread placid
On Apr 25, 12:00 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Jeff Rush wrote:
> > There is discussion by the Python Software Foundation of offering cash
> > bounties or perhaps periodic awards to the "best of" for magazine articles,
> > video/screencast clips and such.

I would like to see more screen-casts on python modules out there,
like CherryPy, Zope and Twisted.
Sometimes documentation just seems "dry" to read when you're just
trying to learn.

>
> > If YOU would be swayed to get involved in producing content in exchange for
> > cash, please speak up on the advocacy mailing list and also drop an email to
> > Steve Holden <[EMAIL PROTECTED]>, current champion of this idea and looking
> > for encouragement.  Ideas on how to evaluate contributions, how frequently 
> > to
> > do this and critical thresholds of cash amounts necessary to induce YOUR
> > participation are wanted.

I would write an article for a t-shirt with the python logo on
it ;)

Cheers


-- 
http://mail.python.org/mailman/listinfo/python-list


Sending a JavaScript array to Python script?

2007-05-17 Thread placid
Hi All,

Just wondering if there is any way of sending a JavaScript array to a
Python cgi script? A quick Google search didn't turn up anything
useful.

Any help appreciated.

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extract information from HTML table

2007-04-01 Thread placid
On Apr 1, 10:13 pm, "Ulysse" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm trying to extract the data from HTML table. Here is the part of
> the HTML source :
> """
> 
>   
>  type="checkbox">
>   
> Sat, 31.03.2007 - 20:24:00
>   
> http://s2.bitefight.fr/bite/
> bericht.php?q=01bf0ba7258ad976d890379f987d444e&beid=2628033">Vous
> avez tendu une embuscade à votre victime !
> 
> 
>   
>  type="checkbox">
>   
> Sat, 31.03.2007 - 20:14:35
>   
> http://s2.bitefight.fr/bite/
> bericht.php?q=01bf0ba7258ad976d890379f987d444e&beid=2628007">Vous
> avez tendu une embuscade à votre victime !
> 
> 
>   
>  type="checkbox">
>   
> Sat, 31.03.2007 - 20:11:39
>Vous avez bien accompli votre
> tâche de Gardien de Cimetière et vous vous
> voyez remis votre salaire comme récompense.
> Vous recevez 320
>  alt="Or" align="absmiddle" border="0">
> et collectez 3 d'expérience !
> 
> """
>
> I would like to transform this in following thing :
>
> Date : Sat, 31.03.2007 - 20:24:00
> ContainType : Link
> LinkText : Vous avez tendu une embuscade à votre victime !
> LinkURL 
> :http://s2.bitefight.fr/bite/bericht.php?q=01bf0ba7258ad976d890379f987...
>
> Date : Sat, 31.03.2007 - 20:14:35
> ContainType : Link
> LinkText : Vous avez tendu une embuscade à votre victime !
> LinkURL 
> :http://s2.bitefight.fr/bite/bericht.php?q=01bf0ba7258ad976d890379f987...
>
> Date : Sat, 31.03.2007 - 20:14:35
> ContainType : Text
> Contain : Vous avez bien accompli votre tâche de Gardien de Cimetière
> et vous vous
> voyez remis votre salaire comme récompense.
> Vous recevez 320 et collectez 3 d'expérience !
>
> 
>
> Do you know the way to do it ?

You can use Beautiful Soup http://www.crummy.com/software/BeautifulSoup/

see this page to see how you can search for tags, then retrieve the
contents

http://www.crummy.com/software/BeautifulSoup/documentation.html#Searching%20Within%20the%20Parse%20Tree

Cheers



-- 
http://mail.python.org/mailman/listinfo/python-list


Projects anyone?

2007-01-16 Thread placid
Hi all,

I'm looking for anyone who is working on a project at the moment that
needs help (volunteer). The last project i worked on personally was
screen-scraping MySpace profiles (read more at the following link)

http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles


but that didn't go all to well, so im kinda bored and need something to
do, with Python. So any suggestions anyone? 

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Projects anyone?

2007-01-17 Thread placid
Thanks for all the help. I have some projects that i will look into and
see if i can contribute anything

Cheers

Ben Finney wrote:
> "placid" <[EMAIL PROTECTED]> writes:
>
> > I'm looking for anyone who is working on a project at the moment that
> > needs help (volunteer).
>
> The Volunteer Opportunities page is a bit thin at the moment. I'd hope
> people can respond to this thread and update that page with other
> projects that need help.
>
> http://wiki.python.org/moin/VolunteerOpportunities>
>
> The Coding Project Ideas page is more specifically focussed on getting
> programmer help.
>
> http://wiki.python.org/moin/CodingProjectIdeas>
>
> Browse the Cheese Shop for packages that you'd like to improve, and
> offer your help to the project maintainer.
>
> http://cheeseshop.python.org/pypi/>
>
> --
>  \   "A 'No' uttered from deepest conviction is better and greater |
>   `\   than a 'Yes' merely uttered to please, or what is worse, to |
> _o__)   avoid trouble."  -- Mahatma Gandhi |
> Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >