Re: how to write a C-style for loop?

2006-02-15 Thread Tim Roberts
John Salerno <[EMAIL PROTECTED]> wrote:
>
>I assume this is the way for loops are written in C, but if it helps to 
>be specific, I'm referring to C# for loops. The Python for loop seems to 
>be the same (or similar) to C#'s foreach loop:
>
>foreach int i in X
>
>But how would you write a C# for loop in Python? Do you rework a while 
>loop, or use the range() function?
>
>Here's an example:
>
>for (int i = 0; i < 50; i += 5)
>
>How would that go in Python, in the simplest and most efficient way?

  for i in range(0,50,5):
  print i
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Soduku

2006-02-15 Thread Mikael Olofsson
Jonathan Gardner wrote:
> How do you have a 16x16 grid for soduku? Are you using 16 digits? 0-F?
> 
> The one I am using has 9 digits, 9 squares of 9 cells each, or 9x9
> cells.

What alphabet you use is irrelevant. Sudokus has really nothing to do 
with numbers. You can use numbers, as well as letters, fruits, or car 
models. Numbers just happen to be nice to use as alphabet for fairly 
small sudokus. The hobby electronics magazine elektor at

 http://www.elektor-electronics.co.uk/

uses 0-F for their 16x16 sudokus.

You can make sudokus of more or less any size. In the kids department at

 http://www.dailysudoku.co.uk

you can find 4x4 and 6x6 grids. Apart from those and the standard 9x9, I 
have also seen 12x12, 16x16 and 25x25. You could make them 8x8 or 99x99 
if you wish. Those numbers should be non-primes, though, since the 
pattern of sub-blocks breaks if the numbers are primes.

Perhaps I should mention the three-dimensional one (9x9x9) that someone 
showed me at work. That particular one was a bore, since it contained 
too much patterns. Or the two orthogonal ones, where you have two 9x9 
sudokus in one with interrelations...

Finally, dailysudoku also has what they call squiggly sudokus, e.g.

 
http://www.dailysudoku.co.uk/sudoku/squiggly/archive.shtml?year=2006&month=02&day=15

By the way, if I'm not completely mistaken, there are only two 
non-equivalent solutions to the 4x4 grid. The equivalence relations 
taken into account are then the following:

   Permutations of the alphabet.
   Interchanging interchangeable rows or columns.
   Transpose - as in matrix transpose - of the whole grid.

Enough off-topic for now
/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Self-identifying functions and macro-ish behavior

2006-02-15 Thread Duncan Booth
Michael wrote:

> def func2():
> 
> print 
> return True
> 
> I imagine this means things like closures which I'm not familiar with
> (I'm not a CS person).  In this case, each function is part of a class,
> so I imagine I can take a dir() of the class if necessary.

Use the inspect module to find out what you need.

> 
> This leads into my next related question, which is How do I get some
> sort of macro behavior so I don't have to write the same thing over and
> over again, but which is also not neatly rolled up into a function,
> such as combining the return statements with a printing of ?

By rolling it up neatly in a function?

>>> def printcaller():
print inspect.stack()[1][3]
return True

>>> def func1():
return printcaller()

>>> func1()
func1
True

But remember this prints the name under which the function was created, not 
the name of the variable in which it is stored:

>>> func2 = func1
>>> func2()
func1

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


Re: How to *Search* with google from inside my programme and get the search result?

2006-02-15 Thread Fuzzyman

Frank Potter wrote:
> I want to search something by a key word from inside my py script.
> The using google idea comes to my mind first because write a search
> programme from scratch is not so easy.
>
> I want to take advantage of goolge results, but I don't know how.
> To extract the result from html of google can get the result, but it's not
> reliable and stable because the html structure my be changed any time.
>
> Does google supply some webservice to programmers? I did see
> some a tool use google to search and use it's result from the programme very
> well. Its name is "Email catcher&sender 2.10", which can be download
> at http://www.worldminer.com/download.htm. Windows users can take a
> look at it. It supports more than google, but yahoo and some other search
> engines. How does it do it? I really need some hints.

If you'd like a (simple) example of using the google webservice, have a
look at googlerank -
htpp://www.voidspace.org.uk/python/recipebook.shtml#google

In practise I've found the yahoo web services faster, simpler and less
restrictive, so you may want to try that.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: Excel and TrackChanges

2006-02-15 Thread Gerard Flanagan
pierre_py wrote:
> I have a problem with pycom automation with excel.
> If i use the following in my excel_wrapper:
> """
> self.Workbook.Save()
> self.Workbook.HighlightChangesOptions(When=1)
> self.Workbook.ListChangesOnNewSheet = True
> """
> I don't get any history worksheet. If i use 2 (xlAllChanges) or 3
> (xlNotYetReviewed), i get the history worksheet but with all results.
>
> I use Office 2k sp1.
>
> thanks in advance

What does '1' represent?  The first hit in Google for
"HighlightChangesOptions" suggests it may be 'xlSinceMyLastSave', so
maybe there are no changes to show? What happens if you comment out
"self.Workbook.Save()", or move it to below the other two lines?

Gerard

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


Re: Self-identifying functions and macro-ish behavior

2006-02-15 Thread Iain King

[EMAIL PROTECTED] wrote:
> Hi, I was wondering how I may get a python function to know what its
> name is without me having to write it manually?  For example:
>
> def func1():
> 
> print 'func1'
> return True
>
> def func2():
> 
> print 'func2'
> return True
>
> should be more like
> def func1():
> 
> print 
> return True
>
> def func2():
> 
> print 
> return True
>
> I imagine this means things like closures which I'm not familiar with
> (I'm not a CS person).  In this case, each function is part of a class,
> so I imagine I can take a dir() of the class if necessary.

Yeah, I think these are closures (though when I learnt CS we didn't get
taught them).  Try this:

def makeFunction(name):
def func():

print name
return True
return func

func1 = makeFunction('func1')
func2 = makeFunction('func2')

>
> This leads into my next related question, which is How do I get some
> sort of macro behavior so I don't have to write the same thing over and
> over again, but which is also not neatly rolled up into a function,
> such as combining the return statements with a printing of ?

I think I've answered this too?

Iain

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


PyDot problem

2006-02-15 Thread Sbaush
Hi all. I use pydot for drawing nework link.the code is at bottom of mail.i have a png like this attachedIf you look png you can see that 10.0.0.1 and 
10.0.0.2 are linked by 2 arrow, one from 1 to 2, one form 2 to 1. Is possible to draw only one line with both arrow?I would have a result like in route2.png but i don't know how!!!Help me!!!
#---#code#---import pydot
edges=[("10.0.0.1","10.0.0.2"), ("10.0.0.2","10.0.0.1"),("
10.0.0.2","10.0.0.7"),("10.0.0.2","10.0.0.9"),("
10.0.0.2","10.0.0.6"),("10.0.0.9","10.0.0.8"),("10.0.0.6","
10.0.0.7") ]g=pydot.graph_from_edges(edges,directed=True)
g.write_png('route.png')-- Sbaush


route.png
Description: PNG image


route2.png
Description: PNG image
-- 
http://mail.python.org/mailman/listinfo/python-list

a numarray question

2006-02-15 Thread avharut
hello everyone

would anyone please tell me what is the best (fastest) way of replacing
values in numarray arrays?

lets say i have an array that may contain 0s, and i just want to get
rid of those 0s by replacing them with another number. what would be
the most efficient way to do that?

many thanks in advance!

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


using the Filters DLL (image filters)

2006-02-15 Thread Dieter Vanderelst
Hello,

I'm trying to access the Filters-Dll provided by the filters-project 
(http://filters.sourceforge.net/index.htm).

Following the advice I got from the Python list -thank you for that-, I 
do this using ctypes 
(http://starship.python.net/crew/theller/ctypes/index.html).

I can seem to access the image filters now provided by the Dll. But 
reading and writing of images is still a problem.
Furthermore, the project is not very well documented. So, I was 
wondering whether there are people on this list that have some 
experience in using the filters Dll. Maybe they could sent me some 
examples of the use of the Dll with Python?

Kind regards,
Dieter

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


Re: Python advocacy in scientific computation

2006-02-15 Thread Juho Schultz
Michael Tobis wrote:
> Someone asked me to write a brief essay regarding the value-add
> proposition for Python in the Fortran community. Slightly modified to
> remove a few climatology-related specifics, here it is.
> 

Thank you - this was very good reading.

> I would welcome comments and corrections, and would be happy to
> contribute some version of this to the Python website if it is of
> interest.
> 

A slight broadening of the perspective could show another advantage:
Python is also used for data processing, at least in astronomy. Modeling 
and processing the data in the same environment is very practical. Spend 
more time on modeling and processing the critical data sections - 
critical data section may depend on model parameters and sampling (which 
is often incomplete and uneven). You also avoid wasting CPU cycles to 
model things not in the data.

A theorist may be perfectly happy with Fortran, and an observer could do 
his stuff with simple scripts. But if they need to work together, Python 
is a very good option.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using the Filters DLL (image filters)

2006-02-15 Thread Michele Petrazzo
Dieter Vanderelst wrote:
> Hello,
> 
> I'm trying to access the Filters-Dll provided by the filters-project
>  (http://filters.sourceforge.net/index.htm).

Nice project :)

> 
> Following the advice I got from the Python list -thank you for that-,
> I do this using ctypes 
> (http://starship.python.net/crew/theller/ctypes/index.html).

Good choose!

> 
> I can seem to access the image filters now provided by the Dll. But 
> reading and writing of images is still a problem.

What are the problems? Please specify it.

> Furthermore, the project is not very well documented. So, I was 
> wondering whether there are people on this list that have some 
> experience in using the filters Dll. Maybe they could sent me some 
> examples of the use of the Dll with Python?

There are a lot of python projects that use ctypes for use libraries
(.dll/.so). You can see them for study and copy that code (like all do :P ).
Start at wnd.sf.net and freeimagepy.sf.net

> 
> Kind regards, Dieter
> 

Bye,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a numarray question

2006-02-15 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
> hello everyone
> 
> would anyone please tell me what is the best (fastest) way of replacing
> values in numarray arrays?
> 
> lets say i have an array that may contain 0s, and i just want to get
> rid of those 0s by replacing them with another number. what would be
> the most efficient way to do that?
> 
> many thanks in advance!
> 
One way to do that is

data2 = numarray.choose(numarray.equal(data,0), (data, another_number))

I am not sure this is the most efficient way. If you get other 
suggestions, you can compare them with the timeit module.

http://www.python.org/doc/2.4.2/lib/module-timeit.html

But if you plan to do calculations with the data, I think replacing 
zeros is not critical for performance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Downloading files using urllib in a for loop?

2006-02-15 Thread Martin Franklin

[EMAIL PROTECTED] wrote:
> Hi,
>  I'm using Python 2.3 on Windows for the first time, and am doing
> something wrong in using urllib to retrieve images from urls embedded
> in a csv file. If I explicitly specify a url and image name it works
> fine(commented example in the code), but if I pass in variables in this
> for loop it throws errors:
> 
> --- The script:
> 
> import csv, urllib
> reader = csv.reader(open("source.csv"))
> for x,y,z,imagepath in reader
>   theurl = imagepath[:55]
>   theimage = imagepath[55:-8]

"No such file or directory: ''" sounds to me like you are trying
to open a file called '' (empty string)

try adding some debugging

 print theimage, imagepath



>   urllib.urlretrieve(theurl, theimage)
>   #urllib.urlretrieve("http://someurl/image.gif";, "image.gif") # works!
> 
> --- The errors:
> 
> This throws the following errors:
>   File "getimages.py", line 9, in ?
> urllib.urlretrieve(theurl,theimage)
>   File "C:\Python23\lib\urllib.py", line 83, in urlretrieve
> return _urlopener.retrieve(url, filename, reporthook, data)
>   File "C:\Python23\lib\urllib.py", line 213, in retrieve
> fp = self.open(url, data)
>   File "C:\Python23\lib\urllib.py", line 181, in open
> return getattr(self, name)(url)
>   File "C:\Python23\lib\urllib.py", line 410, in open_file
> return self.open_local_file(url)
>   File "C:\Python23\lib\urllib.py", line 420, in open_local_file
> raise IOError(e.errno, e.strerror, e.filename)
> IOError: [Errno 2] No such file or directory: ''
> 
> ---
> 
> Would really appreciate some pointers on the right way to loop through
> and retrieve images, as I've tried various other solutions but am
> clearly missing something simple!
> 
> Thanks,
> 
> justin.
> 

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


Downloading files using urllib in a for loop?

2006-02-15 Thread justsee
Hi,
 I'm using Python 2.3 on Windows for the first time, and am doing
something wrong in using urllib to retrieve images from urls embedded
in a csv file. If I explicitly specify a url and image name it works
fine(commented example in the code), but if I pass in variables in this
for loop it throws errors:

--- The script:

import csv, urllib
reader = csv.reader(open("source.csv"))
for x,y,z,imagepath in reader
  theurl = imagepath[:55]
  theimage = imagepath[55:-8]
  urllib.urlretrieve(theurl, theimage)
  #urllib.urlretrieve("http://someurl/image.gif";, "image.gif") # works!

--- The errors:

This throws the following errors:
  File "getimages.py", line 9, in ?
urllib.urlretrieve(theurl,theimage)
  File "C:\Python23\lib\urllib.py", line 83, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
  File "C:\Python23\lib\urllib.py", line 213, in retrieve
fp = self.open(url, data)
  File "C:\Python23\lib\urllib.py", line 181, in open
return getattr(self, name)(url)
  File "C:\Python23\lib\urllib.py", line 410, in open_file
return self.open_local_file(url)
  File "C:\Python23\lib\urllib.py", line 420, in open_local_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] No such file or directory: ''

---

Would really appreciate some pointers on the right way to loop through
and retrieve images, as I've tried various other solutions but am
clearly missing something simple!

Thanks,

justin.

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


Re: Which is faster? (if not b in m) or (if m.count(b) > 0)

2006-02-15 Thread Felipe Almeida Lessa
Em Ter, 2006-02-14 às 20:14 -0800, Farel escreveu:
> Which is Faster in Python and Why?
> 
> jc = {}; m = []
> x = [ [1,2,3,4,5,6,7,8,9],[..],...] # upwards of 1 entries
> def binm()
> for item in x:
> b = item[:]; b.sort(); bc = 0
> for bitem in b: bc += int(bitem)
> try: m = jc[bc]
> except: m = []
> if not b in m:
> m.append(b); jc[bc]=m

Why do you copy the list and sort it if you're just summing its
elements? Instead of

b = item[:]; b.sort(); bc = 0
for bitem in b: bc += int(bitem)

you can do just

bc = sum(int(i) for i in item)

or, if the order *really* matters, what is very strange, you can do

bc = sum(int(i) for i in sorted(item))

Another thing, if you want to have in the values of the dictionary jc
only unique elements, you can use sets:

>>> a = set()
>>> print a
set([])
>>> a.add(10)
>>> print a
set([10])
>>> a.add(10)
>>> print a
set([10])
>>> a.add(10)
>>> print a
set([10])

So, the final example would be (assuming that you don't need to sum in
order):

def binm():
for item in x:
bc = sum(int(i) for i in item)
try:
jc[bc].add(b)
except KeyError:
jc[bc] = set([b])

Looks prettier, have less statements and is (or should be) faster. This
only works in Python 2.4, but you can adapt it to run on other versions,
too.

Cheers,
Felipe.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: Downloading files using urllib in a for loop?

2006-02-15 Thread justsee
Thanks - but have printed and verified they are valid paths and
filenames. One correction to the code I listed:
   theurl = imagepath[:-8]

For some reason the values aren't being passed through
urllib.urlretrieve properly but this makes no sense to me?

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


pop line from file

2006-02-15 Thread Sinan Nalkaya
hello all,
i searched and google long long time but couldnt find any result, i
want pop the first line from file, i dont want to read all file
contents because file is being updated from another proccess. even i
couldnt realize its algorithm, thanks for any suggestion
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a C-style for loop?

2006-02-15 Thread ZeD
Ciao, John Salerno! Che stavi dicendo?

> for (int i = 0; i < 50; i += 5)
> 
> How would that go in Python, in the simplest and most efficient way?

i=0
while i<50:
#...
i+=5

about range()/xrange(): what if you want to traslate this c-loop?
for (int i=1; i<50; i*=2)

-- 
Evangelion e' la storia yaoi di un angelo che vuole portarsi a letto un
ragazzo che si intreccia con la storia di un maturo professionista con il
complesso delle lolite... fatte in casa.
-- Lennier, 2006

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


Re: Downloading files using urllib in a for loop?

2006-02-15 Thread Fredrik Lundh
Martin Franklin wrote:

> "No such file or directory: ''" sounds to me like you are trying
> to open a file called '' (empty string)
>
> try adding some debugging
>
>  print theimage, imagepath

or, better:

print repr(theimage), repr(imagepath)





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


choose and open a folder in Windows

2006-02-15 Thread palo
Hello
I wrote a little script (that will be used only under Windows if at
all) where the user should choose a directory and the script will then
process some data files in the directory and write the result there. To
make it a bit more pleasant, it would be nice if the directory were
chosen by the standard win directory chooser. When the script is done,
it could open the the directory, so that the user can check the
results. How to do these two things? (I searched this forum and found a
simple solution for the first one, using Tkinter - so there is just an
unimportant question whether one really needs Tkinter to start a
standard windows dialog. But I didn't find how to make windows to open
a given directory in file expolorer)
P.

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


Re: a numarray question

2006-02-15 Thread Bas
I believe it is something like

a[a==0] = 5

Note that numarray will eventually be replaced by Scipy/Numpy at some
time, but this wouldn't change the basic stuff.

Cheers,
Bas

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


Re: Pythonic gui format?

2006-02-15 Thread Gregory Petrosyan
Bruno: in your original example, how can it be specified that image
should be placed before text? Of course, it  *can*  be done with one
extra level of wrapping of gui elements in list... did you mean that?

Patrik: thanks a lot!
Stan (the way it represents XML) is almost what I am looking for.

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


[ANN] Movable Python 1.0.1

2006-02-15 Thread Fuzzyman
I'm pleased to be able to announce the release of `Movable Python 1.0.1
`_. This includes the
release of **Movable Python** for Python 2.2.

To obtain it, visit the `Movable Python Shop
`_.

Existing users of Movable Python can go to the groups area and simply
download an updated copy.

.. note::

For a heads up about possible features in the *next* version of a
Movable Python, visit the `Voidspace Techie Blog
`_.

What's New ?
==

Added support for the ``-m`` command line option. This works for
modules contained within the ``library.zip``, as well as other modules
on ``sys.path``.

**Movable Python** now *ignores* (with warnings) the unsupported Python
command line options.

Error messages are now printed to ``sys.stderr``.

Can run '.pyc' and '.pyo' files.

``customize.py`` now run when launching an interactive interpreter.

Renamed the function to go interactive to ``interactive_mode``.

New variable available in ``customize.py``. ``interactive``, this is
``True`` if launching an interactive interpreter. This allows you to
customize the environment differently for interactive sessions.

Add the ``lib`` directory (etc) to ``sys.path`` before entering
interactive mode. (BUGFIX)

``pywin32`` extensions now import properly (even on machines that don't
have them installed). (BUGFIX) {sm;:oops:}

Added the extra files for `Firedrop2 Macros
`_.

Changes for Python 2.2 compatibility. Distribution for Python 2.2
built.

What is Movable Python ?
===

**Movable Python** is a distribution of Python for Windows that doesn't
need to be installed. It easily fits onto a USB memory stick. Python on
a stick.

It is integrated with SPE, the Python IDE, to make **Movable Python** a
portable Build, Test, and Run environment. It has a nice GUI to launch
programs and control its behaviour.

Movable Python is useful in the following situations:

* Machines where you can't install programs.
* Where you need a portable 'Build, Test, and Run' Python environment.
* Having several versions of Python on the same machine for
forward/backward compatibility testing.
* Easily deploying Python scripts without having to install Python.
* Try before you buy - test Python without having to install it,
including new versions .
* 'Python Runtime Environment'. '``.py``' files can be associated with
movpy.

For more information, see `An Introduction to Movable Python
`_.


Known Issues
==

* There are problems with the ``pywin32`` extensions and Python 2.2.
They are included but may not all function correctly.
* ``-m`` doesn't work with modules in ``library.zip`` under Python 2.2.
This may or may not be resolvable.
* **Movable Python** doesn't yet handle ``from __future__ import ...``
statements in scripts that are run. This will be fixed.

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


Re: Downloading files using urllib in a for loop?

2006-02-15 Thread Martin Franklin
Martin Franklin wrote:
> [EMAIL PROTECTED] wrote:
>> Hi,
>>  I'm using Python 2.3 on Windows for the first time, and am doing
>> something wrong in using urllib to retrieve images from urls embedded
>> in a csv file. If I explicitly specify a url and image name it works
>> fine(commented example in the code), but if I pass in variables in this
>> for loop it throws errors:
>>
>> --- The script:
>>
>> import csv, urllib
>> reader = csv.reader(open("source.csv"))
>> for x,y,z,imagepath in reader

I just noticed the code you sent will not work... notice the lack of a 
colon ( : ) and the end of the 'for' line

please post an exact copy of your code and also the results with the
included print debugging line (with or without repr ;) )



Cheers
Martin


>>   theurl = imagepath[:55]
>>   theimage = imagepath[55:-8]
> 
> "No such file or directory: ''" sounds to me like you are trying
> to open a file called '' (empty string)
> 
> try adding some debugging
> 
>  print theimage, imagepath
> 
> 
> 
>>   urllib.urlretrieve(theurl, theimage)
>>   #urllib.urlretrieve("http://someurl/image.gif";, "image.gif") # works!
>>
>> --- The errors:
>>
>> This throws the following errors:
>>   File "getimages.py", line 9, in ?
>> urllib.urlretrieve(theurl,theimage)
>>   File "C:\Python23\lib\urllib.py", line 83, in urlretrieve
>> return _urlopener.retrieve(url, filename, reporthook, data)
>>   File "C:\Python23\lib\urllib.py", line 213, in retrieve
>> fp = self.open(url, data)
>>   File "C:\Python23\lib\urllib.py", line 181, in open
>> return getattr(self, name)(url)
>>   File "C:\Python23\lib\urllib.py", line 410, in open_file
>> return self.open_local_file(url)
>>   File "C:\Python23\lib\urllib.py", line 420, in open_local_file
>> raise IOError(e.errno, e.strerror, e.filename)
>> IOError: [Errno 2] No such file or directory: ''
>>
>> ---
>>
>> Would really appreciate some pointers on the right way to loop through
>> and retrieve images, as I've tried various other solutions but am
>> clearly missing something simple!
>>
>> Thanks,
>>
>> justin.
>>
> 

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


Re: Downloading files using urllib in a for loop?

2006-02-15 Thread Martin Franklin
[EMAIL PROTECTED] wrote:
> Thanks - but have printed and verified they are valid paths and
> filenames. One correction to the code I listed:
>theurl = imagepath[:-8]
> 
> For some reason the values aren't being passed through
> urllib.urlretrieve properly but this makes no sense to me?
> 

A working (for me!) example:-


import urllib

paths = ["http://www.python.org/index.html";, ]



for remotepath in paths:
 # keep only last 10 chars (index.html)
 # for local file name
 localpath = remotepath[-10:]

 print remotepath, localpath

 urllib.urlretrieve(remotepath, localpath)


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


RE: choose and open a folder in Windows

2006-02-15 Thread Tim Golden
[palo]

| But I didn't find how to make windows to open
| a given directory in file expolorer)
| P.

At the risk of suggesting the obvious, have you tried:


import os
os.system ("explorer.exe c:\\temp")


or 


import os
os.startfile ("c:\\temp")


or something similar?

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Pythonic gui format?

2006-02-15 Thread Ivan Voras
James Stroud wrote:

> The reasons given in the blog were fairly precise. I think "only on 
> vague[...]" is misleading here. The idea of the article was to educate a 
> Java user how to change his or her frame of reference to better use Python.
> 
> The author was not being territorial as you are implying.

What triggered me is the presence of lots of absolute statements like 
"XML is not the answer. It is not even the question.", "In Python, XML 
is something you use for interoperability, not your core functionality, 
because you simply don't need it for that." and similar. Though the 
author says at the end "There are also other, very rare, architectural 
reasons to need XML" he then proceeds to say "Trust me, they don't apply 
to your app." instead of educating the reader what they are and make him 
conclude that for himself. The article is actually quite good, but in 
this particular section the author doesn't explain his advices well. 
Personally, I the approach "X is good because of Y, except when Z and W, 
when it's the other way around" better, since IRL it's always so.

Mentioning (again, not explaining!) LISP to state XML is laughable is 
kind of lame, especially since the focus of the article are Python and Java.

Again, it's good, but I'd like more explanations and conditionals in 
that paragraph :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic gui format?

2006-02-15 Thread Fuzzyman

Gregory Petrosyan wrote:
> > > Isn't it ugly a bit?
> >I'd even say 'ugly 16-bits' !-)
>
> You are right of course. Those  "examples"  are really bad, and, most
> of all, really un-pythonic.
>
> Thanks for JSON. It's more clean&simple than XML, but my main idea is
> to remove any extra layer between Python and GUI. I want all GUI
> elements/data to be directly accessible from Python (without extra
> libraries).
> Your dicts example is nice, but this  approach (and some others) lacks
> one important feature: ordering of GUI elements. In XML, the order of
> all elements is specified, and with dicts (or with very clean Georg's
> model) it is not. (BTW remember topics about ordered dicts...)
>

ConmfigObj is *another* configuration module that has a nice syntax for
storing data. It will effectively store nested dicts with single items
or lists for values. You access members using the mapping protocol
(ordinary dictionary syntax), but members *are* ordered. (ConfigObj
instances are effectively ordered dictionaries as well.)

You say you don't want an 'extra layer' between your GUI  and Python -
but your approach of using XML has the same drawback. Storing your 'GUI
configuration' in a text based format is a nice idea, but you will need
*something* to do the translation.

http://www.voidspace.org.uk/python/configobj.html

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> I think that there should be a way for solving this problem, and I'll
> certainly try to find it.
> Thanks for your help.

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


Re: a numarray question

2006-02-15 Thread avharut
thanks guys!


import timeit
first_way = "the_array[the_array == 0] = 5.0"
second_way = "another_array = numarray.choose(the_array == 0,
(the_array, 5.0))"
some_third_way = """\
indx = numarray.where(the_array == 0)[0]
another_array = numarray.put(the_array, indx, len(indx) * [5.0,])
"""
initial_statements = 'import numarray; the_array =
numarray.array(int(1.0e6) * [1.0, 0.0])'
t1 = timeit.Timer(first_way, initial_statements)
t2 = timeit.Timer(second_way, initial_statements)
t3 = timeit.Timer(some_third_way, initial_statements)
print '1st way takes', round(t1.timeit(number=100) / 100, 4),
'seconds\n',\
   '2nd way takes', round(t2.timeit(number=100) / 100, 4),
'seconds\n',\
   '3rd way takes', round(t3.timeit(number=100) / 100, 4),
'seconds'


the above written stuff printed like:

1st way takes 0.0624 seconds
2nd way takes 0.0948 seconds
3rd way takes 0.0641 seconds

no any other idea on how else one might do the replacement and the
difference among those three seems to be not very big, well, i expected
something bigger.

p.s. gonna use the first way =)

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


Re: Which is faster? (if not b in m) or (if m.count(b) > 0)

2006-02-15 Thread bruno at modulix
Farel wrote:
> Which is Faster in Python and Why?

Why don't you try by yourself ?
hint :
from timeit import Timer
help(Timer)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding an Application in a Web browser

2006-02-15 Thread paron
You may already know this, but I don't think anyone has mentioned it
explicitly.

You can run a Python web server (I like CherryPy) on the local machine,
and serve pages to "localhost." Everything else is just plain old
Python, and talking to the OS is no problem.

Ron

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


Re: Pythonic gui format?

2006-02-15 Thread bruno at modulix
Fuzzyman wrote:
(snip)

> You say you don't want an 'extra layer' between your GUI  and Python -
> but your approach of using XML has the same drawback. Storing your 'GUI
> configuration' in a text based format is a nice idea, but you will need
> *something* to do the translation.

Well, if the conf is valid Python, you've already get most of the
'something to do the translation' for free !-)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic gui format?

2006-02-15 Thread bruno at modulix
Gregory Petrosyan wrote:
> Bruno: in your original example, how can it be specified that image
> should be placed before text? Of course, it  *can*  be done with one
> extra level of wrapping of gui elements in list... did you mean that?

Yes. That's a pretty straightforward translation of the real Python's
object structure:

class Window(...):
  def __init__(self):
self._widgets = []

=>

window = {
  'widgets' : [],
}

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: processing limitation in Python

2006-02-15 Thread Steven D'Aprano
On Wed, 15 Feb 2006 10:16:07 +, Dennis Lee Bieber wrote:

>   Why bother collecting the "factors" into a list only to print them
> at the bottom of the procedure -- you aren't returning a value from
> factor(), so I'd suggest dropping the 
>   factors = []
> and
>   print factors
> 
> replace
>   factors.append(d)
> with
>   print d #optional , if you want as many on a line as possible

This is generally bad practice. You now have a function which can't
easily feed its output into any other function (without pipes, file
redirection and other tricks). The function is now locked down into one
rather limited use: printing the factors.

If you need the factors one at a time, the right way is to use a
generator, and yield them as they are found. Otherwise, the correct way to
solve this problem is to accumulate all the factors in a list and return
the list.


>   Among other things, besides not needing memory to store the entire
> list, you also get to see it working as each one is found and printed.

The amount of memory needed to store the entire list is trivial for all
but the hugest numbers. A number with 1,000 factors would be enormous,
and yet the memory needed for a list of 1,000 ints could be as small as
8K -- trivial on modern computers.


-- 
Steven.

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


low level data types

2006-02-15 Thread dementrio
How can I handle low-level data types in Python?
What I want to do is writing an interface to a C daemon which waits for
stuff like unsigned ints on a socket. For example, I need to craft and
decode data structures that look like this:

32-bit unsigned int MSG_LENGTH
32-bit unsigned int MSG_CODE
64-bit signed int DATA
32-bit length + utf-8 characters STRING_DATA
etc.

What's the right way to do this in Python?

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


Re: Python and ASP

2006-02-15 Thread Roger Upole
No, what I mean is that until you upload the file to the web server and
request it back thru the server, it's just a text source file.  However,
let me make sure I understood your previous post.  I had thought
you meant you were opening the ASP file directly, as in locally and
not from a web service.
Did I read that right ?

  Roger

"Tempo" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> What do you mean? I can't just upload the file to the server that is
> going to host my site?
> 




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Downloading files using urllib in a for loop?

2006-02-15 Thread justsee
ah - thanks for your help, but what is happening is the first line
being returned contains the field names from the csv file! Schoolboy
errors :-)

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


Re: low level data types

2006-02-15 Thread Fredrik Lundh
"dementrio" wrote:

> What I want to do is writing an interface to a C daemon which waits for
> stuff like unsigned ints on a socket. For example, I need to craft and
> decode data structures that look like this:
>
> 32-bit unsigned int MSG_LENGTH
> 32-bit unsigned int MSG_CODE
> 64-bit signed int DATA
> 32-bit length + utf-8 characters STRING_DATA
> etc.
>
> What's the right way to do this in Python?

http://docs.python.org/lib/module-struct.html





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


Re: Which is faster? (if not b in m) or (if m.count(b) > 0)

2006-02-15 Thread Steven D'Aprano
On Wed, 15 Feb 2006 08:44:10 +0100, Marc 'BlackJack' Rintsch wrote:

> In <[EMAIL PROTECTED]>, Farel wrote:
> 
>> Which is Faster in Python and Why?
> 
> ``if not b in m`` looks at each element of `m` until it finds `b` in it
> and stops then.  Assuming `b` is in `m`, otherwise all elements of `m` are
> "touched".
> 
> ``if m.count(b) > 0`` will always goes through all elements of `m` in the
> `count()` method.

But the first technique executes in (relatively slow) pure Python, while
the count method executes (relatively fast) C code. So even though count
may do more work, it may do it faster.

The only way to tell for sure is to actually time the code, not try to
guess.



-- 
Steven.

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


Re: Embedding an Application in a Web browser

2006-02-15 Thread paron
I forgot -- I like the idea of Kerrigell, too. It runs on top of
CherryPy, and lets you use python either in the server (which is just a
little program on your local machine) or embedded in the html pages, or
in a Kerrigell service, which is an application server based on Python.

So, a script to print the squares of numbers from 1 to 9 looks like:

Python script +

print "Squares"
for i in range(10):
print "%s :%s" %(i,i*i)


Karrigell service 

def index():
print "Squares"
for i in range(10):
print "%s :%s" %(i,i*i)

HTML Inside Python +++

"Squares"
for i in range(10):
"%s :%s" %(i,i*i)

Python Inside HTML +++

Squares
<%
for i in range(10):
print "%s :%s" %(i,i*i)
%>

It's certainly flexible.

As far as your animated shapes go, you have a number of unattractive
options!

Flash (my preference, if you already have the authoring software,)
openLazslo (maybe the best bet for free),
SVG (which requires a plug-in for IE,) or
creating them and making them interactive with Javascript ( see
http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm )

Ron

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


[ANN] pyqonsole-0.2.0

2006-02-15 Thread Alexandre Fayolle
Logilab has released pyqonsole-0.2.0

Pyqonsole is a X Window terminal written in Python. The code is based
on konsole, and it uses the Qt toolkit. It is mainly meant for use by
Python application developpers who would like to embed a terminal in
their application, but it can be used as a not blazingly fast XTerm
replacement.

Download: http://www.logilab.org/projects/pyqonsole
Mailing List: http://www.logilab.org/mailinglists/python_projects

-- 
Alexandre Fayolle  LOGILAB, Paris (France).
http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org
Retrait du projet de loi DADVSI: http://eucd.info/petitions/index.php?petition=2


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to write a C-style for loop?

2006-02-15 Thread Steven D'Aprano
On Wed, 15 Feb 2006 10:20:13 +, ZeD wrote:

> Ciao, John Salerno! Che stavi dicendo?
> 
>> for (int i = 0; i < 50; i += 5)
>> 
>> How would that go in Python, in the simplest and most efficient way?
> 
> i=0
> while i<50:
> #...
> i+=5

That's exceedingly unPythonic. In fact I'd go far to say it is bad
practice in just about any programming language that has for loops. Why on
earth would any sensible programmer want to manage the loop variable by
hand if the language can do it for you?


> about range()/xrange(): what if you want to traslate this c-loop? for
> (int i=1; i<50; i*=2)

That's a completely different question, so of course it has a completely
different answer. Here is one way:

for i in [2**n for n in range(6)]:
do_something(i)

Here is another:

for i in range(int(math.log(50)/math.log(2)+1)):
do_something(2**i)

Here is a third way:

i = 1
while i < 50:
do_something(i)
i *= 2

Here is a fourth way:

import operator
def looper(start, (op, finish), (op2, x)):
n = start
while op(n, finish):
yield n
n = op2(n, x)

loop = looper(1, (operator.__lt__, 50), (operator.__mul__, 2))

for i in loop:
do_something(i)



-- 
Steven.

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


Re: how to write a C-style for loop?

2006-02-15 Thread Duncan Booth
Steven D'Aprano wrote:

>> about range()/xrange(): what if you want to traslate this c-loop? for
>> (int i=1; i<50; i*=2)
> 
> That's a completely different question, so of course it has a completely
> different answer. Here is one way:

... various options snipped ...

and another way for use when you have more than one loop following this 
pattern:

def powerrange(base, start=0, limit=0):
value = base**start
while value < limit:
yield value
value *= base


for i in powerrange(2,0,50):
dosomething(i)


Putting the question the other way round: how would you move the control 
logic out of the loop in C?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pop line from file

2006-02-15 Thread Dylan Wilson
Try open.readline()

>>>help(open)
...

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


Re: choose and open a folder in Windows

2006-02-15 Thread palo
thanks a lot, it works
and sorry for intelligent questions:)

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


Re: Rethinking the Python tutorial

2006-02-15 Thread Magnus Lycka
JW wrote:
> I started with the official tutorial.  It seemed up to date to me.
> Things that changed from 2.4 to 2.5 changed in the tutorial as well. 

Agreed. I mainly felt that A Byte of Python seems to go through
the features in Python in a more systematic way. The official
tutorial is being kept up to date concerning details, but it's
basically the same text as ten years ago. I think we owe a lot
of gratitude to Fred Drake and all the other peope who have put
a lot of efforts into the tutorial, but it's too much to expect
that they would transform it significantly. It was written a
long time ago, with different users, use cases and features in
mind.

If we would really get a user guide, I guess there is less reason
to have a differently organized tutorial though. Today, I guess we
suffer from the fact that the tutorial is the only place to describe
things that don't fit in the library reference in a user-oriented
way. Yet, the tutorial is not organized as a reference, and from
the purely tutorial point of view, it wouldn't have to be complete.

> I haven't tried "A Byte of Python", so I can't comment.

Please do. I've been programming Python since 1996, so I'm
really just guessing when I try to judge material for beginners.
My impression is that it's aa good and well organized tutorial.

> I tried to learn from "Dive into Python", but I found that it went too
> quickly. 

Right. I would not suggest replacing the official tutorial
with that. I see it more as a complement.

> "Dive into Python" is not being kept up to date.  The last revision was
> May 2004, and several things have changed since then.

Ok. There are two issues here I guess.

First of all, any official material needs to be kept up
to date, whether it's the old tutorial or a new one. It
might be too much to maintain both A Byte of Python and
one more text if we change tutorial(s).

Secondly, since Dive into Python goes beyond the core of
Python, with dependencies to third party stuff, I guess
it's more costly to maintain.

Perhaps it was a bad suggestion to include that. Thanks
for your feedback.

> I think the most important thing for a tutorial is a consistant style
> and a consistant idea of the user's capabilities.  This is easiest with
> a single maintainer, but requires constant dilligence and a subdued ego
> for a collaborative document.

On the other hand, one size doesn't fit all. Thus my suggestion
of two texts. With the 60+ links that I mentioned before, I don't
think the current way newbies are guided to tutorials is ideal.
There is too much to choose from and to little guidence for those
who try to figure out where to go. The information is also spread
out too much.

http://python.org/doc/
http://python.org/doc/2.4.2/ ==(?) http://docs.python.org/
http://wiki.python.org/moin/BeginnersGuide + sub pages
http://www.python.org/doc/Intros.html
etc...

If the content in these pages were cleaned up significantly
(it's like the wardrobes at home--we can't keep all that old
stuff just because it isn't broken. Throw out the stuff which
isn't essential) I guess we could have less official stuff
(e.g. just one tutorial) and clear links to the others.

Perhaps a better approach would be that Dive ino Python was
one of a smaller set of external links to tutorials, in a
cleaned up set of web pages. At least, it's not a problem today
that there are too few online Python tutorials on the web.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding an Application in a Web browser

2006-02-15 Thread paron
I forgot -- I like the idea of Kerrigell, too. It runs on top of
CherryPy, and lets you use python either in the server (which is just a
little program on your local machine) or embedded in the html pages, or
in a Kerrigell service, which is an application server based on Python.

So, a script to print the squares of numbers from 1 to 9 looks like:

Python script +

print "Squares"
for i in range(10):
print "%s :%s" %(i,i*i)


Karrigell service 

def index():
print "Squares"
for i in range(10):
print "%s :%s" %(i,i*i)

HTML Inside Python +++

"Squares"
for i in range(10):
"%s :%s" %(i,i*i)

Python Inside HTML +++

Squares
<%
for i in range(10):
print "%s :%s" %(i,i*i)
%>

It's certainly flexible.

As far as your animated shapes go, you have a number of unattractive
options!

Flash (my preference, if you already have the authoring software,)
openLazslo (maybe the best bet for free),
SVG (which requires a plug-in for IE,) or
creating them and making them interactive with Javascript ( see
http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm )

Ron

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


Re: pop line from file

2006-02-15 Thread Sybren Stuvel
Sinan Nalkaya enlightened us with:
> i searched and google long long time but couldnt find any result, i
> want pop the first line from file, i dont want to read all file
> contents because file is being updated from another proccess.

So basically, what you want is some sort of on-disk FIFO queue, right?
Unless your filesystem supports this, there is no way to do that
programmatically.

Removing the first line of a file without having to rewrite the entire
file, requires the pointer to the beginning of the data of the file to
be altered. Since this pointer usually consists of a block number, it
is impossible to point to the new start, unless all lines in the file
are exactly one block in length. This probably isn't the case.

If you're working on a UNIX platform, you could use FIFO pipes, see
'mkfifo'.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding an Application in a Web browser

2006-02-15 Thread Kent Johnson
paron wrote:
> I forgot -- I like the idea of Kerrigell, too. It runs on top of
> CherryPy

Karrigell is independent of CherryPy, it has it's own web server built in.

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


Re: 'could not open display' error when import gtk - how fix?

2006-02-15 Thread ngw
[EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> Why can't I import gtk (pygtk) module?  It appears gtk module want X
> perms?
>
>
 import gtk
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/lib/python2.3/site-packages/gtk-2.0/gtk/__init__.py", line
> 37, in ?from _gtk import *
> RuntimeError: could not open display

You have to run the pyshell under the right permissions. Are you
trying to import pygtk from the root/toor account ?

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


Code organization

2006-02-15 Thread Thomas Girod
Hi.

I found a lot of documentation about how to code in Python, but not
much about how you organize your code in various modules / packages ...
As I am not yet used to python, this puzzle me a bit.

So, can anyone explain how one should organize and store its code ? the
uses of __init__.py files ? Maybe my question is not very clear, but I
hope someone will understand anyway ...

Thomas

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


Re: Win32_Process.Create -- not starting process

2006-02-15 Thread abcd
Tim,
   Ok, well I verified that my python script and batch script are
working properly.  In fact, if I double click on the batch script (when
its on Computer B), it starts the python script and the script runs
fine with no problem.
However when I try to execute the batch script from computer A
using WMI it doesnt start.  I say that because the python script that
gets executed writes a status message to a file, and that does not
occur as well as Python.exe does not show up in the task manager, even
though Win32_Process.Create returns a PID and a 0 for the return code.
So, if I try the same process a second time...it works.  python.exe is
running, status message is written to a file, etc.  Is there some sort
of initialization that needs to be done?

Thanks

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


Re: Python and ASP

2006-02-15 Thread Steve Holden
Tempo wrote:
> What do you mean? I can't just upload the file to the server that is
> going to host my site?
> 
Note that the language identifier directive

<%@ Language=Python %>

should come right at the top of the file to do any good.

Is this an ISP-managed web server? If so it's possible that they haven't 
(and may not want to) installed the Active Scripting features of Python 
that come with the win32all extensions.

I can't remember offhand whether a separate step is necessary after 
installing win32all, but without those extensions IIS just won't 
recognize Python as an Active Scripting language.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Code organization

2006-02-15 Thread bruno at modulix
Thomas Girod wrote:
> Hi.
> 
> I found a lot of documentation about how to code in Python, but not
> much about how you organize your code in various modules / packages ...
> As I am not yet used to python, this puzzle me a bit.
> 
> So, can anyone explain how one should organize and store its code ? the
> uses of __init__.py files ? Maybe my question is not very clear, but I
> hope someone will understand anyway ...

Well... As a starting point relative to Python specific stuff (use of
__init__.py etc), the Fine Manual is your friend:
http://www.python.org/doc/2.4.2/tut/node8.html

Now for best practices and whatnots, this isn't really specific to
Python. Try to have modules with high cohesion and low coupling, and
it'll be fine. Eventually try to provide a facade class or function for
complex packages (this is a current pattern in the standard lib).

Also, python-is-not-java, so don't feel commited to putting everything
in classes when plain functions would do, and avoid the 1:1 class/file
Java plague !-)

My 2 cents...
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic gui format?

2006-02-15 Thread Fuzzyman

bruno at modulix wrote:
> Fuzzyman wrote:
> (snip)
>
> > You say you don't want an 'extra layer' between your GUI  and Python -
> > but your approach of using XML has the same drawback. Storing your 'GUI
> > configuration' in a text based format is a nice idea, but you will need
> > *something* to do the translation.
>
> Well, if the conf is valid Python, you've already get most of the
> 'something to do the translation' for free !-)
>

Except he can't use ordinary dictionaries because they don't preserve
order, which is one of his requirements...

Your trivial example below redone with ConfigObj syntax :

[window]

widgets = , # empty list

Code to read it :

from configobj import ConfigObj
gui_object = ConfigObj(filename)

All thebest,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml


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

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


Re: Best way of finding terminal width/height?

2006-02-15 Thread Joel Hedlund
> Sure.  I was going to do that yesterday, but I realized that I
> didn't know how/where to do it.  I assume there's a link
> somewhere at www.python.org, but I haven't had a chance to look
> yet.

It's already reported to the bug tracker:

http://www.python.org/sf/210599

Apparently, this has been around since 1.5.2. It's in fact also in the feature 
request PEP right now: 

http://www.python.org/peps/pep-0042.html

and it's listed as a "Big" project under the "Standard library" heading. I 
assume we're going to have to live with this for a while yet...

Take care everyone!
/Joel
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Win32_Process.Create -- not starting process

2006-02-15 Thread Tim Golden
[abcd]

|Ok, well I verified that my python script and batch script are
| working properly.  In fact, if I double click on the batch 
| script (when its on Computer B), it starts the python script and the
script runs
| fine with no problem.

That's all very well, and it does confirm that there's no
obvious error in the file, but by running the batch script
*on* the computer it's on, you're running it in a particular
environment / context etc. That environment isn't (necessarily)
the same when you're running it across WMI.

All I'm saying is that remotely executed jobs tend to be
sensitive to environment issues which one is usually
unconcerned about. This is as true for cron jobs or
ssh-initiated execution on Unix as it is for WMI or
service-driven execution under Windows.

| However when I try to execute the batch script from computer A
| using WMI it doesnt start.  I say that because the python script that
| gets executed writes a status message to a file, and that does not
| occur as well as Python.exe does not show up in the task manager, even
| though Win32_Process.Create returns a PID and a 0 for the return code.
| So, if I try the same process a second time...it works.  python.exe is
| running, status message is written to a file, etc.  Is there some sort
| of initialization that needs to be done?

Ok. That's certainly peculiar. I assume that the pid / zero-return
is because the batch script itself is run; it's only the python
script which isn't. Which doesn't explain why it runs the second
time.

Some obvious test cases:

1) If you have the batch script write something out to file by itself,
does that happen? (eg SET > c:\temp.txt). Note - make sure the log
file destination is absolute, ie c:\temp.txt, not just temp.txt.


SET > c:\temp\test.txt


2) If you bypass the batch altogether, does that work, eg


import wmi
c = wmi.WMI ()
c.Win32_Process.Create (CommandLine=r"c:\python24\python
c:\temp\test.py")


If this isn't getting you anywhere, could you post up
or send me privately your batch and python scripts?

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: how do you pronounce 'tuple'?

2006-02-15 Thread Grant Griffin
Tim Peters wrote:
...
> "tuhple" is a girly-man affectation.  That's why Guido and I both say
> the manly "toople".
...

Yes, but doesn't Guido say 'Guido' with some sort of strange faux-manly 
'H'-ish sortta sound?

methinks-the-lady-doth-protest-too-much-ly y'rs,

=g2
-- 
_

Grant R. Griffin
Publisher of dspGuru   http://www.dspguru.com
Iowegian International Corporationhttp://www.iowegian.com
See http://www.iowegian.com/img/contact.gif for e-mail address
-- 
http://mail.python.org/mailman/listinfo/python-list


file existence checking

2006-02-15 Thread john peter
does anyone have a suggestion on simplest way to check for the existence of a file  within the same directory where a python script was started without really opening it?  i've seen some people use this as a mechanism for informing an application of  an external event, signalling it for example to disable some functionalities,  or perhaps a thread. Is such an approach a good one? Are there other "simple" approaches that  might be better (if so, why is it/are they better?)__Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Code organization

2006-02-15 Thread Kent Johnson
bruno at modulix wrote:
> Thomas Girod wrote:
>>
>>I found a lot of documentation about how to code in Python, but not
>>much about how you organize your code in various modules / packages ...
>>As I am not yet used to python, this puzzle me a bit.
> 
> Now for best practices and whatnots, this isn't really specific to
> Python. Try to have modules with high cohesion and low coupling, and
> it'll be fine. Eventually try to provide a facade class or function for
> complex packages (this is a current pattern in the standard lib).

Also, be aware of dependencies between packages and make sure they are 
acyclic - if a module in package A imports a module in package B, then A 
depends on B and B should not be allowed to also depend on A either 
directly (module in B imports module in A) or indirectly (module in B 
imports module in C which imports module in A).

If you follow this rule your packages will be more testable and 
reusable. The alternative tends to devolve into 
everything-depends-on-everything-else which makes testing harder and 
reuse nearly impossible.

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


Re: How to *Search* with google from inside my programme and get the search result?

2006-02-15 Thread Brett g Porter
I V wrote:
> Frank Potter wrote:
>> Does google supply some webservice to programmers? I did see
> 
> Googling for "google api" gets you to:
> 
> http://www.google.com/apis/
> 
> It appears to be a SOAP API, which you can access with python, but I
> think you'll need a third-party library. Googling for "python soap"
> gets you:
> 
> http://www-128.ibm.com/developerworks/library/ws-pyth5/
> 
> which might be a place to start.
> 
Or even easier:
http://pygoogle.sourceforge.net/

SUMMARY
---
This module allows you to access Google's web APIs through SOAP,
to do things like search Google and get the results programmatically.
This API is described here:
   http://www.google.com/apis/

SYSTEM REQUIREMENTS
---
Requires Python 2.0 or later

Requires the SOAPpy library from the Python Web Services project
(http://pywebsvcs.sourceforge.net).  We include an older version, but
its use is now deprecated (and will go away completely in future
releases).  Unfortunately, versions of SOAPpy prior to 0.11.3 will not
work correctly, and thus PyGoogle will fall back on the included
SOAP.py library if an earlier version is found.

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


Re: windows security descriptors

2006-02-15 Thread rtilley
The link changed... sorry.
http://opensource.w2k.vt.edu/Win32_Perms.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'could not open display' error when import gtk - how fix?

2006-02-15 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> Why can't I import gtk (pygtk) module?  It appears gtk module want X
> perms?
>
>
> >>> import gtk
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/lib/python2.3/site-packages/gtk-2.0/gtk/__init__.py", line
> 37, in ?from _gtk import *
> RuntimeError: could not open display

An error like this usually happens when X security is on, or the
display name isn't known.

#before you run it, try (for csh):
setenv DISPLAY host:0.0
#where host is your computers name

#If that doesn't get it, do:
xhost +

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


Re: file existence checking

2006-02-15 Thread Fredrik Lundh
"john peter" <[EMAIL PROTECTED]> wrote:
> does anyone have a suggestion on simplest way to check for the existence of a 
> file
>   within the same directory where a python script was started without really 
> opening
>   it?

it's not like opening a file is a very expensive or dangerous operation, but
you can use

import os

if os.path.isfile(filename):
print "a file named", filename, "exists"

or

if os.path.exists(filename):
print "something named", filename, "exists"

to check for a file.  however, if you plan to open the file later on, it's 
better
to just open it, and deal with the exception; e.g.

try:
f = open(filename)
except IOError:
print "failed to open", filename
sys.exit(1)

data = f.read(100)





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


Re: low level data types

2006-02-15 Thread Simon Brunning
On 15 Feb 2006 04:07:37 -0800, dementrio <[EMAIL PROTECTED]> wrote:
> How can I handle low-level data types in Python?
> What I want to do is writing an interface to a C daemon which waits for
> stuff like unsigned ints on a socket. For example, I need to craft and
> decode data structures that look like this:
>
> 32-bit unsigned int MSG_LENGTH
> 32-bit unsigned int MSG_CODE
> 64-bit signed int DATA
> 32-bit length + utf-8 characters STRING_DATA
> etc.
>
> What's the right way to do this in Python?

Look at the struct module.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a C-style for loop?

2006-02-15 Thread John Salerno
Tim Roberts wrote:
> John Salerno <[EMAIL PROTECTED]> wrote:
>> I assume this is the way for loops are written in C, but if it helps to 
>> be specific, I'm referring to C# for loops. The Python for loop seems to 
>> be the same (or similar) to C#'s foreach loop:
>>
>> foreach int i in X
>>
>> But how would you write a C# for loop in Python? Do you rework a while 
>> loop, or use the range() function?
>>
>> Here's an example:
>>
>> for (int i = 0; i < 50; i += 5)
>>
>> How would that go in Python, in the simplest and most efficient way?
> 
>   for i in range(0,50,5):
>   print i

Thanks guys. I thought it might be something like this. In fact, the 
chapter I just read dicussed how you use the range function with a for 
loop, but I didn't quite see a connection with the C# for loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding an Application in a Web browser

2006-02-15 Thread paron
Thanks, Kent -- you're right. That'll teach me to work from memory!

Ron

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


Re: Encryption application/NEED A HACKER TO TRY IT

2006-02-15 Thread Fredrik Lundh
"atanas Cosmas Nkelame" <[EMAIL PROTECTED]> wrote:


> I'm putting here the 'encoded' text for someone to try to encipher the text
> or tell me what is the chance that one can encipher the text.
>
>
> Here we go..
>
> .>. 3;0.$0.8:;07&:00: 07&.>..&;.$> 9::.$0. .&;..9>.;.$0.3;0 ;...$0.3;0
> 9::.$0. 3;014>.>.9::$> .;>..$0..$0.:00: >6..12>9::;...$0..9>.;
> :->.$0.:00:$>.
>
> :-><.>.9>.; ;>.$0..9$$>.$0..9>.;$> ;..$>07&>6.

related:

http://www.faqs.org/faqs/cryptography-faq/part02/

2.3. How do I present a new encryption scheme in sci.crypt?

"I just came up with this neat method of encryption. Here's some
ciphertext: FHDSIJOYW^&[EMAIL PROTECTED] Is it strong?'' Without a
doubt questions like this are the most annoying traffic on sci.crypt.

If you have come up with an encryption scheme, providing some
ciphertext from it is not adequate. Nobody has ever been impressed by
random gibberish. Any new algorithm should be secure even if the
opponent knows the full algorithm (including how any message key is
distributed) and only the private key is kept secret. There are some
systematic and unsystematic ways to take reasonably long ciphertexts
and decrypt them even without prior knowledge of the algorithm, but
this is a time-consuming and possibly fruitless exercise which most
sci.crypt readers won't bother with.

/.../





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


RE: Encryption application/NEED A HACKER TO TRY IT

2006-02-15 Thread atanas Cosmas Nkelame
Hi guys,There was an instence in our office whereby someone happened to get his eyes on information he is not supposed to.I got an idea to write a python application which ciphers and enciphers informationation (converting it to a format which only the person who changed it understands as he is the only one who has the program to decode the information).
The program will allways have to be pysicaly separated from the machine where data is kept.I'm putting here the 'encoded' text for someone to try to encipher the text or tell me what is the chance that one can encipher the text.
Here we go...>. 3;0.$0.8:;07&:00: 07&.>..&;.$> 9::.$0. .&;..9>.;.$0.3;0 ;...$0.3;0 9::.$0. 3;014>.>.9::$> .;>..$0..$0.:00: >6..12>9::;...$0..9>.; :->.$0.:00:$>.
:-><.>.9>.; ;>.$0..9$$>.$0..9>.;$> ;..$>07&>6.Regards, Atanas Cosmas NkelameDar es Salaam-Tanzania-East Africa

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

Re: file names longer than MAX_PATH under Windows 2003

2006-02-15 Thread Sergey

"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
[Sergey]

>I see from another post that CreateFile cannot open your file.
>That puts it further away from Python, although it doesn't
>explain how some other program can see the files. Can you use
>os.startfile (or its equivalent win32api.ShellExecute from
>pywin32)? Perhaps if you were to chdir to the directory in
>question you'd be able to access the file.

I found error in filename (extra backslash) and now I can open file.
But another trouble appeared: I cannot listdir so long name.
I examined posixmodule.c... There are wcsncpy with hard limit of MAX_PATH*2+5.
So... RIP, my module...


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


Re: Self-identifying functions and macro-ish behavior

2006-02-15 Thread Ben Cartwright
[EMAIL PROTECTED] wrote:
> How do I get some
> sort of macro behavior so I don't have to write the same thing over and
> over again, but which is also not neatly rolled up into a function,
> such as combining the return statements with a printing of ?


Decorators: http://www.python.org/peps/pep-0318.html


> My application has a bunch of functions that must do different things,
> then print out their names, and then each call another function before
> returning.  I'd like to have the last function call and the return in
> one statement, because if I forget to manually type it in, things get
> messed up.
>
> (ok, I'm writing a parser and I keep track of the call level with a tab
> count, which gets printed before any text messages.  So each text
> message has a tab count in accordance with how far down the parser is.
> Each time a grammar rule is entered or returned from, the tab count
> goes up or down.  If I mess up and forget to call tabsup() or tabsdn(),
> the printing gets messed up.  There are a lot of simple cheesy
> production rules, [I'm doing this largely as an exercise for myself,
> which is why I'm doing this parsing manually], so it's error-prone and
> tedious to type tabsup() each time I enter a function, and tabsdn()
> each time I return from a function, which may be from several different
> flow branches.)


def track(func):
"""Decorator to track calls to a set of functions"""
def wrapper(*args, **kwargs):
print " "*track.depth + func.__name__, args, kwargs or ""
track.depth += 1
result = func(*args, **kwargs)
track.depth -= 1
return result
return wrapper
track.depth = 0


# Then to apply the decorator to a function, e.g.:
def f(x):
return True
# Add this line somewhere after the function definition:
f = track(f)

# Alternately, if you're using Python 2.4 or newer, just define f as:
@track
def f(x):
return True


# Test it:
@track
def fact(n):
"""Factorial of n, n! = n*(n-1)*(n-2)*...*3*2"""
assert n >= 0
if n < 2:
return 1
return n * fact(n-1)
@track
def comb(n, r):
"""Choose r items from n w/out repetition, n!/(r!*(n-r)!)"""
assert n >= r
return fact(n) / fact(r) / fact(n-r)
print comb(5, 3)
# Output:
"""
comb (5, 3)
 fact (5,)
  fact (4,)
   fact (3,)
fact (2,)
 fact (1,)
 fact (3,)
  fact (2,) 
   fact (1,) 
 fact (2,) 
  fact (1,) 
10
"""

--Ben

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


Re: Which is faster? (if not b in m) or (if m.count(b) > 0)

2006-02-15 Thread Georg Brandl
Steven D'Aprano wrote:
> On Wed, 15 Feb 2006 08:44:10 +0100, Marc 'BlackJack' Rintsch wrote:
> 
>> In <[EMAIL PROTECTED]>, Farel wrote:
>> 
>>> Which is Faster in Python and Why?
>> 
>> ``if not b in m`` looks at each element of `m` until it finds `b` in it
>> and stops then.  Assuming `b` is in `m`, otherwise all elements of `m` are
>> "touched".
>> 
>> ``if m.count(b) > 0`` will always goes through all elements of `m` in the
>> `count()` method.
> 
> But the first technique executes in (relatively slow) pure Python, while
> the count method executes (relatively fast) C code. So even though count
> may do more work, it may do it faster.

Why does "not b in m" execute in pure Python? list.__contains__ is implemented
in C code as well as list.count.

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


Re: Python advocacy in scientific computation

2006-02-15 Thread Georg Brandl
Michael Tobis wrote:
> Someone asked me to write a brief essay regarding the value-add
> proposition for Python in the Fortran community. Slightly modified to
> remove a few climatology-related specifics, here it is.

Great text. Do you want to put it onto a Wiki page at wiki.python.org?

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


Re: Best way of finding terminal width/height?

2006-02-15 Thread Grant Edwards
On 2006-02-15, Joel Hedlund <[EMAIL PROTECTED]> wrote:
>> Sure.  I was going to do that yesterday, but I realized that I
>> didn't know how/where to do it.  I assume there's a link
>> somewhere at www.python.org, but I haven't had a chance to look
>> yet.
>
> It's already reported to the bug tracker:
>
> http://www.python.org/sf/210599
>
> Apparently, this has been around since 1.5.2. It's in fact
> also in the feature request PEP right now: 
>
> http://www.python.org/peps/pep-0042.html
>
> and it's listed as a "Big" project under the "Standard
> library" heading. I assume we're going to have to live with
> this for a while yet...

Oh.  

I've got no complaints about the way things work, I was just
going to suggest changing the documentation to correctly
describe the way things work. Too mundane a solution?

It seems a bit odd that we've known the documentation is wrong
for 6 years and nobody's bothered to fix it.  Or is the
documentation describing how we wish things would work
regardless of whether they work that way or not?

-- 
Grant Edwards   grante Yow!  It's today's SPECIAL!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encryption application/NEED A HACKER TO TRY IT

2006-02-15 Thread Paul Boddie
Fredrik Lundh wrote:
> "atanas Cosmas Nkelame" <[EMAIL PROTECTED]> wrote:
>
> > I'm putting here the 'encoded' text for someone to try to encipher the text
> > or tell me what is the chance that one can encipher the text.

[From an FAQ on the subject...]

> "I just came up with this neat method of encryption. Here's some
> ciphertext: FHDSIJOYW^&[EMAIL PROTECTED] Is it strong?'' Without a
> doubt questions like this are the most annoying traffic on sci.crypt.

[...]

> There are some
> systematic and unsystematic ways to take reasonably long ciphertexts
> and decrypt them even without prior knowledge of the algorithm, but
> this is a time-consuming and possibly fruitless exercise which most
> sci.crypt readers won't bother with.

And in any case, there are surely more interesting challenges of this
nature than some random person's "elite" cryptography skills:

http://www.math.ucr.edu/home/baez/voynich.html

Paul

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


RE: file names longer than MAX_PATH under Windows 2003

2006-02-15 Thread Tim Golden
[Sergey]

| "Tim Golden" <[EMAIL PROTECTED]> wrote in 
| message news:[EMAIL PROTECTED]
| [Sergey]
| 
| >I see from another post that CreateFile cannot open your file.
| >That puts it further away from Python, although it doesn't
| >explain how some other program can see the files. Can you use
| >os.startfile (or its equivalent win32api.ShellExecute from
| >pywin32)? Perhaps if you were to chdir to the directory in
| >question you'd be able to access the file.
| 
| I found error in filename (extra backslash) and now I can open file.
| But another trouble appeared: I cannot listdir so long name.
| I examined posixmodule.c... There are wcsncpy with hard limit 
| of MAX_PATH*2+5.
| So... RIP, my module...

Have a look at win32file.FindFilesIterator from the pywin32 extensions.
Maybe that can cope? (I haven't looked at the source).


import win32file
for (
  attr, created, accessed, written, size_hi, size_lo, 
  _, _, 
  filename, alt_filename
) in win32file.FindFilesIterator ("c:/temp/*"):
  print filename



TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: low level data types

2006-02-15 Thread dementrio
Thanks for the hint!

However now I have another problem - endianness (the client runs on
powerpc, the server on x86). I found that simply reversing the stuff I
recv() works, but is there any cleaner way for taking care of this?

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


Re: file names longer than MAX_PATH under Windows 2003

2006-02-15 Thread Claudio Grondi
Sergey wrote:
> "Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> [Sergey]
> 
> 
>>I see from another post that CreateFile cannot open your file.
>>That puts it further away from Python, although it doesn't
>>explain how some other program can see the files. Can you use
>>os.startfile (or its equivalent win32api.ShellExecute from
>>pywin32)? Perhaps if you were to chdir to the directory in
>>question you'd be able to access the file.
> 
> 
> I found error in filename (extra backslash) and now I can open file.
> But another trouble appeared: I cannot listdir so long name.
> I examined posixmodule.c... There are wcsncpy with hard limit of MAX_PATH*2+5.
> So... RIP, my module...
> 
> 
I don't know if and how it apply and can be of any help here, but in my 
C programs in the very past after switching from DOS to Windows long 
names a following trick solved often my problems with too long names:
   step 1:  setting the current directory to the beginning part of the 
name with a length which can be passed as a function parameter
   step 2:  usage of the remaining part of name as name passed as 
parameter to the file accessing function (relative to current directory)

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


Re: low level data types

2006-02-15 Thread Diez B. Roggisch
dementrio wrote:

> Thanks for the hint!
> 
> However now I have another problem - endianness (the client runs on
> powerpc, the server on x86). I found that simply reversing the stuff I
> recv() works, but is there any cleaner way for taking care of this?

Have you actually _read_ the struct documentation?

"""
Alternatively, the first character of the format string can be used to
indicate the byte order, size and alignment of the packed data, according
to the following table: 

...

"""

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


Re: file names longer than MAX_PATH under Windows 2003

2006-02-15 Thread Sergey

"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
[Sergey]


>Have a look at win32file.FindFilesIterator from the pywin32 extensions.
>Maybe that can cope? (I haven't looked at the source).

Yeah, it works!
THANK YOU!
(but now I must have two pieces of code, one for linux and one for windows)
Interesting, why developers of python didn't use here all power of win32 API?


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


Re: low level data types

2006-02-15 Thread Fredrik Lundh
"dementrio" wrote:

> However now I have another problem - endianness (the client runs on
> powerpc, the server on x86). I found that simply reversing the stuff I
> recv() works, but is there any cleaner way for taking care of this?

http://docs.python.org/lib/module-struct.html

(see the second table, the one that has "byte order" and "size and
alignment" in the heading)





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


Re: Win32_Process.Create -- not starting process

2006-02-15 Thread abcd
so far i tried adding

SET > c:\tmp.txt
start 
SET > c:\tmp2.txt

...and I saw both tmp files created but no python running.  I still
have to try skipping the batch file...i'll let u know.

thanks

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


Re: low level data types

2006-02-15 Thread Daniel Dittmar
dementrio wrote:
> Thanks for the hint!
> 
> However now I have another problem - endianness (the client runs on
> powerpc, the server on x86). I found that simply reversing the stuff I
> recv() works, but is there any cleaner way for taking care of this?
> 

http://docs.python.org/lib/module-struct.html
and search for "Alternatively, the first character of the format string 
can be used to indicate the byte order"

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


kwargs keyword evaluation

2006-02-15 Thread [EMAIL PROTECTED]
Ok, so here is my situation:

Let's assume I have a function that makes good use of the kwargs
parameter. It requires that there is a certain "format" for the kwargs
keywords. (I am using Django, btw). The format is like such:
"SOMEVAL__exact", etc., where SOMEVAL is some value that it parses from
the keyword.

Now, I want to call this function, specifying the kwargs. The problem
is that I want to dynamically set the kwargs. For example, I don't want
to hard code in the name like such:
function_call(name__exact="Tom")

I want to generate the keyword on the fly. So, I want to do this:
(assume someVar == 'name' for now)
keyword = someVar + "__exact"

The problem:
I need to know how to get it to use the VALUE of the keyword for the
keyword.


My thoughts:
(1) Maybe I can override the kwargs parameter by doing such:
function_call(kwargs={keyword:"Tom"})
*loud buzzer* Nope. (as expected)

(2) Maybe I can just pass it in:
function_call(keyword="Tom")
Nope! (as expected, it tries to use 'keyword' as the keyword)

What can I do?!?!?!?
I really don't want to have to hardcode a BUNCH of if statements.

Thanks in advance!

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


Embedding a binary file in a python script

2006-02-15 Thread mrstephengross
I want to find a way to embed a tar file *in* my python script, and
then use the tarfile module to extract it. That is, instead of
distributing two files (extractor.py and archive.tar) I want to be able
to distribute *one* file (extractor-with-embedded-archive.py). Is there
a way to do this? 

Thanks,
--Steve ([EMAIL PROTECTED])

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


How to tell the parent frame is a C module? (Lazy importing)

2006-02-15 Thread David Christian
Hello all,
I've been working on a lazy import module to be found here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473888

The basic idea is that a module proxy for foo is returned from an
'import foo' statement.  When an attribute of foo is accessed, or
dir(foo) is called, or a from foo import * is done, the module is
actually loaded, and the module proxy is replaced in the calling
frame.  This relies on the proxy being able to intercept __getattr__,
etc from the module and behaving appropriately.

This seems to work very well except in the case where the importing
module is a C module.

When getting the attributes of a class in C, python does the following check:

if (!PyModule_Check(m)) {
  PyErr_BadInternalCall();
return NULL;
}
d = ((PyModuleObject *)m) -> md_dict;

Which does an end-run around all of my module-related evilness.

I'm hoping that there is some way to somehow detect when the import
statement is being called from a C module, and in that case just load
the module normally.  But I can't figure out any way to detect that
from python.  In fact, in sys.frame it looks like any C modules are
simply skipped over.  I could try to detect that an intermdiate frame
is missing, I suppose

Any pointers?
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: kwargs keyword evaluation

2006-02-15 Thread Carsten Haese
On Wed, 2006-02-15 at 11:40, [EMAIL PROTECTED] wrote:
> Ok, so here is my situation:
> 
> Let's assume I have a function that makes good use of the kwargs
> parameter. It requires that there is a certain "format" for the kwargs
> keywords. (I am using Django, btw). The format is like such:
> "SOMEVAL__exact", etc., where SOMEVAL is some value that it parses from
> the keyword.
> 
> Now, I want to call this function, specifying the kwargs. The problem
> is that I want to dynamically set the kwargs. For example, I don't want
> to hard code in the name like such:
> function_call(name__exact="Tom")
> 
> I want to generate the keyword on the fly. So, I want to do this:
> (assume someVar == 'name' for now)
> keyword = someVar + "__exact"
> 
> The problem:
> I need to know how to get it to use the VALUE of the keyword for the
> keyword.
> 
> 
> My thoughts:
> (1) Maybe I can override the kwargs parameter by doing such:
> function_call(kwargs={keyword:"Tom"})
> *loud buzzer* Nope. (as expected)
> 
> (2) Maybe I can just pass it in:
> function_call(keyword="Tom")
> Nope! (as expected, it tries to use 'keyword' as the keyword)

The correct answer is behind door number 3:

some_dict = {keyword: "Tom"}
function_call(**some_dict)

HTH,

Carsten.


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


Re: kwargs keyword evaluation

2006-02-15 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Let's assume I have a function that makes good use of the kwargs
> parameter. It requires that there is a certain "format" for the kwargs
> keywords. (I am using Django, btw). The format is like such:
> "SOMEVAL__exact", etc., where SOMEVAL is some value that it parses from
> the keyword.
>
> Now, I want to call this function, specifying the kwargs. The problem
> is that I want to dynamically set the kwargs. For example, I don't want
> to hard code in the name like such:
> function_call(name__exact="Tom")
>
> I want to generate the keyword on the fly. So, I want to do this:
> (assume someVar == 'name' for now)
> keyword = someVar + "__exact"
>
> The problem:
> I need to know how to get it to use the VALUE of the keyword for the
> keyword.
>
> My thoughts:
> (1) Maybe I can override the kwargs parameter by doing such:
> function_call(kwargs={keyword:"Tom"})
> *loud buzzer* Nope. (as expected)

function_call(**{keyword:"Tom"})





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


Re: kwargs keyword evaluation

2006-02-15 Thread [EMAIL PROTECTED]
Well, I knew about the apply() function, but totally forgot to use it.
It worked.

Example:
apply(function_call, (), {keyword: "Tom"})

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


Re: file names longer than MAX_PATH under Windows 2003

2006-02-15 Thread Sergey

"Claudio Grondi" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Sergey wrote:
> I don't know if and how it apply and can be of any help here, but in my C 
> programs in the very past after switching from DOS to 
> Windows long names a following trick solved often my problems with too long 
> names:
>   step 1:  setting the current directory to the beginning part of the name 
> with a length which can be passed as a function 
> parameter
>   step 2:  usage of the remaining part of name as name passed as parameter to 
> the file accessing function (relative to current 
> directory)

It seems this method doesn't help here.


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


Re: Embedding a binary file in a python script

2006-02-15 Thread Rene Pijlman
mrstephengross:
>I want to find a way to embed a tar file *in* my python script, and
>then use the tarfile module to extract it. That is, instead of
>distributing two files (extractor.py and archive.tar) I want to be able
>to distribute *one* file (extractor-with-embedded-archive.py). Is there
>a way to do this? 

I guess you can uuencode your tar file, and put the result in a multiline
string. See module 'uu'.

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding a binary file in a python script

2006-02-15 Thread Fredrik Lundh
"mrstephengross" wrote:

> I want to find a way to embed a tar file *in* my python script, and
> then use the tarfile module to extract it. That is, instead of
> distributing two files (extractor.py and archive.tar) I want to be able
> to distribute *one* file (extractor-with-embedded-archive.py). Is there
> a way to do this?

I'm not sure I understand why you think you need to embed a tarfile
(why not just embed the actual files?), but here's an outline:

$ echo hello >hello.txt
$ echo world >world.txt
$ tar cvfz archive.tar hello.txt world.txt
hello.txt
world.txt
$ ls -l archive.tar
-rw-r--r--  1 effbot effbot 151 2006-02-15 17:52 archive.tar

$ python
>>> import base64, sys
>>> base64.encode(open("archive.tar", "rb"), sys.stdout)
H4sIAPlc80MAA+3TwQqDMAzG8Z73FH2CkWqbPs/GFA+FguvYHn8qQ3aaJ3XC/3cJJJeQ8HVNSvlc
XsWsRwbq/VhdDPJdP9Q4qaPXoFIPfVdVTo2VFXeaPe7l0ltrmra95h9XWJofVDf+/7T3FtjLM/fp
9lf5D1P+fST/W5j+T/4BAAAO6w1uw+KBACgAAA==
>>> ^D

$ python
>>> import base64, cStringIO, tarfile
>>> f = cStringIO.StringIO(base64.decodestring("""
... H4sIAPlc80MAA+3TwQqDMAzG8Z73FH2CkWqbPs/GFA+FguvYHn8qQ3aaJ3XC/3cJJJeQ8HVNSvlc
... XsWsRwbq/VhdDPJdP9Q4qaPXoFIPfVdVTo2VFXeaPe7l0ltrmra95h9XWJofVDf+/7T3FtjLM/fp
... 9lf5D1P+fST/W5j+T/4BAAAO6w1uw+KBACgAAA==
... """))
>>> f

>>> tar = tarfile.TarFile.gzopen("dummy", fileobj=f)
>>> tar.list()
-rw-r--r-- effbot/effbot  6 2006-02-15 17:51:36 hello.txt
-rw-r--r-- effbot/effbot  6 2006-02-15 17:51:41 world.txt
>>> tar.extractfile("hello.txt").read()
'hello\n'

hope this helps!





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


Clarity: GIL, processes and CPUs etc

2006-02-15 Thread adsheehan
I have been reading many of the posting on the GIL and impact on
threading etc.
I have found is confusing and would welcome some clarity on this.

I understand that embedding the interpreter in a C/C++ application
limits it to one CPU.
If the application is multi-threaded (system threads) in will not use
additional CPUs as the interpreter is tied to one CPU courtesy of the
GIL.
True or False?

I understand that forking or running multiple process instances of the
above application would make use of multiple CPUs. This is because each
process would have its own interpreter and GIL that is independent of
any other process.
True or False?

Can anyone clarify the above?

Thanks
A

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


Re: Embedding an Application in a Web browser

2006-02-15 Thread Magnus Lycka
bruno at modulix wrote:
> rodmc wrote:
> 
>>Is it possible to embed a Python application within Internet explorer?
> 
> No. Nor in any other browser (except from Grail, but I think this
> doesn't count).

This is simply not true!

Python can work as a Windows scripting language just as VB Script.
That means that IE can use Python just as it can use JScript or
VB Script for client side scripting in the browser.

For instance, see here:
http://www.4guysfromrolla.com/webtech/082201-1.shtml

Another issue is whether this was advisable from a security point
of view... Python isn't written to be safe. I don't want Python
client side scripting enabled in my browser... (Not that I use
IE when I can avoid it...)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: kwargs keyword evaluation

2006-02-15 Thread [EMAIL PROTECTED]
Thanks. That also worked. I will use that, since apply() is deprecated
as of 2.3.

Thanks!
-Tom

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


Re: Embedding a binary file in a python script

2006-02-15 Thread mrstephengross
Ok, this is a neat idea... The uu module deals with files though, not
strings. Is there a way in python to make a string act like a file
handle?

Example:

my_string = "uu-encoded-stuf.."
my_out_file_handle = ?? # What should this variable look like?
import uu
uu.decode(my_string, my_out_file_handle)
import tarfile
tarfile.open(my_out_file_handle)

Thanks again,
--Steve ([EMAIL PROTECTED])

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


Re: Embedding a binary file in a python script

2006-02-15 Thread mrstephengross
Ok, this looks really cool, but can you explain a little more
step-by-step what's going on? In the end, I need to have a single
python script that (1) contains the archive and (2) can extract that
archive. The example you've given is interesting, but it's not clear to
me how to create the actual python script to do it all.

Thanks again,
--Steve ([EMAIL PROTECTED])

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


Re: Embedding a binary file in a python script

2006-02-15 Thread Diez B. Roggisch
mrstephengross wrote:

> Ok, this is a neat idea... The uu module deals with files though, not
> strings. Is there a way in python to make a string act like a file
> handle?

(c)?StringIO

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


Re: Best way of finding terminal width/height?

2006-02-15 Thread Kent Johnson
Grant Edwards wrote:
> I've got no complaints about the way things work, I was just
> going to suggest changing the documentation to correctly
> describe the way things work. Too mundane a solution?

Submit a patch, it's quick and easy and fun:
http://docs.python.org/about.html

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


Re: Embedding a binary file in a python script

2006-02-15 Thread Rene Pijlman
mrstephengross:
>Ok, this looks really cool, but can you explain a little more
>step-by-step what's going on? 

What happened to "Hey thanks, I'll look into that" :-(

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >