Re: stuck in files!!

2012-07-06 Thread Alex
Chirag B wrote:

> i want to kno how to link two applications using python for eg:notepad
> txt file and some docx file. like i wat to kno how to take path of
> those to files and run them simultaneously.like if i type something in
> notepad it has to come in wordpad whenever i run that code.

Text and docx files are not "applications"; you don't "run" them. You
can "open" them with applications like Notepad or Microsoft Word, and
you can open two files simultaneously in two different applications (or
in two windows within the same application).

Other than that, I don't understand what you mean by "link" them or
what it means for something typed in Notepad to "come in wordpad."
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a way to configure IDLE to use spaces instead of tabs for indenting?

2012-08-24 Thread Alex
I'm new to Python and have been using IDLE 3.2.3 to experiment with
code as I learn. Despite being configured to use a 4 space indentation
width, sometimes IDLE's "smart" indentation insists upon using width-8
tabs.

>From what I've been able to find on Google, this is due to a
shortcoming in Tk. While it's not that big a deal in the grand scheme
of things, I think it looks like poop, and I'd like to change IDLE to
use 4-space indentation instead of tabs for all indentation levels.

Is there any way for me to achieve what I want in IDLE, or do I have to
start up my full-blown IDE if I want consistent 4-space indentation?

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


Re: Is there a way to configure IDLE to use spaces instead of tabs for indenting?

2012-08-25 Thread Alex
Terry Reedy wrote:

> On 8/24/2012 6:33 PM, Alex wrote:
> > Despite being configured to use a 4 space
> > indentation
...
> > sometimes IDLE's "smart" indentation insists upon using
> > width-8 tabs.
> 
> [The 4-space indentation setting] applies to the editor and works in 
> the editor for me and others.
> 
> [The width-8 tabs are inserted] Only for the simulated interpreter.
> There is a tracker issue about changing that but no consensus.

Yes, it works in the editor. I was referring to the simulated
interpreter. I guess I didn't make that clear.

In my search for a solution, I did see some of the traffic regarding
the tracker issue, but the posts were all several years old and I was
hoping maybe there was a fix by now. I guess not. Maybe in Python 4, eh?

Thanks.

Alex

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


Re: Is there a way to configure IDLE to use spaces instead of tabs for indenting?

2012-08-25 Thread Alex
Mark Lawrence wrote:

> On 25/08/2012 13:50, Alex wrote:
> > Terry Reedy wrote:
> > 
> > > On 8/24/2012 6:33 PM, Alex wrote:
> > > > Despite being configured to use a 4 space
> > > > indentation
> > ...
> > > > sometimes IDLE's "smart" indentation insists upon using
> > > > width-8 tabs.
> > > 
> > > [The 4-space indentation setting] applies to the editor and works
> > > in the editor for me and others.
> > > 
> > > [The width-8 tabs are inserted] Only for the simulated
> > > interpreter.  There is a tracker issue about changing that but no
> > > consensus.
> > 
> > Yes, it works in the editor. I was referring to the simulated
> > interpreter. I guess I didn't make that clear.
> > 
> > In my search for a solution, I did see some of the traffic regarding
> > the tracker issue, but the posts were all several years old and I
> > was hoping maybe there was a fix by now. I guess not. Maybe in
> > Python 4, eh?
> > 
> > Thanks.
> > 
> > Alex
> > 
> 
> For the record issue 7676, yes?

Yes, that appears to be the issue I was talking about and is, in fact,
one of the threads I had looked at before posting here. Of course, I
didn't pay enough attention to the dates. I see the most recent posting
on the issue appears to have been made in January of this year, so I
should have realized it's an ongoing issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to configure IDLE to use spaces instead of tabs for indenting?

2012-09-06 Thread Alex
Ramchandra Apte wrote:

> On Saturday, 25 August 2012 04:03:52 UTC+5:30, Alex  wrote:
> > I'm new to Python and have been using IDLE 3.2.3 to experiment with
> > 
> > code as I learn. Despite being configured to use a 4 space
> > indentation
> > 
> > width, sometimes IDLE's "smart" indentation insists upon using
> > width-8
> > 
> > tabs.
> > 
> > 
> > 
> > From what I've been able to find on Google, this is due to a
> > 
> > shortcoming in Tk. While it's not that big a deal in the grand
> > scheme
> > 
> > of things, I think it looks like poop, and I'd like to change IDLE
> > to
> > 
> > use 4-space indentation instead of tabs for all indentation levels.
> > 
> > 
> > 
> > Is there any way for me to achieve what I want in IDLE, or do I
> > have to
> > 
> > start up my full-blown IDE if I want consistent 4-space indentation?
> > 
> > 
> > 
> > Alex
> 
> I think an IDE is better than IDLE. Try NINJA IDE.
> http://ninja-ide.org

Agreed. I like PyDev in Eclipse, but sometimes I just want to try out
something quick in the interpreter, to ensure I understand it or do a
quick experiment. Since indentation is syntactically significant in
Python, I think fixing the interpreter to produce good, readable,
cut-and-pasteable, and Pythonic code is more important than a cosmetic
feature, but less important than true bugs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to configure IDLE to use spaces instead of tabs for indenting?

2012-09-06 Thread Alex
Terry Reedy wrote:

[snip]

> IDLE is not the interpreter. 

Fine, I meant shell. Thanks for fixing that for me.

> The IDLE Shell is intended mainly for single-line inputs. 

Maybe it should be limited to that, then. That way stoopid noobs like
me don't use it wrong and then use the wrong nomenclature to complain
about it.

> For more than a three-line compound statement, I use the editor with
> a scratchpad file where editing is much easier. 

Great tip, thanks. That's how I'll do it from now on.


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


Re: Insert item before each element of a list

2012-10-08 Thread Alex
mooremath...@gmail.com wrote:

> What's the best way to accomplish this?  Am I over-complicating it?
> My gut feeling is there is a better way than the following:
> 
> >>> import itertools
> >>> x = [1, 2, 3]
> >>> y = list(itertools.chain.from_iterable(('insertme', x[i]) for i
> in range(len(x >>> y
> ['insertme', 1, 'insertme', 2, 'insertme', 3]
> 
> I appreciate any and all feedback.
> 
> --Matt

Just like the Zen of Python (http://www.python.org/dev/peps/pep-0020/)
says . . . "There should be at least ten-- and preferably more --clever
and obscure ways to do it."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to configure IDLE to use spaces instead of tabs for indenting?

2012-10-17 Thread Alex
Fabio Zadrozny wrote:

> On Thu, Sep 6, 2012 at 10:43 AM, Alex  wrote:
> > Ramchandra Apte wrote:
> > 
> >> On Saturday, 25 August 2012 04:03:52 UTC+5:30, Alex  wrote:
> >> > I'm new to Python and have been using IDLE 3.2.3 to experiment
> with >> >
> >> > code as I learn. Despite being configured to use a 4 space
> >> > indentation
> >> >
> >> > width, sometimes IDLE's "smart" indentation insists upon using
> >> > width-8
> >> >
> >> > tabs.
> >> >
> >> >
> >> >
> >> > From what I've been able to find on Google, this is due to a
> >> >
> >> > shortcoming in Tk. While it's not that big a deal in the grand
> >> > scheme
> >> >
> >> > of things, I think it looks like poop, and I'd like to change
> IDLE >> > to
> >> >
> >> > use 4-space indentation instead of tabs for all indentation
> levels.  >> >
> >> >
> >> >
> >> > Is there any way for me to achieve what I want in IDLE, or do I
> >> > have to
> >> >
> >> > start up my full-blown IDE if I want consistent 4-space
> indentation?  >> >
> >> >
> >> >
> >> > Alex
> > > 
> >> I think an IDE is better than IDLE. Try NINJA IDE.
> >> http://ninja-ide.org
> > 
> > Agreed. I like PyDev in Eclipse, but sometimes I just want to try
> > out something quick in the interpreter, to ensure I understand it
> > or do a quick experiment. Since indentation is syntactically
> > significant in Python, I think fixing the interpreter to produce
> > good, readable, cut-and-pasteable, and Pythonic code is more
> > important than a cosmetic feature, but less important than true
> > bugs.
> > --
> 
> 
> Actually, if you're in PyDev/Eclipse already, you can just use the
> interactive shell that PyDev provides:
> http://pydev.org/manual_adv_interactive_console.html
> 
> Cheers,
> 
> Fabio

Awesome. Exactly what I was looking for. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python lists

2012-12-28 Thread Alex
Manatee wrote:

> On Friday, December 28, 2012 9:14:57 AM UTC-5, Manatee wrote:
> > I read in this:
> > 
> > ['C100, C117', 'X7R 0.033uF 10% 25V  0603', '0603-C_L, 0603-C_N',
> > '10', '2', '', '30', '15463-333', 'MURATA', 'GRM188R71E333KA01D',
> > 'Digi-Key', '490-1521-1-ND', '']
> > 
> > 
> > 
> > Then I need to convert it to this:
> > 
> > [['C100', 'C117'], 'X7R 0.033uF 10% 25V  0603', '0603-C_L',
> > '0603-C_N', '10', '2', '', '30', '15463-333', 'MURATA',
> > 'GRM188R71E333KA01D', 'Digi-Key', '490-1521-1-ND', '']]
> > 

l = ['C100, C117', 'X7R 0.033uF 10% 25V  0603', '0603-C_L, 0603-C_N',
'10', '2', '', '30', '15463-333', 'MURATA', 'GRM188R71E333KA01D',
'Digi-Key', '490-1521-1-ND', '']

[item.split(',') if i == 0 else item for i, item in enumerate(l)]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is awesome (Project Euler)

2012-12-31 Thread Alex
Yes. Although sometimes I fear that we are becoming a society of
end-users who rely too much on the capability of our tools and fail to
take the time to understand the fundamentals upon which those tools are
based or cultivate the problem-solving skills that Project Euler
appears to be trying to hone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python GUI able to display a spatial image

2013-01-25 Thread Alex
Hello, does python have capabilities to display a spatial image and read the 
coordinates from it? If so, what modules or extension do I need to achieve 
that? I'll appreciate any help. 

Thanks, 
Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


GeoBases: data services and visualization

2013-01-29 Thread Alex
This new project provides tools to play with geographical data. It also works 
with non-geographical data, except for map visualizations :).

There are embedded data sources in the project, but you can easily play with 
your own data in addition to the available ones. Files containing data about 
airports, train stations, countries, ... are loaded, then you can:

 - performs various types of queries ( find this key, or find keys with this 
property)
 - fuzzy searches based on string distance ( find things roughly named like 
this)
 - geographical searches ( find things next to this place)
 - get results on a map, or export it as csv data, or as a Python object

This is entirely written in Python. The core part is a Python package, but 
there is a command line tool as well! 

For tutorials and documentation, check out 
http://opentraveldata.github.com/geobases/
-- 
http://mail.python.org/mailman/listinfo/python-list


K-means Python code analyse

2016-11-23 Thread Alex
Can please anyone explaine me what do each of these code lines and how k-means 
algorithm works?


from scipy.cluster.vq import *
from scipy.misc import imresize
from pylab import *
from PIL import Image
steps = 500 
im = array(Image.open("empire.jpg"))
dx = im.shape[0] / steps
dy = im.shape[1] / steps
# compute color features for each region
features = []
for x in range(steps): 
for y in range(steps):
R = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,0])
G = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,1])
B = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,2])
features.append([R,G,B]) 
features = array(features,"f") # make into array
# cluster
centroids,variance = kmeans(features,3)
code,distance = vq(features,centroids)
# create image with cluster labels
codeim = code.reshape(steps,steps)
codeim = imresize(codeim,im.shape[:2],interp="nearest")
figure()
imshow(codeim)
show()
-- 
https://mail.python.org/mailman/listinfo/python-list


IDLE missing !

2019-09-01 Thread Alex
I tried downloading the 3.7.4 version of python and and then tried to install 
tensorflow but found that TF is only available for version 3.5.x.
Thus uninstalled the 3.7.4. version and tried downloading multiple 3.5.x 
version while all of them downloaded but I couldn’d find the IDLE shell with 
them.
They do get installed into the system but the IDLE is not installed.
what should I do about it ?

Regrards,
Alex

Sent from Mail for Windows 10

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


what does 0 mean in MyApp(0)

2005-09-30 Thread Alex
I'm looking at a tutorial with the code below

from wxPython.wx import *

class MyApp(wxApp):
def OnInit(self):
frame = wxFrame(NULL, -1, "winApp", size = (800,640))
frame.Show(true)
self.SetTopWindow(frame)
return true

app = MyApp(0)
app.MainLoop()

Everything is explained nicely except the zero parameter in MyApp(0).
Anybody knows what that zero refers to? 

Alex

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


Re: what does 0 mean in MyApp(0)

2005-09-30 Thread Alex
Thanks for the replies. It seems that I have three options
1. app=MyApp()
2. app=MyApp(0)
3. app=MyApp('myfile.txt')

1. In the first case the output stream will be set to stdout/stderr,
which means that errors will be sent to a window which will be closed
when the app crashes.
2. In the second case the output will be set to the command prompt
window, which means that I will be able to catch the errors when my app
crashes.
3. There is also a third alternative which is to set the output to  a
file.

Alterbnative 2 is simple and useful, so that's why everybody use that
alternative.

Is that correct?
Alex

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


how do you pronounce wxpython

2005-10-08 Thread Alex
My native language is not English so I just wonder how you pronounce
wxPython.

vi-ex python
double-you-ex python
wax-python

or something else

Thanks

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


Batteries Included?

2005-10-10 Thread Alex
One of the first things I wanted to do when I start learning Python was
to produce a simple standalone application that I could distribute to
my users (windows users). Python's moto is "Batteries Included", but
where are the batteries for making exe files and making an installer
file? I had to download, install and use py2exe and Inno Setup in order
to accomplish this. I might be wrong expecting that a language whose
moto is "Batteries Included" would be able to produce exe files. Are
there plans to do this in the future version of Python?

Alex

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


pickling class instances with __slots__

2005-10-28 Thread Alex
I would greatly appreciate an advice on the following matter that was
very much discussed circa 2002 but in all this discussion I could not
find the final answer with a code example. Neither I can find it in
Python documentation.


I have a series of new classes with child-parent relationship and each
has unique __slots__. They don't have __dict__ . I need to be able to
pickle and unpickle them. As far as I could understand, I need to
provide __getstate__  and  __setstate__ methods for each class. Is
there a universally accepted code for each method? If so, what is it?
If there is no standard, what works?


TIA


Alex

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


Pickling and unpickling inherited attributes

2005-10-30 Thread Alex
I have a serious problem and I hope there is some solution. It is
easier to illustrate with a simple code:

>>> class Parent(object):
__slots__=['A', 'B']
def __init__(self, a, b):
self.A=a; self.B=b
def __getstate__(self):
return self.A, self.B
def __setstate__(self, tup):
self.A, self.B=tup


>>> class Child(Parent):
__slots__=['C',]
def __init__(self, c):
self.C=c
def __getstate__(self):
return self.C,
def __setstate__(self, tup):
self.C, =tup


>>> obj=Child(1)
>>> obj.A=2
>>> obj.B=3
>>> obj.A
2
>>> obj.B
3
>>> obj.C
1
>>> objct.Z=4

Traceback (most recent call last):
  File "", line 1, in -toplevel-
objct.Z=4
AttributeError: 'Child' object has no attribute 'Z'

So far so good.. Object obj inherited attributes (A and B) from the
parent class and refuses to take any new ones. But look what happens
when I try to pickle and unpickle it:

>>> import cPickle
>>> File=open('test', 'w')
>>> cPickle.dump(obj, File)
>>> File.close()
>>>
>>> file1=open('test', 'r')
>>> objct=cPickle.load(file1)
>>> file1.close()
>>> objct.A

Traceback (most recent call last):
  File "", line 1, in -toplevel-
objct.A
AttributeError: A
>>> objct.C
1

Its own attribute (C) value is restored but the value of an inherited
attribute (A) is not. I tried pickling protocol 2, and module pickle
instead of cPickle, all with the same result.

What can be done?! Or maybe nothing can be done?

I would greatly appreciate an advice. A lot of code is written, but now
we have a need for pickling and unpickling objects and discovered this
problem.

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


Re: Pickling and unpickling inherited attributes

2005-10-30 Thread Alex
Sorry, I copied and pasted a wrong piece from shell at one part of the
code:

objct.Z=4 was in fact obj.Z=4 and it did refuse to accept Z (because it
is not in __slots__).

But the question remains: why the value of attribute A is not preserved
during pickling and unpickling and what can be done about it, if
anything?

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


Re: Pickling and unpickling inherited attributes

2005-10-30 Thread Alex
Thanks so much! It makes perfect sense and I am sure it will work now.

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


Re: Pickling and unpickling inherited attributes

2005-11-01 Thread Alex
Thanks to both Alex Martelli and Steve Holden.. We need __slots__ for
other reasons, too long to explain, but basically to prevent assignment
of extra attributes.

I ended up changing child classes this way:

def __getstate__(self):
return(Parent.__getstate__(self), self.C)
def __setstate__(self, data):
Parent.__setstate__(self, data[0])
self.C=data[1:]

This seems to work fine.

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


Re: Pickling and unpickling inherited attributes

2005-11-02 Thread Alex

> >
> OK, but do be aware that slots was intended solely as a
> memory-conservation measure where large numbers of objects are being
> created. You are therefore subverting its true intent by using it to
> limit the assignment of extra attributes (and there has been much recent
> discussion on this list, though not in this thread, about what to do
> instead.
>
> regards
>   Steve
> --


Oh, that too... We have tens of thousands of these objects in the
memory at the same moment, so memory conservation is another reason for
slots.

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


setattr for secondary attribute

2005-11-20 Thread Alex
I apologize for asking  maybe a very trivial question.
I have a new class object A with slots. One of the slots is, for
example, object spam. Object spam, in turn, also has slots and one of
them is attribute eggs. I need to assign a new value to eggs. In other
words, I need to perform the following:

A.spam.eggs=newValue

The problem is that I have only a string s='spam.eggs' with which to
work, so I cannot write an expression written above. I tried to use
setattr:

setattr(A, s, newValue)

but this does not work. It says that object A does not have attribute
spam.eggs

How would you do it? TIA.

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


Re: setattr for secondary attribute

2005-11-21 Thread Alex
Great! Thanks, it works (of course).

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


Basic file operation questions

2005-02-02 Thread alex
Hi,

I am a beginner with python and here is my first question:
How can I read the contents of a file using a loop or something? I open
the file with file=open(filename, 'r') and what to do then? Can I use
something like

for xxx in file:
   


Thanks for help
Alex

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


global variables

2005-02-02 Thread alex
Hi,

is it possible to create 'global' variables that can be seen in all
other classes?

Alex

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


Re: Jargons of Info Tech industry ... and Xah Lee (I mean Jerry) Springer

2005-08-14 Thread Alex
Xah Lee wrote:
> Jargons of Info Tech industry
> 
> (A Love of Jargons)
> 
> Xah Lee, 2002 Feb
> 
> The jargon-soaked stupidity in computing field can be grouped into
> classes  ...  One flagrant example is Sun Microsystem's
> Java stuff  ...  fucking stupid Java and fuck Sun
> Microsystems. This is just one example of Jargon hodgepodge of one
> single commercial entity. 
> 
> The other class of jargon stupidity is from computing practitioners, of
> which the Unix/Perl community is exemplary  ...  These types of
> jargons exudes juvenile humor. Cheesiness and low-taste is their
> hall-mark.
> 
> There is another class of jargon moronicity, which i find them most
> damaging to society,   ...  I think the reason for these, is that 
> these
> massive body of average programers usually don't have much knowledge of
> significant mathematics,   ...  these people defining
> or hatching terms   ...  are often a result of sopho-morons
> trying to sound big.
> 
   ...  Because most programers are
> sopho-morons who are less capable of clear thinking but nevertheless
> possess human vanity,   ...  
> 
   ...  One can see that the term
> “closure” is quite vague in conveying its meaning. The term
> nevertheless is very popular among talkative programers and dense
> tutorials, precisely because it is vague and mysterious. These
> pseudo-wit living zombies, never thought for a moment that they are
> using a moronic term,   ...  (for an example of the
> fantastically stupid write-up on closure by the Perl folks  ...  
> 
   ... 
> 
   ...  (one may think from the above tree-diagram
> that Java the language has at least put clear distinction to interface
> and implementation, whereas in my opinion they are one fantastic fuck
> up too, in many respects.)
> 

I've extracted the preceding castigating snippets from Mr. Lee's Jargon 
"thesis". :)) When reciprocated upon his own posts; one could offer up 
the proverb, "he who lives in glass houses should not throw stones."

His inflammatory rhetoric - light on facts, weak in application, and 
generously peppered with self-aggrandizing insults - would probably 
offend Jerry Springer by comparison.

Perhaps the "professor" should more carefully scrutinize himself before 
attempting to castigate others, less he acquire the reputation of a 
hypocrite, e.g. -
   "are often a result of sopho-morons trying to sound big.";
   "who are less capable of clear thinking but nevertheless possess
human vanity";
"These types of jargons exudes juvenile humor.";
"Cheesiness and low-taste is their hall-mark."

Elementary courses in Critical Reasoning, Topical Research, Grammar, 
Creative Writing, and Technical Writing also seem warranted.

A little one on one time with a mental health practitioner probably 
wouldn't hurt either. :))

P.S. Until then, does anyones else deem it appropriate to give 
"professor" Lee the nickname "Xah Lee Springer"?
-- 
http://mail.python.org/mailman/listinfo/python-list

is dict.copy() a deep copy or a shallow copy

2005-09-04 Thread Alex
Entering the following in the Python shell yields

>>> help(dict.copy)
Help on method_descriptor:

copy(...)
D.copy() -> a shallow copy of D

>>>

Ok, I thought a dictionary copy is a shallow copy. Not knowing exactly
what that meant I went to http://en.wikipedia.org/wiki/Deep_copy where
I could read

"...a deep copy is copy that contains the complete encapsulated data of
the original object, allowing it to be used independently of the
original object. In contrast, a shallow copy is a copy that may be
associated to data shared by the original and the copy"

Going back to Python shell I tested the following

>>> D={'Python': 'good', 'Basic': 'simple'}
>>> E=D.copy()
>>> E
{'Python': 'good', 'Basic': 'simple'}
>>> D['Basic']='oh my'
>>> D
{'Python': 'good', 'Basic': 'oh my'}
>>> E
{'Python': 'good', 'Basic': 'simple'}
>>>

Hmm, this looks like a deep copy to me?? I also tried

>>> D={'Python': 'good', 'Basic': 'simple'}
>>> E=D
>>> E
{'Python': 'good', 'Basic': 'simple'}
>>> E['Basic']='oh my'
>>> E
{'Python': 'good', 'Basic': 'oh my'}
>>> D
{'Python': 'good', 'Basic': 'oh my'}
>>>

which looks like a shallow copy to me?? So my hypothesis is that E=D is
a shallow copy while E=D.copy() is a deep copy.

So is the documentation wrong when they claim that D.copy() returns a
shallow copy of D, or did I misunderstand the difference between a deep
and shallow copy?

Thanks

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


Re: is dict.copy() a deep copy or a shallow copy

2005-09-05 Thread Alex
Thanks max,
Now it's much clearer. I made the following experiment
>>>#1
>>> D={'a':1, 'b':2}
>>> D
{'a': 1, 'b': 2}
>>> E=D.copy()
>>> E
{'a': 1, 'b': 2}
>>> D['a']=3
>>> D
{'a': 3, 'b': 2}
>>> E
{'a': 1, 'b': 2}
>>>#2
>>> D={'a':[1,3], 'b':[2,4]}
>>> D
{'a': [1, 3], 'b': [2, 4]}
>>> E=D.copy()
>>> E
{'a': [1, 3], 'b': [2, 4]}
>>> D['a'][0]=9
>>> D
{'a': [9, 3], 'b': [2, 4]}
>>> E
{'a': [9, 3], 'b': [2, 4]}
>>>#3
>>> import copy
>>> F=copy.deepcopy(D)
>>> D
{'a': [9, 3], 'b': [2, 4]}
>>> F
{'a': [9, 3], 'b': [2, 4]}
>>> D['a'][0]=7
>>> D
{'a': [7, 3], 'b': [2, 4]}
>>> F
{'a': [9, 3], 'b': [2, 4]}
>>>

A shallow copy of an object is a copy of the first-level data members
and if one of the members is a pointer, then only the pointer value is
copied, not the structure pointed to by the pointer. The original
object and its shallow copy share the memory space occupied by these
structures.
A deep copy of an object is a copy of everything (including the
structures pointe to by the pointers). The original object and its deep
copy do not share any memory space.

In #1 no pointers are involved so changing a value affects only D but
not E.

In #2 D['a'] and E['a'] are pointers that both point to the same memory
space. Changing that memory space doesn't change the pointers
themsleves.

In #3 a deepcopy makes sure that a copy is made not just of the
pointers but also of the things pointed to.

So the lesson to be learned is that if you make a copy of a dictionary
whose values are pointers to other structures then a deepcopy prevents
a coupling between a the original and the copy. 

Alex

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


dict and __cmp__() question

2005-09-07 Thread Alex
Entering

>>> help(dict)
Help on class dict in module __builtin__:

class dict(object)
 |  dict() -> new empty dictionary.
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |  (key, value) pairs.
 |  dict(seq) -> new dictionary initialized as if via:
 |  d = {}
 |  for k, v in seq:
 |  d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value
pairs
 |  in the keyword argument list.  For example:  dict(one=1, two=2)
 |
 |  Methods defined here:
 |
 |  __cmp__(...)
 |  x.__cmp__(y) <==> cmp(x,y)
 |
 |  __contains__(...)
 |  D.__contains__(k) -> True if D has a key k, else False

snip

 |  update(...)
 |  D.update(E, **F) -> None.  Update D from E and F: for k in E:
D[k] = E[k]
 |  (if E has keys else: for (k, v) in E: D[k] = v) then: for k in
F: D[k] = F[k]
 |
 |  values(...)
 |  D.values() -> list of D's values

Now I understand methods like update(...) and values(...), for instance

>>> D={'a':1, 'b':2}
>>> D.values()
[1, 2]
>>>

But what are those with double underscore? For instance __cmp__(...)?

I tried
>>> D.cmp('a','b')

Traceback (most recent call last):
  File "", line 1, in -toplevel-
D.cmp('a','b')
AttributeError: 'dict' object has no attribute 'cmp'
>>>

Alex

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


is interactive mode same as calculator mode?

2005-09-09 Thread Alex
Loking at Rossum's tutorial I've seen that he sometimes uses the
expression "interactive mode" and sometimes "calculator mode". Or these
concepts same?

I've made the following assertion.

"When Python prompts for the next command with the primary prompt ">>>
", the interpreter is said to be in an interactive mode, or in a
calculator mode. In interactive mode, the Python interpreter acts as a
simple calculator: you can type an expression at it and it will write
back the value of that expression."

Is this correct or incorrect?

Alex

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


where is sys.path initialized?

2005-09-09 Thread Alex
Rossum's tutorial states
"Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory containing
the input script (or the current directory)"

I'm running Python standard installation (ver 2.4) on Windows XP. Where
can I find the "input script" where the sys.path is defined?

Alex

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


Re: where is sys.path initialized?

2005-09-09 Thread Alex
No one is answering this question. Why, is it a bit unclear or what?
All I wanted to do was to add the path C:\Python24\mypython to the
sys.path so that I could put all my stuff there instead of mixing it
with the stuff that comes with the installation. And I wanted to do it
permanently som that I wouldn't have to use sys.path.append every time
I started Python interpreter.

Here is what I did, and it worked, but I still don't know why. If
somebody has an explanation please tell me.

1. My computer -> Properties->Advanced->Environment variables->System
variables ->New

2. In Variable name field enter PYTHONPATH and in Variable value field
enter C:\Python24\mypython

3. OK, OK, OK to close all the dialog boxes.

4. Restart the computer (it's essential to restart the computer and not
just the Python shell).

5. Open the Python shell and enter
>>> import sys
>>> sys.path
If you've done exactly as I've described here you should see
C:\Python24\mypython in the list.

Alex

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


How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Alex
Rossum's tutorial on Python states:
"open() returns a file object, and is most commonly used with two
arguments: 'open(filename, mode)'
mode 'r+' opens the file for both reading and writing."

Here's a little session in Python's interactive window

>>> f=open('mytext.txt','w+')
>>> f.write('My name is Bob')
>>> s=f.read()
>>> s.len()
>>> len(s)
4082
>>>f.close()

If I open the file mytext.txt in Notepad I see something that begins
with

"My name is Bob  VwMÚ¸x¶ Ð"

and goes on for approximately 4082 characters.

What's happening??

Alex

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


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Alex
Yes the problem seems to be exactly that. I'm moving around the file
pointer. This piece of code works. Observe the only thing I've added is
f.seek(0)

>>> f=open('mytext.txt', 'w+')
>>> f.write('My name is Bob')
>>> f.seek(0)
>>> s=f.read()
>>> print s
My name is Bob
>>> f.close()

I've found this piece of clue at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_fopen.2c_._wfopen.asp
"However, when you switch between reading and writing, there must be an
intervening fflush, fsetpos, fseek, or rewind operation. The current
position can be specified for the fsetpos or fseek operation, if
desired."

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


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Alex
Thanks Steven, very good explaination. f.seek(0) does the trick!
Alex

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


Test for structure

2005-02-16 Thread alex
Hi there,

how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list of
character strings line ['word1', 'word2',...]

So how can I test if a variable 'a' is either a single character string
or a list? I tried:

if a is list:


but that does not work. I also looked in the tutorial and used google
to find an answer, but I did not.

Has anyone an idea about that?

Alex

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


Multiple initialization methods?

2005-02-16 Thread alex
Hi,

it is possible to define multiple initialization methods so that the
method is used that fits?

I am thinking of something like this:

  def __init__(self, par1, par2):
self.init(par1, par2);

  def __init__(self, par1):
self.init(par1, None)

  def init(self, par1, par2):
 ...
 ...

So if the call is with one parameter only the second class is executed
(calling the 'init' method with the second parameter set to 'None' or
whatever. But this example does not work. 

How to get it work?

Alex

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


Re: Python, Perl & PDF files

2005-04-25 Thread Alex
rbt wrote:
I just want to read PDF files in a portable way (windows, linux, mac) 
from within Python.

reportlab is an excelent tool for generating pdf files, but as far as I 
know, it doesn't "read" pdf's.
http://www.reportlab.org/rl_toolkit.html

there's a project in sourceforge called pdf playground.
http://sourceforge.net/projects/pdfplayground
it's supposed to read/write pdf files..
I never tried it, you might want to check it out.
I don't think there's something like perl's pdf support on python.
but you can find tools and libs that might help.
regards,
Alex
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which IDE is recommended?

2005-04-27 Thread alex
jeff elkins wrote:
Is Boa actively used? There doesn't seem to be much activity its mailing list. 
The tutorial fails for me using python 2.3.5, wxpython 2.5.3.2 and Boa 0.4.0 
under debian sid.

Jeff
 

Boa is not a dead project if that's your concern, maybe it's not getting 
a lot of attention, but the cvs is getting some decent activity, 0.4.x 
was recently released, and I've seen some bug reports being fixed in cvs 
quite fast too.

It's really a great product if you can live with its poor documentation 
and its constraint-oriented design (as opposed to sizer oriented)
yes I know it supports sizers, but it wasn't designed for it, and you'll 
probably end up manually coding the sizers because the built-in support 
is really weird.

anyway,  I consider boa the best rad tool for wxpython, it could be 
better.. but it's still the best of its kind imho.

regards,
Alex Verstraeten.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: eGenix PyRun - One file Python Runtime 2.1.0

2015-07-16 Thread Alex
Do you have Python 2.7 64bit versions available for Solaris (10/11)
x86/SPARC, AIX, and HP-UX IA/RISC? I've had the displeasure of having to
install 64bit Python on Solaris and AIX and it's an experience I would not
recommend even though OpenCSW and Perzl have done much of the legwork
already. I'd also just be happy with any pointers to building PyRun or
regular Python on such systems if such currently there exist no such builds.

On Wed, May 13, 2015 at 10:34 AM, Cristiano Cortezia <
cristiano.corte...@gmail.com> wrote:

> In one of the next releases we'll probably add a tool to bundle
>> complete applications together with pyrun, perhaps even by
>> recompiling it to include the application byte code files
>> right in the binary like we do for the stdlib.
>
>
> Well, that would be simply awesome. Looking forward to it.
>
> PS: you guys should definitely advertise this work on the embedded
> software community.
>
>
> 2015-05-13 11:29 GMT-03:00 M.-A. Lemburg :
>
>> On 13.05.2015 16:09, Cristiano Cortezia wrote:
>> > Well I gave it a try, and it seems my assumptions were *somehow* true.
>> > Here is what I got when running one of my apps in single shot mode
>> (load,
>> > run, terminate):
>> >
>> > *default python distribution*
>> > total time 9.022s
>> > ENOENT's count 7377
>> >
>> > *pyrun*
>> > total time 8.455s
>> > ENOENT's count 3064
>> >
>> > So, it indeed failed much less to open files, but I guess this didn't
>> make
>> > that much difference after all (500ms).
>>
>> PyRun has the advantage of being able to read the byte code
>> directly from the binary (using memory mapping). However,
>> it still needs to run the same startup machinery as Python
>> itself.
>>
>> Note that startup time for Python was a lot worse before
>> Python used the same approach as PyRun to compile in the
>> parsed sysconfig data.
>>
>> > Perhaps it is because this app has some external dependencies (22 to be
>> > precise) not bundled on pyrun that had to be scanned by the interpreter
>> > anyway. If by any means we could bundle them all the same way, than it
>> > could bring a much higher performance gain. But I guess it is not really
>> > safe-feasible.
>>
>> It's certainly possible to use the pyrun build system to create
>> bundles with more packages and tools included.
>>
>> The one we're shipping has most of the stdlib included,
>> but leaves all the application code to reside on the
>> sys.path or in a ZIP archive.
>>
>> In one of the next releases we'll probably add a tool to bundle
>> complete applications together with pyrun, perhaps even by
>> recompiling it to include the application byte code files
>> right in the binary like we do for the stdlib.
>>
>> --
>> Marc-Andre Lemburg
>> eGenix.com
>>
>> Professional Python Services directly from the Source  (#1, May 13 2015)
>> >>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>> >>> mxODBC Plone/Zope Database Adapter ...   http://zope.egenix.com/
>> >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/
>> 
>> 2015-05-13: Released mxODBC Connect 2.1.3 ... http://egenix.com/go75
>> 2015-05-11 : Released eGenix PyRun
>> 2.1.0 ...   http://egenix.com/go74
>> 2015-05-25 : PyWaw Summit 2015,
>> Warsaw, Poland ...  12 days to go
>>
>>eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
>> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
>>Registered at Amtsgericht Duesseldorf: HRB 46611
>>http://www.egenix.com/company/contact/
>>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: eGenix PyRun - One file Python Runtime 2.1.0

2015-07-17 Thread Alex
They don't offer any free versions for those systems and their licenses are
quite expensive.

On Fri, Jul 17, 2015 at 2:26 AM, Laura Creighton  wrote:

> I think Activestate makes a Python 2.y for Solaris.
> http://www.activestate.com/activepython
>
> I've never used it.
>
> Laura
>
> In a message of Thu, 16 Jul 2015 18:58:37 -0400, Alex writes:
> >Do you have Python 2.7 64bit versions available for Solaris (10/11)
> >x86/SPARC, AIX, and HP-UX IA/RISC? I've had the displeasure of having to
> >install 64bit Python on Solaris and AIX and it's an experience I would not
> >recommend even though OpenCSW and Perzl have done much of the legwork
> >already. I'd also just be happy with any pointers to building PyRun or
> >regular Python on such systems if such currently there exist no such
> builds.
> >
> >On Wed, May 13, 2015 at 10:34 AM, Cristiano Cortezia <
> >cristiano.corte...@gmail.com> wrote:
> >
> >> In one of the next releases we'll probably add a tool to bundle
> >>> complete applications together with pyrun, perhaps even by
> >>> recompiling it to include the application byte code files
> >>> right in the binary like we do for the stdlib.
> >>
> >>
> >> Well, that would be simply awesome. Looking forward to it.
> >>
> >> PS: you guys should definitely advertise this work on the embedded
> >> software community.
> >>
> >>
> >> 2015-05-13 11:29 GMT-03:00 M.-A. Lemburg :
> >>
> >>> On 13.05.2015 16:09, Cristiano Cortezia wrote:
> >>> > Well I gave it a try, and it seems my assumptions were *somehow*
> true.
> >>> > Here is what I got when running one of my apps in single shot mode
> >>> (load,
> >>> > run, terminate):
> >>> >
> >>> > *default python distribution*
> >>> > total time 9.022s
> >>> > ENOENT's count 7377
> >>> >
> >>> > *pyrun*
> >>> > total time 8.455s
> >>> > ENOENT's count 3064
> >>> >
> >>> > So, it indeed failed much less to open files, but I guess this didn't
> >>> make
> >>> > that much difference after all (500ms).
> >>>
> >>> PyRun has the advantage of being able to read the byte code
> >>> directly from the binary (using memory mapping). However,
> >>> it still needs to run the same startup machinery as Python
> >>> itself.
> >>>
> >>> Note that startup time for Python was a lot worse before
> >>> Python used the same approach as PyRun to compile in the
> >>> parsed sysconfig data.
> >>>
> >>> > Perhaps it is because this app has some external dependencies (22 to
> be
> >>> > precise) not bundled on pyrun that had to be scanned by the
> interpreter
> >>> > anyway. If by any means we could bundle them all the same way, than
> it
> >>> > could bring a much higher performance gain. But I guess it is not
> really
> >>> > safe-feasible.
> >>>
> >>> It's certainly possible to use the pyrun build system to create
> >>> bundles with more packages and tools included.
> >>>
> >>> The one we're shipping has most of the stdlib included,
> >>> but leaves all the application code to reside on the
> >>> sys.path or in a ZIP archive.
> >>>
> >>> In one of the next releases we'll probably add a tool to bundle
> >>> complete applications together with pyrun, perhaps even by
> >>> recompiling it to include the application byte code files
> >>> right in the binary like we do for the stdlib.
> >>>
> >>> --
> >>> Marc-Andre Lemburg
> >>> eGenix.com
> >>>
> >>> Professional Python Services directly from the Source  (#1, May 13
> 2015)
> >>> >>> Python Projects, Coaching and Consulting ...
> http://www.egenix.com/
> >>> >>> mxODBC Plone/Zope Database Adapter ...
> http://zope.egenix.com/
> >>> >>> mxODBC, mxDateTime, mxTextTools ...
> http://python.egenix.com/
> >>>
> 
> >>> 2015-05-13: Released mxODBC Connect 2.1.3 ...
> http://egenix.com/go75
> >>> 2015-05-11 <http://egenix.com/go752015-05-11>: Released eGenix PyRun
> >>> 2.1.0 ...   http://egenix.com/go74
> >>> 2015-05-25 <http://egenix.com/go742015-05-25>: PyWaw Summit 2015,
> >>> Warsaw, Poland ...  12 days to go
> >>>
> >>>eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
> >>> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
> >>>Registered at Amtsgericht Duesseldorf: HRB 46611
> >>>http://www.egenix.com/company/contact/
> >>>
> >>
> >>
> >> --
> >> https://mail.python.org/mailman/listinfo/python-list
> >>
> >>
> >
> >--
> >https://mail.python.org/mailman/listinfo/python-list
> >
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem with function

2013-03-21 Thread Alex
leonardo selmi wrote:

> hi all,
> 
> i wrote the following code:
> 
> def find(word, letter):
> index = 0
> while index < len(word):
> if word[index] == letter:
> return index
> index = index + 1
> return -1
> 
> if i run the program i get this error: name 'word' is not defined.
> how can i solve it?
> 

What does your call to find look like? I called it with:

find("word", 'd')

and it returned 3, as expected.

If I call find with

find(word, 'd')

I get an error, as expected, since I have not assigned a string to the
name word.


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


Re: Why does 1**2**3**4**5 raise a MemoryError?

2013-03-31 Thread Alex
Dave Angel wrote:

> On 03/31/2013 02:56 AM, morphex wrote:
> > > > > 1**2
> > 1
> > > > > 1**2**3
> > 1
> > > > > 1**2**3**4
> > 1L
> > > > > 1**2**3**4**5
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > MemoryError
> > > > > 
> > 
> > Does anyone know why this raises a MemoryError?  Doesn't make sense
> > to me.
> 
> Perhaps you didn't realize that the expression will be done from
> right to left.  

Really? 

The Python 3 documentation
(http://docs.python.org/3/reference/expressions.html) says in section
6.14 (Evaluation order) that "Python evaluates expressions from left to
right" (an exception being when evaluating assignments, in which case
the RHS of the assignment is calculated first, in left-to-right order).

Section 6.4 discusses the power operator specifically and does not
contradict 6.14 except that the power operator uses right-to-left
evaluation in the presence of unparenthesized unary operators.

Neither of these two exception cases appear to apply here, so I think
the OP is reasonable in expecting Python to do the operation
left-to-right.

Am I missing something written somewhere else in the docs? Are the docs
I quoted wrong? Please help me understand the discrepancy I am
perceiving here.

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


Re: Why does 1**2**3**4**5 raise a MemoryError?

2013-03-31 Thread Alex
Chris Angelico wrote:

> 
> Opening paragraph, "... exponentiation, which groups from right to
> left". It follows the obvious expectation from mathematics. (The OP is
> using Python 2, but the same applies.)

Thanks. I did miss that parenthetical comment in para 6.15, and that
would have been the correct place to look, since it appears that
operators are not parts of expressions, but rather separate them. Is
that the "obvious expectation from mathematics," though? Given that

  3
 5
4

(i.e.: 4**5**3) is transitive, I would have expected Python to exhibit
more consistency with the other operators. I guess that is one of the
foolish consistencies that comprise the hobgoblins of my little mind,
though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Faster copying of composite new-class objects

2005-12-17 Thread Alex
Hi,

My program requires copying thousands of composite new-class objects. I
found that the following: objCopy=cPickle.loads(cPickle.dumps(obj,
protocol=2)) works about 4 times faster than
copyObj=copy.deepcopy(obj). Is there any way to do it even faster?

All objects have slots, __getstate__ and __setstate__.

TIA,

Alex

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


How to get file name on a remote server with ftplib?

2007-01-05 Thread alex
Hello,

My script is trying to get a file from a remote server, every day it
ftps from a directory. My code works perfect if I know the name of the
file in the remote directory.

ftp.retrbinary('RETR ' + filename, handleDownload)

The problem is that in the future the name of the file is going to be
aleatory. How can I get the file's name (only one file is in that
directory) and store it in a variable before executing ftp.retrbinary?

Thanks a lot for your help,

Alex

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


Re: How to get file name on a remote server with ftplib?

2007-01-08 Thread alex
Thanks guys for the help! I used nlst().
The ftputil seems to be very helpfull, but getting a new library in an
organization like the one I work at  is big issue. Thanks anyway :)



[EMAIL PROTECTED] wrote:
> alex wrote:
> > Hello,
> >
> > My script is trying to get a file from a remote server, every day it
> > ftps from a directory. My code works perfect if I know the name of the
> > file in the remote directory.
> >
> > ftp.retrbinary('RETR ' + filename, handleDownload)
> >
> > The problem is that in the future the name of the file is going to be
> > aleatory. How can I get the file's name (only one file is in that
> > directory) and store it in a variable before executing ftp.retrbinary?
> >
> > Thanks a lot for your help,
> >
> > Alex
>
> You can use the nlst(dirname) method to retrieve a directory listing on
> the remote server. If the remote server doesn't support NLST command
> rhen you could do ftp.retrlines('LIST')  and parse the results to get a
> directory listing.

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


popen, Pipes with programs that expect user input

2007-01-08 Thread Alex
Hello everyone,


I am writing a terminal server client-server application, that offers
the client the ability to run commands on the server and read their
output.

So far everything works fine, but I encounter a problem with commands
which require some sort of user input; i.e. they don't return
immediately.

This is my setup:
Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)]
on win32  


-
import os

def myExecEx(command):
"""Executes a command and returns a tuple (stdin,
stdout_stderr)"""  
outErrFile, inFile = os.popen4(command)

return (inFile, outErrFile)


fouterr, fin = myExecEx('date')   # try 'date /t' as well
#fin.write('\n')

try:
data=fouterr.read()
print data
except:
print "an exception occurred"
-

On Windows, the 'date' command will show the current date, and then
prompt me to enter a new one (thus waiting for something to come to
STDIN)

I am reading the output with:
  data=fouterr.read()

but data is empty (also, I must mention that "an exception occurred"
is not shown)

If I execute
   myExecEx('date /t')

(the /t parameter tells the date tool that it has to print the current
date and not wait for user input), then the program works as
expected).

Also, I noticed that if I uncomment the line in which I wrote to
STDIN:
  fin.write('\n')

then I can read STDOUT without problems (but this is counter-intuitive
to me; I don't know what to write to STDIN before I see what STDOUT
has to say). 


I have tried other commands from the popen family, but in either case
the behaviour was the same.


Could someone point out the cause of this?  It seems to me that the
interpreter is stuck at this line
  data=fouterr.read()

and it won't go forward unless popen returns. If so, how should the
objective be achieved?


Thank you

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


Re: array type casting problem in scipy.interpolate

2005-04-30 Thread Alex
On 30 Apr 2005 12:32:31 -0700, bgs <[EMAIL PROTECTED]> said:
> The routine requires real arrays, and you are giving it one complex
> one.  It does not know what to do with the complex array.  What are you
> expecting it to do?  If you need the real and imaginary parts to be
> separately interpolated, then split the complex array into two real
> arrays and use the routine twice.

Hello,

Thanks for the pointer. I will interpolate the real and imaginary parts
separately then.

Regards,

Alex


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


In search of prothon source

2005-05-14 Thread Alex
Since the DNS servers hosting prothon.org have stopped responding, the 
sole source of the source of prothon online that I can find has become 
inaccessable.  I was wondering if anyone subscribed has a copy of the 
source for the last C version of prothon, and would be kind enough to 
post a copy online.

Thanks,

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


output object fields into a file

2007-08-13 Thread Alex
Hello,  I am rather new to python.  Maybe my thinking is in the
paradigm of C++, that makes me hard to make sense of some python
scripts (interacting with C# code) written by my colleague.  I am
thinking of outputting all objects and their fields of each script
into a file.  The tricky part is I am NOT quite sure of the type of
the fields.  How can I output these objects and their fields into an
external file.  Any code sample would be highly appreciated !!!

Alex

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


What's the difference ?

2007-08-29 Thread Alex
Hye,

I was just wondering what is the difference between

>> if my_key in mydict:
>> ...

and

>> if mydict.has_keys(my_key):
>> ...

I've search a bit in the python documentation, and the only things I
found was that they are "equivalent".

But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
Cookbook/Python/Recipe/59875" ), there is difference between the two
notation.

Thanks in advance

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


Re: An Editor that Skips to the End of a Def

2007-09-20 Thread alex
> Paul Rudin wrote:
>> "W. Watson" <[EMAIL PROTECTED]> writes:
>>
>>> Is there an editor that allows one to position to put the cursor and
>>> then by pushing some button goes to the end of the def?
>>
>> C-M-e in emacs/python-mode.
> 
W. Watson wrote:
 > Thanks, but no thanks. The learning curve is way too steep.

There are two good editors for writing code -- vim and emacs.
If you write more than a few lines of code a year you should learn
one of them. Time spent doing it will pay for itself *very* quickly.

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


Re: An Editor that Skips to the End of a Def

2007-09-24 Thread alex
W. Watson wrote:
> Well, you may. Unfortunately, there are many NGs that do the opposite.
> 
> Bruno Desthuilliers wrote:
>> W. Watson a écrit :
>>> How about in the case of MS Win?
>>>
>>> Ben Finney wrote:

 (Please don't top-post. Instead, reply below each point to which
 you're responding, removing quoted text irrelevant to your response.)

>>
>> Wayne, may I second Ben on his suggestion to stop top-posting ?
> 

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

Re: Match 2 words in a line of file

2007-01-20 Thread Alex


egc> how do i write a regexp for this.. or better yet shd i even be using
egc> regexp or is there a better way to do this
"A team of engineers were faced with a problem; they decided to handle
it with regular expressions. Now they had two problems"


Regular expressions are not always the best solution. Others have
pointed out how it can work with "if word in line", this approach will
do if you're dealing with simple cases.


Take a look at this discussion, it is very informative:
http://blogs.msdn.com/oldnewthing/archive/2006/05/22/603788.aspx

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


How to organise classes and modules

2006-05-15 Thread Alex
Hi, this is my first mail to the list so please correct me if Ive done
anything wrong.

What Im trying to figure out is a good way to organise my code. One
class per .py file is a system I like, keeps stuff apart. If I do
that, I usually name the .py file to the same as the class in it.

File: Foo.py
***
class Foo:
 def __init__(self):
  pass
 def bar(self):
  print 'hello world'



Now, in my other module, I want to include this class. I tried these two ways:

>>> import Foo
>>> Foo.Foo.bar()
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

Some unbound method error. Have I missunderstood something or am I on
the right track here?

I did this to, almost the same thing:

>>> from Foo import Foo
>>> Foo.bar()
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

One thing that I tried that worked ok was this:

>>> import Foo
>>> instance=Foo.Foo()
>>> instance.bar()
hello world

But in my opinion, this is very ugly. Especially if the class names
are long, like my module/class TileDataBaseManager. But is this the
"right" way in python?

Another (ugly) way that Ive considered is the following. Break it out
of the class, save the functions in a file alone, import the file and
treat it like a class:

File: Foo2.py
***
def bar(self):
 print 'hello world'



>>> import Foo2
>>> Foo2.bar()
hello world

Very clean from the outside. I would like something like this. But,
here, I loose the __init__ function. I have to call it manually that
is, which s not good. Also, maybe the biggest drawback, its no longer
in a class. Maybe its not that important in python but from what Ive
learned (in c++) object orientation is something to strive for.

So, to sum it up, I have one class in one file, both with the same
name. How do I store/import/handle it in a nice, clean and python-like
manner?

Thank you very much in advance.
/ Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to organise classes and modules

2006-05-15 Thread Alex
On 5/15/06, bruno at modulix <[EMAIL PROTECTED]> wrote:
> Alex wrote:
> > Hi, this is my first mail to the list so please correct me if Ive done
> > anything wrong.
> >
> > What Im trying to figure out is a good way to organise my code. One
> > class per .py file is a system I like, keeps stuff apart. If I do
> > that, I usually name the .py file to the same as the class in it.
>
> First point is that Python doesn't force you to put everything in
> classes - if you just need a function, well, make it a function !-)
>
> Also, the common pattern is to put closely related
> classes/functions/constants in a same module, and closely related
> modules in the same package. Since Python uses a "one file == one
> module" scheme, the Javaish "one class per file" idiom leads to overly
> complicated imports. And the most common naming scheme for modules is
> 'alllowercase'.
>
>
>
> > File: Foo.py
> > ***
> > class Foo:
> > def __init__(self):
> >  pass
> > def bar(self):
> >  print 'hello world'
> >
> > 
> >
> > Now, in my other module, I want to include this class. I tried these two
> > ways:
> >
> >>>> import Foo
> >>>> Foo.Foo.bar()
> >
> > Traceback (most recent call last):
> >  File "", line 1, in ?
> > TypeError: unbound method bar() must be called with Foo instance as
> > first argument (got nothing instead)
> >
> > Some unbound method error. Have I missunderstood something
>
> Yes:
> 1/ you usually need to instanciate the class to call an instance method
> 1/ in this case, bar doesn't need to be a method, since it doesn't
> depend on the instance it's called on - a plain old function would be a
> better fit.
>
> > or am I on
> > the right track here?
> >
> > I did this to, almost the same thing:
> >
> >>>> from Foo import Foo
> >>>> Foo.bar()
> >
> > Traceback (most recent call last):
> >  File "", line 1, in ?
> > TypeError: unbound method bar() must be called with Foo instance as
> > first argument (got nothing instead)
> >
> > One thing that I tried that worked ok was this:
> >
> >>>> import Foo
> >>>> instance=Foo.Foo()
> >>>> instance.bar()
> >
> > hello world
> >
> > But in my opinion, this is very ugly.
>
> Nope, it's just OO at work.
>
> > Especially if the class names
> > are long, like my module/class TileDataBaseManager. But is this the
> > "right" way in python?
>
> If you want to import a class from a module and create an instance of
> that class, yes.
>
> > Another (ugly) way that Ive considered is the following. Break it out
> > of the class,
>
> Which would be a sensible thing to do given the current implementation
> of bar().
>
> > save the functions in a file alone,
>
> Nothing prevent you from putting many functions in a same module, you
> know...
>
> > import the file
>
> s/file/module/
>
> > and
> > treat it like a class:
>
> ???
>
> > File: Foo2.py
> > ***
> > def bar(self):
> > print 'hello world'
> >
> > 
> >
> >>>> import Foo2
> >>>> Foo2.bar()
> >
> > hello world
>
> You don't "treat it like a class", you're just using the normal
> namespace resolution mechanism. Modules are namespaces, classes are
> namespaces, objects (class instances) are namespaces, and the dot is the
>  lookup operator (ie : somenamespacename.somename means 'retrieve what's
> actually bound to name 'somename' in namespace 'somenamespacename').
>
> > Very clean from the outside. I would like something like this. But,
> > here, I loose the __init__ function.
>
> Which in the given implementation is just doing nothing.
>
> Ok, I understand that this is just example code. The rule here is:
> - if you need per-instance state management, use a class (that you of
> course need to instanciate - else you can't have per-instance state !-)
> - if you don't need per-instance state management, use a plain function.
>
> > I have to call it manually that
> > is, which s not good. Also, maybe the biggest drawback, its no longer
> > in a class.
>
> def MyFunc():
>   pass
>
> print MyFunc.__class__.__name__
>
> Python function's are i

Edit Python code programmatically

2008-02-09 Thread Alex
Which library could you recommend to perform simple editing of Python 
code (from Python program)? For example, open *.py file, find specific 
function definition, add another function call inside, find existing 
call and change parameter value, etc.

What I'm trying to implement isn't a real visual programming tool, but 
some code-generation is necessary. For now I think I can generate Python 
syntax manually (like any text file), but it can become more complicated 
in future (like partially implementing code-generation library), plus 
there'll always be possibility of corrupting files and losing data (or 
having to recover valid Python syntax manually) due to coding mistake.

Thanks

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


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Guilherme Polo wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>   
>> Which library could you recommend to perform simple editing of Python
>>  code (from Python program)? For example, open *.py file, find specific
>>  function definition, add another function call inside, find existing
>>  call and change parameter value, etc.
> You are after inspect, it is included with python.
Yes, I forgot to mention - I'm new to Python. I didn't necessary mention 
3rd party library. Simply such wasn't mentioned in library review and 
tutorials, so I didn't know of it. What's the module's name?
>> What I'm trying to implement isn't a real visual programming tool, but
>>  some code-generation is necessary. For now I think I can generate Python
>>  syntax manually (like any text file), but it can become more complicated
>>  in future (like partially implementing code-generation library), plus
>>  there'll always be possibility of corrupting files and losing data (or
>>  having to recover valid Python syntax manually) due to coding mistake.
> Generating code like this is always dangerous. Maybe you could
> generate some other kind of file, then use some library or build one,
> to operator over this file.
No, the code by itself is the goal.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Steven D'Aprano wrote:
> On Sat, 09 Feb 2008 14:38:29 +0300, Alex wrote:
>
>   
>> Which library could you recommend to perform simple editing of Python
>> code (from Python program)? 
>> 
>
> I'm not even sure such a library exists.
>   
Yes they exist, that field is called "code-generation", "generative 
programming" etc.
>
>   
>> For example, open *.py file, find specific
>> function definition, add another function call inside, find existing
>> call and change parameter value, etc.
>> 
>
> Why do you want to do that? I'm not sure what you're trying to 
> accomplish. Code refactoring? I imagine that's probably best done with 
> your text editor: at best, your editor will have dedicated refactoring 
> tools, and at worst, it will have global search and replace.
I don't feel like describing all ideas - it's nothing really intersting 
anyway, just a learning project (to get to know language features), but 
obviously it's not for regular programming - I know text editors can do 
that just fine. Simply in some situation I think instead of generating 
data I'd better generate some code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Guilherme Polo wrote:
> 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>   
>> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >
>>  > > Guilherme Polo wrote:
>>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>
>> 
>>  > >  >> Which library could you recommend to perform simple editing of 
>> Python
>>  > >  >>  code (from Python program)? For example, open *.py file, find 
>> specific
>>  > >  >>  function definition, add another function call inside, find 
>> existing
>>  > >  >>  call and change parameter value, etc.
>>  > >  > You are after inspect, it is included with python.
>>  >
>>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
>>  > >  3rd party library. Simply such wasn't mentioned in library review and
>>  > >  tutorials, so I didn't know of it. What's the module's name?
>>  >
>>
>> 
>>> inspect is a module, inspect is the name. It is not a module for
>>>   
>>  > editing Python code per se, but it will help with the other part.
>>
>>
>> I don't think the OP wants to edit python code *objects*, rather he
>>  wants to edit python *source* code programmatically.  Inspect is not
>>  the tool for this.
>> 
>
> I didn't tell him to use inspect to edit python code, I said it was
> useful for the other part. The other part, as he mentioned on his
> email is: "find specific
> function definition, add another function call inside, find existing
> call".
Sorry but I said "in *.py file", meaning that file isn't executed to 
edit objects in memory. It's instead saved in modified form, possibly to 
be edited by user. Guess it's a common task for visual GUI editors and 
any visual programming tools.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Guilherme Polo wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>   
>> Guilherme Polo wrote:
>>  > 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>>  >
>>  >> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>>  >>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >>  >
>>  >>  > > Guilherme Polo wrote:
>>  >>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >>
>>  >>
>>  >>  > >  >> Which library could you recommend to perform simple editing of 
>> Python
>>  >>  > >  >>  code (from Python program)? For example, open *.py file, find 
>> specific
>>  >>  > >  >>  function definition, add another function call inside, find 
>> existing
>>  >>  > >  >>  call and change parameter value, etc.
>>  >>  > >  > You are after inspect, it is included with python.
>>  >>  >
>>  >>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary 
>> mention
>>  >>  > >  3rd party library. Simply such wasn't mentioned in library review 
>> and
>>  >>  > >  tutorials, so I didn't know of it. What's the module's name?
>>  >>  >
>>  >>
>>  >>
>>  >>> inspect is a module, inspect is the name. It is not a module for
>>  >>>
>>  >>  > editing Python code per se, but it will help with the other part.
>>  >>
>>  >>
>>  >> I don't think the OP wants to edit python code *objects*, rather he
>>  >>  wants to edit python *source* code programmatically.  Inspect is not
>>  >>  the tool for this.
>>  >>
>>  >
>>  > I didn't tell him to use inspect to edit python code, I said it was
>>  > useful for the other part. The other part, as he mentioned on his
>>  > email is: "find specific
>>  > function definition, add another function call inside, find existing
>>  > call".
>>
>> Sorry but I said "in *.py file", meaning that file isn't executed to
>>  edit objects in memory. It's instead saved in modified form, possibly to
>>  be edited by user. Guess it's a common task for visual GUI editors and
>>  any visual programming tools.
>>
>> 
>
> By visual GUI editors I will assume GUI designer tools. These tend to
> not generate  direct python code, glade-2 used to but glade-3 doesn't
> anymore. Other tools like XRCed generates xrc, wxGlade has an option
> to generate .xrc too, Qt Designer generates .ui and .qrc, Glade-3
> generates .glade file, Gazpacho generates .glade, or a gazpacho format
> or gtkbuilder format. In all these, it is recommended to use something
> to work with the generated code, like libglade, wx.xrc and PyQt has
> tools to convert .ui and .qrc to python modules but they don't affect
> your custom code (it is also possible to load .ui using uic module).
>
> With this we come back to my first email, where I told you it is not
> recommended to generate direct python code, especially if you are
> doing the kind of things you just mentioned. If you still want to
> generate python code, from some other source, inspect can be helpful.
Thank you for detailed reply... but I still want to generate python 
code. By the way, Python Package Index references code generators able 
to generate Python code 
(http://pypi.python.org/pypi?:action=browse&show=all&c=409), which I'll 
inspect later (especially their ability to *edit* code). Inspect might 
be useful too.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get current module object

2008-02-17 Thread Alex
Can I get reference to module object of current module (from which the 
code is currently executed)? I know __import__('filename') should 
probably do that, but the call contains redundant information (filename, 
which needs to be updated), and it'll perform unnecessary search in 
loaded modules list.

It shouldn't be a real problem (filename can probably be extracted from 
the traceback anyway), but I wonder if there is more direct and less 
verbose way.

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


Re: How to get current module object

2008-02-18 Thread Alex
Gabriel Genellina wrote:
> En Sun, 17 Feb 2008 16:25:44 -0200, Alex <[EMAIL PROTECTED]> escribi�:
>   
>> Can I get reference to module object of current module (from which the
>> code is currently executed)? I know __import__('filename') should
>> probably do that, but the call contains redundant information (filename,
>> which needs to be updated), and it'll perform unnecessary search in
>> loaded modules list.
>>
>> It shouldn't be a real problem (filename can probably be extracted from
>> the traceback anyway), but I wonder if there is more direct and less
>> verbose way.
>> 
> sys.modules[__name__]
>   
That's what I've been searching for, thanks. By the way, I know it might 
be trivial question... but function and class namespaces have __name__ 
attribute too. Why is global one always returned?
> Why do you want to get the module object? globals() returns the module  
> namespace, its __dict__, perhaps its only useful attribute...
To pass it as a parameter to a function (in another module), so it can 
work with several modules ("plugins" for main program) in a similar manner.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to get current module object

2008-02-18 Thread Alex
Alex wrote:
> function and class namespaces have __name__ attribute too
I was wrong - these were function and class _objects'_ namespaces
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get current module object

2008-02-18 Thread Alex
Gabriel Genellina wrote:
> En Mon, 18 Feb 2008 14:49:02 -0200, Alex <[EMAIL PROTECTED]> escribió:
>> That's what I've been searching for, thanks. By the way, I know it might
>> be trivial question... but function and class namespaces have __name__
>> attribute too. Why is global one always returned?
> I don't understand the question (even with the later correction  
> namespaces->objects)
There's no question anymore, I just failed to distinguish function local 
variables (which don't include __name__) and function object's attributes
>>> Why do you want to get the module object? globals() returns the module
>>> namespace, its __dict__, perhaps its only useful attribute...
>>>   
>> To pass it as a parameter to a function (in another module), so it can
>> work with several modules ("plugins" for main program) in a similar  
>> manner.
>> 
>
> The function could receive a namespace to work with (a dictionary). Then  
> you just call it with globals() == the namespace of the calling module.
Yes, but access to module seems more verbose:

 >>> module_dict['x']()
xxx

Instead of just:

 >>> module.x()
xxx
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there Python equivalent to Perl BEGIN{} block?

2008-03-12 Thread Alex
Hi all,

The subject says pretty much all, i would very appreciate an answer. I
tried to search the various forums and groups, but didn't find any
specific answer...

Thanks,
Alex.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there Python equivalent to Perl BEGIN{} block?

2008-03-13 Thread Alex
On Mar 12, 8:48 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Mar 12, 2:19 pm, Alex <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
>
> > The subject says pretty much all, i would very appreciate an answer. I
> > tried to search the various forums and groups, but didn't find any
> > specific answer...
>
> Python technically has no equivalent: you can't run code at compile
> time.  However, the BEGIN block in Perl seems to have been added to
> work around some of Perl's nonlinear order of execution.  Normally in
> Python you don't need a BEGIN block: just put the code at the top of
> you script/module and it will exectute before anything else.
>
> Want to tell us what you need it for?  Perhaps we can suggest a way of
> doing it that's appropriate in Python.
>
> Carl Banks

Hi,

First of all thanks all for answering!

I have some environment check and setup in the beginning of the code.
I would like to move it to the end of the script. But I want it to
execute first, so the script will exit if the environment is not
configured properly.

Thanks,
Alex.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there Python equivalent to Perl BEGIN{} block?

2008-03-14 Thread Alex
On Mar 13, 6:21 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Mar 13, 7:02 am, Bruno Desthuilliers 
>
>
> [EMAIL PROTECTED]> wrote:
> > Alex a écrit :
> > (sni)
>
> > > First of all thanks all for answering!
>
> > > I have some environment check and setup in the beginning of the code.
> > > I would like to move it to the end of the script.
>
> > Why ? (if I may ask...)
>

Sure, because of a readability (similar to function declarations in
C).

> > > But I want it to
> > > execute first, so the script will exit if the environment is not
> > > configured properly.
>
> > If you want some code to execute first when the script/module is loaded,
> > then keep this code where it belongs : at the beginning of the script.
>
> I concur with Bruno's recommendation: stuff you want to do first
> should come first in the script.  Things like BEGIN blocks hurt
> readability because you can't identify where execution begins without
> reading the whole file.
>
> Having said that, one thing that often happens in Python scripts is
> that all the functions are defined first, then the script logic
> follows.  So you could put the meat of your script in a function, then
> the "BEGIN" stuff after that functions:
>
> def run_script():
> #
> # script contained in this long function
> #
>
> # Then test preconditions here...
> if os.environ["HELLO"] != "WORLD":
> sys.exit(2)
>
> # Then call the run_script functions
> run_script()
>
> But having said THAT, I don't recommend you do that with
> preconditions.  If the script has a quick early exit scenario, you
> really ought to put that near the top, before the function
> definitions, to clearly show to a human reader what is necessary to
> run the script.
>
> Carl Banks

Hi,

Maybe i was a little bit unclear... I meant that i wanted to do
something like this:

#!usr/bin/env python

check_env()

from subprocess import *

class MyClass:
   # Class definition

def check_env():
   # Code

if __name__ == "__main__":
   # Script logic

The thing is, as i saw, that Python doesn't recognize the
"check_env()" function before it reaches the "def" statement.

I need the check to be done before the subprocess import, because our
customers use different Python versions, some of them do not have
subprocess module. So i want to exit if i see that Python version
being used doesn't have that module.

The solution to that problem with what you suggested could be wrapping
the subprocess import with function, am i correct?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there Python equivalent to Perl BEGIN{} block?

2008-03-15 Thread Alex
On Mar 15, 5:42 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Mar 14, 6:37 pm, Alex <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 13, 6:21 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 13, 7:02 am, Bruno Desthuilliers 
> > > [EMAIL PROTECTED]> wrote:
> > > > Alex a écrit :
> > > > (sni)
>
> > > > > First of all thanks all for answering!
>
> > > > > I have some environment check and setup in the beginning of the code.
> > > > > I would like to move it to the end of the script.
>
> > > > Why ? (if I may ask...)
>
> > Sure, because of a readability (similar to function declarations in
> > C).
>
> > > > > But I want it to
> > > > > execute first, so the script will exit if the environment is not
> > > > > configured properly.
>
> > > > If you want some code to execute first when the script/module is loaded,
> > > > then keep this code where it belongs : at the beginning of the script.
>
> > > I concur with Bruno's recommendation: stuff you want to do first
> > > should come first in the script.  Things like BEGIN blocks hurt
> > > readability because you can't identify where execution begins without
> > > reading the whole file.
>
> > > Having said that, one thing that often happens in Python scripts is
> > > that all the functions are defined first, then the script logic
> > > follows.  So you could put the meat of your script in a function, then
> > > the "BEGIN" stuff after that functions:
>
> > > def run_script():
> > > #
> > > # script contained in this long function
> > > #
>
> > > # Then test preconditions here...
> > > if os.environ["HELLO"] != "WORLD":
> > > sys.exit(2)
>
> > > # Then call the run_script functions
> > > run_script()
>
> > > But having said THAT, I don't recommend you do that with
> > > preconditions.  If the script has a quick early exit scenario, you
> > > really ought to put that near the top, before the function
> > > definitions, to clearly show to a human reader what is necessary to
> > > run the script.
>
> > > Carl Banks
>
> > Hi,
>
> > Maybe i was a little bit unclear... I meant that i wanted to do
> > something like this:
>
> > #!usr/bin/env python
>
> > check_env()
>
> > from subprocess import *
>
> > class MyClass:
> ># Class definition
>
> > def check_env():
> ># Code
>
> > if __name__ == "__main__":
> ># Script logic
>
> > The thing is, as i saw, that Python doesn't recognize the
> > "check_env()" function before it reaches the "def" statement.
>
> You could rearrange it like this and it will work:
>
> #!usr/bin/env python
>
> def check_env():
># Code
>
> check_env()
>
> from subprocess import *
>
> class MyClass:
># Class definition
>
> if __name__ == "__main__":
># Script logic
>
> Or, better yet, do what Arnaud Delobelle suggests.
>
> It's not a big deal to move imports down the page a bit, as long as
> you throw in a few clear comments explaning what you're doing and why.
>
> You might also consider putting check_env() in a separate module.
>
> Carl Banks

Hi guys,

Thanks for help! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Which way to access Scintilla

2008-03-16 Thread Alex
There are several ways to use Scintilla in Python, the ones described at 
http://scintilla.sourceforge.net/ScintillaRelated.html are:
-through wxPython
-pyscintilla is the original Python binding for Scintilla's default 
GTK 1.x class. Includes some additional support, such as native 
printing on Windows. The binding is hand-written rather than 
auto-generated from the Scintilla.iface file.

-pygtkscintilla is a Python binding for gtk1.x scintilla that uses 
gtkscintilla instead of the default GTK class.

-pyscintilla2 is a Python binding for GTK 2.x scintilla that uses 
gtkscintilla2.

I'm not using any of the libraries GTK 1.x, GTK 2.x or WxPython for GUI 
(always used Tkinter), but I want to use Scintilla so I wonder which way 
would have less overhead. First, loading of an additional library would 
(I think) slow down startup and operating time of program, plus there 
can be additional complexity of use.

I also want to embed Scintilla in Tkinter-created window (create the 
rest of the GUI in Tkinter), or rather, I want to know if that's 
possible at all. Any suggestions are appreciated.

Thanks

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


ctypes with Compaq Visual Fortran 6.6B *.dll (Windows XP), passing of integer and real values

2009-01-27 Thread alex
Hello everybody
I am mainly a Fortran programmer and beginning to learn Python(2.5)
and OOP programming.
I hope in the end to put a GUI on my existing Fortran code.
Therefore I am also trying to learn Python's "ctypes" library.

Unfortunately the ctypes tutorial does not show simple examples so I
set up a simple fortran module
and Python script to test.
But even with passing Integer and Real values I get the right output
but with subsequent error:
ValueError: Procedure probably called with too many arguments (4 bytes
in excess)
The scripts exits then, so the second subroutine call does not happen.


>From reading comp.lang.python and comp.lang.fortran I understood that
passing character strings
may not be simple but I could not find any solution to my problem.
Maybe somebody can help me with solving it?


The Fortran module (footst.f90):

!
  module footst
!
  implicit none
!
!
!- End of module header

!
!- Execution part of the module

!
!
  contains
!- Define procedures contained in this module.
!
!---
!
!
  subroutine foo1(int_tst)
  !DEC$ ATTRIBUTES DLLEXPORT :: foo1
  integer, intent(in):: int_tst
  write(unit=*, fmt="(a)") "Subroutine foo1(int_tst)"
  write(unit=*, fmt="(a, i4)") "a= ", int_tst
  end subroutine foo1
!
!
  subroutine foo2(real_tst)
  !DEC$ ATTRIBUTES DLLEXPORT :: foo2
  real, intent(in):: real_tst
  write(unit=*, fmt="(a)") "Subroutine foo2(real_tst)"
  write(unit=*, fmt="(a, f6.2)") "a= ", real_tst
  end subroutine foo2
!
!
  end module footst
!


The Python script (footst.py):

#!/usr/bin/env python
#
#
from ctypes import *
#
#
if __name__ == '__main__':
tst=windll.LoadLibrary("f:\\scratch\\test2\\footst.dll")
#tst.restype=None
#tst.argtypes=(c_int)
x=c_int(999)
y=c_float(10.5)
tst.footst_mp_foo1_(byref(x))
#Passing Real values commented out, but leads to the same error
#tst.footst_mp_foo2_(byref(y))
#
main()
#
#


The DOS prompt output:

F:\Scratch\Test2>df /dll /iface=(cref,nomixed_str_len_arg)/
names:lowercase /assume:underscore footst.f90
Compaq Visual Fortran Optimizing Compiler Version 6.6 (Update B)
Copyright 2001 Compaq Computer Corp. All rights reserved.

footst.f90
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

/entry:_dllmaincrtstar...@12
/ignore:505
/debugtype:cv
/debug:minimal
/pdb:none
F:\SysTemp\obj5B.tmp
dfordll.lib
msvcrt.lib
dfconsol.lib
dfport.lib
kernel32.lib
/out:footst.dll
/dll
   Creating library footst.lib and object footst.exp


F:\Scratch\Test2>dumpbin /exports footst.dll
Microsoft (R) COFF Binary File Dumper Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.


Dump of file footst.dll

File Type: DLL

  Section contains the following exports for footst.dll

   0 characteristics
497F5CC3 time date stamp Tue Jan 27 20:13:07 2009
0.00 version
   1 ordinal base
   2 number of functions
   2 number of names

ordinal hint RVA  name

  10 1000 footst_mp_foo1_
  21 10A6 footst_mp_foo2_

  Summary

1000 .data
1000 .rdata
1000 .reloc
1000 .text


F:\Scratch\Test2>footst.py
Subroutine foo1(int_tst)
a=  999
Traceback (most recent call last):
  File "F:\Scratch\Test2\footst.py", line 13, in 
tst.footst_mp_foo1_(byref(x))
ValueError: Procedure probably called with too many arguments (4 bytes
in excess)

F:\Scratch\Test2>
--
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes with Compaq Visual Fortran 6.6B *.dll (Windows XP), passing of integer and real values

2009-01-28 Thread alex
Jon
Thank you for your answer. I tried it with no success.

However I tried with
tst=cdll.LoadLibrary("f:\\scratch\\test2\\footst.dll") instead of
tst=windll.LoadLibrary("f:\\scratch\\test2\\footst.dll")

and it runs now with no error message, I can't figure for now why, but
it's great! This is motivating for going ahead.

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


Re: ctypes with Compaq Visual Fortran 6.6B *.dll (Windows XP), passing of integer and real values

2009-01-29 Thread alex
Duncan
Thank you for your explanation of the relationship between calling
convention and stack management.
I will try to understand better this topic in the CVF and ctypes
documentation (not so easy).

Regards Alex

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


Re: Searching Google?

2009-02-18 Thread Alex
On Feb 18, 1:36 pm, Johannes Bauer  wrote:
> Curt Hash schrieb:
>
> > You just need to change your User-Agent so that Google doesn't know a
> > Python script is making the request:
>
> Why would Google not send a response if the User-Agent header field is
> not a recognized browser?

Because making automated queries to Google is against its TOS so
Google block any client that doesn't seam to be human.
On the other hands Google's API does not return the same exact result
as in a normal web query.
My suggestion is: set a browser like User agent and accept gzipped
content to be as friendly as possible and don't do too many queries in
a small time span.
Parsing Google result page with Beautifulsoup is a piece of cake.

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


How to read stdout from subprocess as it is being produced

2008-12-19 Thread Alex
Hi,

I have a Pyhon GUI application that launches subprocess.
I would like to read the subprocess' stdout as it is being produced
(show it in GUI), without hanging the GUI.

I guess threading will solve the no-hanging issue, but as far as I
searched for now, I've only seen how to read the stdout after
subprocess is finished.

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


Re: How to read stdout from subprocess as it is being produced

2008-12-21 Thread Alex
On Dec 19, 5:09 pm, Albert Hopkins  wrote:
> On Fri, 2008-12-19 at 06:34 -0800, Alex wrote:
> > Hi,
>
> > I have a Pyhon GUI application that launches subprocess.
> > I would like to read the subprocess' stdout as it is being produced
> > (show it in GUI), without hanging the GUI.
>
> > I guess threading will solve the no-hanging issue, but as far as I
> > searched for now, I've only seen how to read the stdout after
> > subprocess is finished.
>
> I believe that's going to be highly dependent upon the particular, yet
> unspecified, GUI toolkit/API.
>
> There are probably a few ways. You're toolkit might native support for
> this, but one way would be to use a timer.  Here is some pseudocode:
>
> class MyWindow(toolkit.Window):
>     def __init__(self, ...):
>         ...
>         self.subprocess = subprocess.Popen(..., stdout=subprocess.PIPE)
>         self.running = True
>
>         ...
>         toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout)
>
>     def read_stdout(self, ...):
>         if not self.running:
>             return
>         char = self.subprocess.stdout.read(1)
>         if char == '':
>             self.running = False
>             return
>         self.update_something(char)
>         toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout)

Hi,

Thanks a lot for the tip!

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


Re: Web crawler on python

2008-10-28 Thread Alex
On Oct 26, 9:54 pm, sonich <[EMAIL PROTECTED]> wrote:
> I need simple web crawler,
> I found Ruya, but it's seems not currently maintained.
> Does anybody know good web crawler on python or with python interface?

You should try Orchid http://pypi.python.org/pypi/Orchid/1.1
 or you can have a look at my project on launchpad
https://code.launchpad.net/~esaurito/jazz-crawler/experimental.
It's a single site crawler but you can easily modified it.

Bye.

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


TextCtrl fully expanding at program start

2009-02-27 Thread alex
Hi all
I have a gridsizer consisting of two vertically stacked panels, one
with a StaticBox and the other with a TextCtrl.
I would like that the TextCtrl expands at program start fully to the
allocated panel size (lower panel of gridSizer).
Instead of like now, fully expanding in the width but not exapnding in
the height direction (two lines high).

I am currently running in circles so maybe can anybody help me?
See below for my best effort (OS WinXP, Python 2.5).

Thank you, regards Alex



import wx

class Frame(wx.Frame):
def __init__(self, title, pos, size):
wx.Frame.__init__(self, None, -1, title, pos, size)

self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour(220, 220, 220))

box1 = wx.StaticBox(self.panel, -1, "Program Preferences")
box2 = wx.TextCtrl(self.panel, -1, size=(-1,-1),style =
wx.TE_MULTILINE|wx.TE_READONLY)


gs = wx.GridSizer(2, 1, 0, 0)
windowOneSizer = wx.BoxSizer(wx.VERTICAL)
windowTwoSizer = wx.BoxSizer(wx.VERTICAL)

windowOneSizer.Add(box1, 0, wx.ALL|wx.EXPAND, 0)
windowTwoSizer.Add(box2, 0, wx.ALL|wx.EXPAND, 0)

gs.Add(windowOneSizer, 0, wx.ALL|wx.EXPAND, 2)
gs.Add(windowTwoSizer, 0, wx.ALL|wx.EXPAND, 2)

self.panel.SetSizer(gs)
self.Centre()
self.Show(True)


class App(wx.App):
def OnInit(self):
frame = Frame("My Frame", (100, 100), (400, 250))
frame.Show()
self.SetTopWindow(frame)
return True
#
#
if __name__ == '__main__':
#
app = App()
app.MainLoop()
#
#

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


Re: TextCtrl fully expanding at program start

2009-02-27 Thread alex
On 27 Feb., 15:14, Vlastimil Brom  wrote:
> 2009/2/27 alex :
>
> > Hi all
> > I have a gridsizer consisting of two vertically stacked panels, one
> > with a StaticBox and the other with a TextCtrl.
> > I would like that the TextCtrl expands at program start fully to the
> > allocated panel size (lower panel of gridSizer).
> > Instead of like now, fully expanding in the width but not exapnding in
> > the height direction (two lines high).
> ...
>
> Hi,
> changing the proportion for adding the textctrl into the sizer to 1
> should expand it to the lower half of the panel.
>
> try changing:
>         windowTwoSizer.Add(box2, 0, wx.ALL|wx.EXPAND, 0)
> TO:
>         windowTwoSizer.Add(box2, 1, wx.ALL|wx.EXPAND, 0)
>
> Seehttp://www.wxpython.org/docs/api/wx.Sizer-class.html#Add
> for the options for adding into the sizer.
>
> hth
>    vbr

Hi Vlastimil
I must have overlooked it. Too much reading and trying...
Thank you, it works perfect.

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


Accessing wx.TextCtrl after refactoring

2009-03-27 Thread alex
Hi all
I am working on a Dialog window for a gui in wxPython and started
refactoring it, below code is a simplified version of it.
"def createInput1" should create a static text, a button and a
textcontrol using the information in "def box1Labels".
"def makeStaticBox1" then arranges all widgets in staticbox1.

My problem is that it works fine for the static text and the button
label but I cant "rename" self.txtctrl that it
becomes self.txtctrl_inpath or self.txtctrl_outpath for getting the
path from either "def BrowseInDlg" or "def BrowseOutDlg".

I must admit that I am still a beginner but searching through my books
does not get me further. I like the idea of refactoring for
"automatising" widgets creation instead of hardcoding each widgetID.
But I am completely stuck here. Maybe can somebody help?

Coming from the Fortran world my programming style may be quite
"fortranic" instead of being "pythonic" but I am trying to improve and
enjoy what I learned so far...

Thanks Alex



#
#
#!/usr/bin/env python
#
#
"""Add Python docs string"""
import wx
import os
#
#
class Dialog1(wx.Dialog):
def __init__(self):
wx.Dialog.__init__(self, None, -1, "Test", size=(500, 600))
self.makeStaticBox1()
self.makeSizer()


def box1Labels(self):
return (("Label1:", "Browse", self.BrowseInDlg,
txtctrl_inpath),
("Label2:", "Browse", self.BrowseOutDlg,
txtctrl_outpath))


def makeStaticBox1(self):
box1 = wx.StaticBox(self, -1, "Box1")
pathFlexGridSizer = wx.FlexGridSizer(4, 0, 0, 0)
pathFlexGridSizer.AddGrowableCol(1)

for label, pth_btn_label, btn_funct, txtctrl_path in
self.box1Labels():
self.createInput1(label, pth_btn_label, txtctrl_path)

pathFlexGridSizer.Add(self.stattxt, 0,
wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.BOTTOM, 2)
pathFlexGridSizer.Add((10, 10))
pathFlexGridSizer.Add(self.pth_Btn, 0, wx.ALIGN_LEFT)
pathFlexGridSizer.Add(self.txtctrl, 0, wx.ALIGN_RIGHT|
wx.TOP|wx.BOTTOM, 2)
self.Bind(wx.EVT_BUTTON, btn_funct, self.pth_Btn)


self.path_sizer = wx.StaticBoxSizer(box1, wx.VERTICAL)
self.path_sizer.Add(pathFlexGridSizer, 2, wx.ALL|wx.EXPAND, 0)


def createInput1(self, label, pth_btn_label, txtctrl_path):
self.stattxt=wx.StaticText(self, -1, label)
self.pth_Btn = wx.Button(self, -1, pth_btn_label)
self.txtctrl=wx.TextCtrl(self, -1, "", size=(300, -1))




def makeSizer(self):
GridSizer = wx.BoxSizer(wx.VERTICAL)
GridSizer.Add(self.path_sizer, 1, wx.ALL|wx.EXPAND, 2)


self.SetSizer(GridSizer)
self.Fit()
self.Centre()
self.Show(True)


def BrowseInDlg(self, event):
#
dialog = wx.DirDialog(None, "Choose directory:",
style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
inpath=dialog.GetPath()
self.txtctrl_inpath.SetValue(inpath)
print inpath
dialog.Destroy()


def BrowseOutDlg(self, event):
#
dialog = wx.DirDialog(None, "Choose directory:",
style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
outpath=dialog.GetPath()
self.txtctrl_outpath.SetValue(outpath)
print outpath
dialog.Destroy()




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


Re: Accessing wx.TextCtrl after refactoring

2009-03-28 Thread alex
Rhodri
thank you very much for your answer.
I had read about setattr but the useage was not completely clear to
me. Now I will study it again.
I inserted it in "def createInput1"


def createInput1(self, label, pth_btn_label, txtctrl_path):
self.stattxt = wx.StaticText(self, -1, label)
self.pth_Btn = wx.Button(self, -1, pth_btn_label)
self.txtctrl = wx.TextCtrl(self, -1, "", size=(300, -1))
setattr(self, self.txtctrl_path, self.txtctrl)

Unfortunately I get the following error

  File "C:\Temp\Test\pydlg.py", line 22, in box1Labels
return (("Input Path:", "Browse", self.BrowseInDlg,
txtctrl_inpath),
NameError: global name 'txtctrl_inpath' is not defined

I suppose that this has to do with the variables in my tuple or the
scope of the variables but for the moment I can't really figure out
what the problem is.

Maybe you can give me a hint. Again thank you.
Alex


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


Accessing items in nested tuples

2009-04-21 Thread alex
Hello everybody
I am able to access the data in a tuple via a for loop (see example
below).


#!/usr/bin/env python

class Test():
def Data(self):
return ("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh")
#return (("aa", ("bb", "cc", "dd")), ("ee", ("ff", "gg",
"hh")), ("ii", ("jj", "kk", "ll")))

def Process(self):
for eachData in self.Data():
print "Printing %s" % eachData


def main():
print "Start processing data"
prtData=Test()
prtData.Process()
print "Stop processing data"


if __name__ == '__main__':
main()


However I do not find out how to access data items in a nested tuple
of
the type (("aa", ("bb", "cc", "dd")), ("ee", ("ff", "gg", "hh")),...).
In fact I am trying to refactor a simple GUI basing on an example
in "wxPython In Action", "Listing 5.5 A refactored example" where the
menues
are described in the way


def menuData(self):
return (("&File",
("&Open", "Open in status bar", self.OnOpen),
("&Quit", "Quit", self.OnCloseWindow)),
("&Edit",
("&Copy", "Copy", self.OnCopy),
("C&ut", "Cut", self.OnCut),
 ...)))

etc...


But I can not get the example running and I can't reprogram the
example to get it running for my case.

In IDLE I can print the individual tuples but not the items within.

IDLE 1.2.1
>>> data=(("aa", ("bb", "cc", "dd")), ("ee", ("ff", "gg", "hh")), ("ii", ("jj", 
>>> "kk", "ll")))
>>> print data[0]
('aa', ('bb', 'cc', 'dd'))
>>> print data[1]
('ee', ('ff', 'gg', 'hh'))
>>> etc...


I would like to be able to access the dataitem "aa" or "bb", "cc",
"dd" individualy.
For sure I am most probably missing something which is evident, maybe
can anybody help?
Thanks Alex

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


Re: Accessing items in nested tuples

2009-04-21 Thread alex
Tim and Mensanator
Thank you very much, this will get me further.
I can not recall having seen this in my books...
I am still getting my grips with Python and OOP.
Regards Alex
--
http://mail.python.org/mailman/listinfo/python-list


wxPython menu creation refactoring

2009-04-28 Thread alex
Hello everybody
I am still trying to refactor a simple GUI basing on an example
in "wxPython In Action", "Listing 5.5 A refactored example" where the
menue creation is "automatized".
I understand the problem (each second for loop in "def createMenuData
(self)"
creates a distinct menu) but I tried now for some evenings and do not
get to
any possible solution.
I am still learning Python and hope to use it as a front end for
my Fortran programs (subprocess and ctypes work very well...)
with the aim of increasing the Python part (text parsing) in the
future.
The following code shows the problem and works out of the DOS box.
Any help would be greatly apreciated.

Alex


#
#!/usr/bin/env python
#
"""Add Python docs string"""
import wx
#
#
class Frame(wx.Frame):
def __init__(self, title, pos, size):
wx.Frame.__init__(self, None, -1, title, pos, size)
#
self.createPanel()
self.createMenuData()


def menuData(self):
return (("&File",
("&Open", self.OnOpen),
("&Restart", self.OnRestart),
("&Exit", self.OnExit)),
("&About",
("&About", self.OnAbout)))


def createMenuData(self):
menuBar = wx.MenuBar()
for eachMenuData in self.menuData():
menuLabel = eachMenuData[0]
for eachLabel, eachHandler in eachMenuData[1:]:
menuBar.Append(self.createMenu(eachLabel,
eachHandler), menuLabel)
self.SetMenuBar(menuBar)


def createMenu(self, itemLabel, itemHandler):
menu = wx.Menu()
menuItem = menu.Append(wx.NewId(), itemLabel)
self.Bind(wx.EVT_MENU, itemHandler, menuItem)
return menu


def createPanel(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.SystemSettings_GetColour
(wx.SYS_COLOUR_3DFACE))
StatusBar = self.CreateStatusBar()

self.Centre()
self.Show(True)


def OnExit(self, event):
self.Close()

def OnOpen(self, event):
pass

def OnRestart(self, event):
pass

def OnAbout(self, event):
pass


class App(wx.App):
def OnInit(self):
frame = Frame("Gui Frame", (100, 100), (600, 450))
frame.Show()
self.SetTopWindow(frame)
return True
#
#
if __name__ == '__main__':
#
app = App()
app.MainLoop()
#
#
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython menu creation refactoring

2009-04-30 Thread alex
Good evening Nick
Thank you for answer I will study your code and learn from it.
I subscribed to the wxPython users mailing list which is for my actual
questions probably the more accurate place.
But I always apreciate that when I post even a probably simple
question I always get an answer from this group.
Thank you
Alex
--
http://mail.python.org/mailman/listinfo/python-list


Help on thread pool

2008-05-17 Thread Alex
Hi all.

In order to understand the concept of threading pool in python I'm
working on a simple single-site web crawler.
I would like to stop the program when the threading pool have
downloaded all internal links from a web site, but now my program keep
waiting forever even if there are no more links to download.

Here's my code, I appreciate any comments, I'm programming just for
fun and learning ;-)

Thanks in advance.

from BeautifulSoup import BeautifulSoup
import urllib
from pprint import pprint
import string
from urlparse import urlparse
import sys
from threading import Thread
import time
from Queue import Queue

#dirty hack: set default encoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8')

opener = urllib.FancyURLopener({})

class Crawler:

def __init__(self):
"""
Constructor
"""
self.missed = 0
self.url_list = []
self.urls_queue = Queue()
self.num_threads = 5

self._create_threads()

def get_internal_links(self,url):
"""
Get all internal links from a web page and feed the queue
"""
self.url = url
url_netloc = urlparse(self.url).netloc
print "Downloading... ", self.url
time.sleep(5)
try:
p = opener.open(self.url)
#print p.info()
except IOError:
print "error connecting to ", self.url
print "wait..."
time.sleep(5)
print "retry..."
try:
p = urllib.urlopen(self.url)
except IOError:
  self.missed = self.missed + 1
  return None

html = p.read()
soup = BeautifulSoup(html)
anchors = soup.findAll('a')
links = [ str(anchor['href']) for anchor in anchors]
internal_links = [link for link in links if
(urlparse(link).netloc == url_netloc)]

for link in internal_links:
if link not in self.url_list and link != self.url:
self.url_list.append(link)
self.urls_queue.put(link)
print "Queue size: ", self.urls_queue.qsize()
print "List size: ", str(len(self.url_list))
print "Errors: ", str(self.missed)
self._queue_consumer()


def _queue_consumer(self):
"""
Consume the queue
"""
while True:
url = self.urls_queue.get()
print 'Next url: ', url
self.get_internal_links(url)
self.urls_queue.task_done()


def _create_threads(self):
"""
Set up some threads to fetch pages
"""
for i in range(self.num_threads):
worker = Thread(target=self._queue_consumer, args=())
worker.setDaemon(True)
worker.start()

#-
#

if __name__ == '__main__':

c = Crawler()
c.get_internal_links('http://www.thinkpragmatic.net/')


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


Re: Help on thread pool

2008-05-17 Thread Alex
On May 17, 2:23 pm, Jeff <[EMAIL PROTECTED]> wrote:
> Your worker threads wait around forever because there is no place for
> them to exit.  Queue.get() by default blocks until there is an item in
> the queue available.  You can do something like this to cause the
> worker to quit when the queue is empty.  Just make sure that you fill
> the queue before starting the worker threads.
>
> from Queue import Queue, Empty
>
> # in your worker
> while True:
>   try:
> item = q.get(block=False)
>   except Empty:
> break
>   do_something_with_item()
>   q.task_done()
>
> You can also use a condition variable and a lock or a semaphore to
> signal the worker threads that all work has completed.

Thanks a lot, it works!


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


is there a bug in urlunparse/urlunsplit

2008-05-18 Thread Alex
Hi all.

Is there a bug in the urlunparse/urlunsplit functions?
Look at this fragment (I know is quite silly):

urlunparse(urlparse('www.example.org','http'))
---> 'http:///www.example.org'
   ^

There are too many slashes, isn't it? Is it a known bug or maybe I
missed something...

Alex

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


learning unit testing in python

2008-06-23 Thread Alex
Hi all.

I'd like learn some basic unit testing with python.
I red some articles about different testing framework like unittest or
nose, but I'm a bit confused: what is the best choice? I'm not a
professional developer (I'm a SEO) but I belive that unit testing is a
good and pragmatic way to produce working software, so I'd like to
find something really simple ad straightforward because I don't have
to manage big programming projects.

Thanks in advance,

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


Re: learning unit testing in python

2008-06-23 Thread Alex
On 23 Giu, 21:26, "Josip" <[EMAIL PROTECTED]> wrote:
> > Hi all.
>
> > I'd like learn some basic unit testing with python.
> > I red some articles about different testing framework like unittest or
> > nose, but I'm a bit confused: what is the best choice? I'm not a
> > professional developer (I'm a SEO) but I belive that unit testing is a
> > good and pragmatic way to produce working software, so I'd like to
> > find something really simple ad straightforward because I don't have
> > to manage big programming projects.
>
> > Thanks in advance,
>
> > Alex
>
> Have you checked out doctest?http://docs.python.org/lib/module-doctest.html
> It's the best way to add few tests to function or class, you just add
> them to docstring.
> Unit tests are somewhat demanding as they usualy require creating another
> file just for storing them, but are ofcourse more powerful as well. For
> example,
> unittest module alows you to execute a section of code before or after each
> test
> to initialize values and clean up.
>
> Nose module has few extra features, but it can also run test writen for
> unittest,
> so it's easy to switch if you find standard library module lacking for your
> purpose.

Tanks a lot. I'll the resources you suggest..
--
http://mail.python.org/mailman/listinfo/python-list


random numbers according to user defined distribution ??

2008-08-06 Thread Alex
Hi everybody,

I wonder if it is possible in python to produce random numbers
according to a user defined distribution?
Unfortunately the random module does not contain the distribution I
need :-(

Many thanks

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


Re: random numbers according to user defined distribution ??

2008-08-07 Thread Alex
Thanks for the many answers.

So basically I have to get the inverse of the CDF and use this to
transform my uniformly distributed random numbers. If my desired
distribution is simple I can get an analytical solution for the
inverse, otherwise I have to use numerical methods.

Okay, things are now much clearer.

Many thanks,

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


paging mark hahn

2008-08-27 Thread Alex
hey mark,  wondering if you've still got a net presence out there.   ive
been playing around with the old C prothon code base and wanted to chat with
you about things.

shoot me an email if you are still out there.

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

Re: Ensure only single application instance.

2008-08-29 Thread Alex
SOP is to write the actual PID of the running process into the pidfile, then
check to a) that the pidfile exists, and b) that the process referenced in
the pidfile exists.  if the pidfile exists, but the process does not, take
over the pidfile and carry on.

On Fri, Aug 29, 2008 at 9:51 AM, Heston James <[EMAIL PROTECTED]>wrote:

> Good afternoon all.
>
> I have an application/script which is launched by crontab on a regular
> basis. I need an effective and accurate way to ensure that only one instance
> of the script is running at any one time.
>
> After a short look around the internet I found a couple of examples, such
> as this one (http://code.activestate.com/recipes/474070/), however they
> both seem to be focused on a windows based environment.
>
> Can anyone offer their advice on how best to do this on a linux based
> system?
>
> I have been contemplating the idea of creating a pidfile which is destroyed
> at the end of the script, will this suffice? is it fool proof? My only
> concern with this is that if the script crashes or is stopped halfway
> through processing for whatever reason, I'll be left with a dead pidfile on
> the system and no successive runs will work.
>
> I'm really interested to get your ideas guys, Thanks.
>
> Heston
>
> --
> Get Hotmail on your mobile from Vodafone Try it 
> Now!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Extracing data from webpage

2008-09-11 Thread Alex
On Sep 11, 11:55 am, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:
> Hi,
> I am trying to download data from a webpage. I use mechanize python module.
> Could someone tell me how to set/pass an agent like Mozilla or IE that we do 
> in perl's WWW::Mechanize??
>
> Thanks,
> Srini
>
>       Be the first one to try the new Messenger 9 Beta! Go 
> tohttp://in.messenger.yahoo.com/win/

If you have to parse a web page, this could be also useful:
http://www.crummy.com/software/BeautifulSoup/
--
http://mail.python.org/mailman/listinfo/python-list


understanding list scope

2008-09-21 Thread Alex
Hi all!

I have a problem understanding the behaviour of this snippet:

data_set = ({"param":"a"},{"param":"b"},{"param":"c"})

for i in range(len(data_set)):
ds = data_set[:]
data = ds[i]
if i == 1: data['param'] = "y"
if i == 2: data['param'] = "x"

print data_set


This script print out:
({'param': 'a'}, {'param': 'y'}, {'param': 'x'})

Why? I'm coping data_set in ds so why data_set is changed?

Thanks in advance.

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


  1   2   3   4   5   6   7   8   9   10   >