Re: problems with shelve(), collections.defaultdict, self

2012-02-11 Thread 7stud
On Feb 11, 10:56 am, Ian Kelly  wrote:
> On Sat, Feb 11, 2012 at 10:54 AM, Ian Kelly  wrote:
> > class Dog(dict):
>
> >    def __missing__(self):
> >        return 0
>
> Sorry, that should have been:
>
> class Dog(dict):
>
>     def __missing__(self, key):
>         return 0
>
> Cheers,
> Ian

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


Re: problems with shelve(), collections.defaultdict, self

2012-02-10 Thread 7stud
On Feb 10, 7:52 pm, 7stud <7s...@excite.com> wrote:

I don't know if this helps, but I notice when I initially do this:

shelve.open('data22')

the file is saved as 'data22.db'.   But on subsequent calls to
shelve.open(), if I use the file name 'data22.db', I get a different
error:

--output:--

 defaultdict(, {'Joe': 30})
Traceback (most recent call last):
  File "3.py", line 95, in 
d.load()
  File "3.py", line 86, in load
my_shelve = shelve.open('data22.db')
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/
python3.2/shelve.py", line 232, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/
python3.2/shelve.py", line 216, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol,
writeback)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/
python3.2/dbm/__init__.py", line 83, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined



The code that produced that error:



import collections as c
import shelve

class Dog(c.defaultdict):
def __init__(self):
super().__init__(int, Joe=30)
print('', self)

def save(self):
my_shelve = shelve.open('data22')
my_shelve['dd'] = self
my_shelve.close()

def load(self):
my_shelve = shelve.open('data22.db')
data = my_shelve['dd']
my_shelve.close()

print(data)


d = Dog()
d.save()
d.load()


I'm using python 3.2.2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems with shelve(), collections.defaultdict, self

2012-02-10 Thread 7stud
On Feb 10, 7:48 pm, 7stud <7s...@excite.com> wrote:
>
> But I cannot get a class that inherits from collections.defaultdict to
> shelve itself:
>
> import collections as c
> import shelve
>
> class Dog(c.defaultdict):
>     def __init__(self):
>         super().__init__(int, Joe=0)
>         print('', self)

Whoops.  I changed:

super().__init__(int, Joe=0)

to:

super().__init__(int, Joe=30)

hence this output..

> --output:--
>
>  defaultdict(, {'Joe': 30})
-- 
http://mail.python.org/mailman/listinfo/python-list


problems with shelve(), collections.defaultdict, self

2012-02-10 Thread 7stud
The following code demonstrates that a collections.defaultdict is
shelve worthy:


import shelve
import collections as c


dd = c.defaultdict(int)
dd["Joe"] = 3
print(dd)

my_shelve = shelve.open('data.shelve')
my_shelve['strike_record'] = dd
my_shelve.close()

my_shelve = shelve.open('data.shelve')
data = my_shelve['strike_record']
my_shelve.close()

dd.clear()
dd.update(data)
print(dd)

--output:--
defaultdict(, {'Joe': 3})
defaultdict(, {'Joe': 3})


And the following code demonstrates that a class that inherits from
dict can shelve itself:

import collections as c
import shelve

class Dog(dict):
def __init__(self):
super().__init__(Joe=1)
print('', self)

def save(self):
my_shelve = shelve.open('data22.shelve')
my_shelve['x'] = self
my_shelve.close()

def load(self):
my_shelve = shelve.open('data22.shelve')
data = my_shelve['x']
my_shelve.close()

print(data)


d = Dog()
d.save()
d.load()

--output:--
 {'Joe': 1}
{'Joe': 1}


But I cannot get a class that inherits from collections.defaultdict to
shelve itself:


import collections as c
import shelve

class Dog(c.defaultdict):
def __init__(self):
super().__init__(int, Joe=0)
print('', self)

def save(self):
my_shelve = shelve.open('data22.shelve')
my_shelve['dd'] = self
my_shelve.close()

def load(self):
my_shelve = shelve.open('data22.shelve')
data = my_shelve['dd']
my_shelve.close()

print(data)


d = Dog()
d.save()
d.load()

--output:--

 defaultdict(, {'Joe': 30})
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/
python3.2/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'dd'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "3.py", line 95, in 
d.load()
  File "3.py", line 87, in load
data = my_shelve['dd']
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/
python3.2/shelve.py", line 114, in __getitem__
value = Unpickler(f).load()
TypeError: __init__() takes exactly 1 positional argument (2 given)



I deleted all *.shelve.db files between program runs.  I can't figure
out what I'm doing wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing lxml ?

2009-11-11 Thread 7stud
On Nov 11, 5:59 pm, 7stud  wrote:
>
> 1) Maybe the installation instructions for mac osx should read:
>
> 
> Installation Instructions
> 
> 
> MAC OS X:
> We're not sure how mac osx works with easy_install.  Apple's system
> installations of libxml and libxslt are pretty bad--and they are
> difficult to upgrade.  As a result, the following instructions may or
> may not work for you...
> 
>
> 2) Stop proclaiming that lxml is cross platform and/or stop
> recommending easy_install.
>
> 3) Don't split up relevant installation instructions over two web
> pages and then bury the link connecting the two web pages at the
> bottom of one of the pages.
>


...and most importantly:

4) The path to easy_install may not get added to your PATH environment
variable, so using the full path to easy_install might be necessary
when issuing the easy_install command.  If you get an error that says:

easy_install: command not found

then you will need to use the full path to easy_install.  Some
installs will put easy_install here:

/Library/Frameworks/Python.framework/
Versions/2.6/bin/easy_install

Others will put it here:



If can't locate easy_install in any of those directories, you can
locate easy_install using the find command:

find / -name easy_install



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


Re: installing lxml ?

2009-11-11 Thread 7stud
On Nov 11, 1:37 pm, Terry Reedy  wrote:
> 7stud wrote:
> > On Nov 11, 7:37 am, "Diez B. Roggisch"  wrote:
> >> And third,
> >> there are limits to what extend one can anticipate the ineptness of
>
> Calling you inept was unnecessary, but
>
> >> others to read. The page you cite from starts with:
>
> You wrote
> "
> I'm trying to install lxml, but I can't figure out the installation
> instructions.  Here:
>
> http://codespeak.net/lxml/installation.html
> "
>
> >>For special installation instructions regarding MS Windows and
> >> MacOS-X, see below.
>
> and that page indeed begins with the words above.
>


> >> And below you find this link:
>
> >>http://codespeak.net/lxml/build.html#building-lxml-on-macos-x
>
> >> Which contains the proper command
>
> >>STATIC_DEPS=true sudo easy_install lxml
>
> And this is also true.
>

Is it?  First, that in fact was not the proper command.  I posted the
actual command I had to issue in my previous post:

$ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/
Versions/
2.6/bin/easy_install lxml


Shall I continue?  Here is what the top of the web page that contains
the installation instructions looks like (with my comments inserted in
the text):

=

For special installation instructions regarding MS Windows and MacOS-
X, see below.

<<<Ok, now I'm scrolling down looking for the *installation
instructions*.>>>

1 Requirements
2 Installation
3 Installation in ActivePython
4 Building lxml from sources
5 MS Windows
6 MacOS-X


Requirements

You need Python 2.3 or later.
Unless you are using a static binary distribution (e.g. a Windows
binary egg from PyPI), you need to install libxml2 and libxslt, in
particular: libxml 2.6.21 or later. It can be found here:
http://xmlsoft.org/downloads.html
If you want to use XPath, do not use libxml2 2.6.27. We recommend
libxml2 2.7.2 or later.
libxslt 1.1.15 or later. It can be found here: 
http://xmlsoft.org/XSLT/downloads.html
Newer versions generally contain less bugs and are therefore
recommended. XML Schema support is also still worked on in libxml2, so
newer versions will give you better complience with the W3C spec.

<<<***Ok, I better read the requirements.  Uhg, those dependencies
look ugly.  Things are looking doubtful at this point.  Back to
looking for those special installation instructions for mac os x...>>>

Installation

Get the easy_install tool and run the following as super-user (or
administrator):

easy_install lxml

On MS Windows, the above will install the binary builds that we
provide. If there is no binary build of the latest release yet, please
search PyPI for the last release that has them and pass that version
to easy_install like this:
easy_install lxml==2.2.2

On Linux (and most other well-behaved operating systems), easy_install
will manage to build the source distribution as long as libxml2 and
libxslt are properly installed, including development packages, i.e.
header files, etc. Use your package management tool to look for
packages like libxml2-dev or libxslt-devel if the build fails, and
make sure they are installed.

On MacOS-X, use the following to build the source distribution, and
make sure you have a working Internet connection, as this will
download libxml2 and libxslt in order to build them:
STATIC_DEPS=true easy_install lxml

<<<***Ah, hah.  There are the special installation instructions for
mac os x.  I'm ready to go.  Uh oh, what the heck is the easy_install
tool?  Oh, that's a link hiding behind the bolded text(hmm...this
website has some usability issues). Time goes by, tetonic plates
shift...Ok, I've got the easy_install tool installed.  Let's install
lxml now.>>

> > Your characterization of that web page is so fraudulent that I can
> > only say one thing in response:  You are a damn liar.
>
> So this makes no sense.
>


If someone were viewing the web page containing the installation
instructions with a screen that was 2 feet high, AND they happened to
see the additional section buried at the bottom of the page, AND they
chose to skip over instructions in the installation section for some
reason, the first part of the section at the bottom of the page reads:

===
MacOS-X

A macport of lxml is available. Try port install py25-lxml.

If you want to use a more recent lxml release, you may have to build
it yourself. Apple doesn't help here, as the system libraries of
libxml2 and libxslt installed under MacOS-X are horribly outdated, and
***updating them is everything but easy***. In any case, you cannot
run lxml 2.x with the system provided libraries, so you have to use
newer libraries...
===

...which would probably make their eyes roll back in their head, or
dissuade them from readi

Re: installing lxml ?

2009-11-11 Thread 7stud
On Nov 11, 7:37 am, "Diez B. Roggisch"  wrote:
> And third,
> there are limits to what extend one can anticipate the ineptness of
> others to read. The page you cite from starts with:
>
>    For special installation instructions regarding MS Windows and
> MacOS-X, see below.
>
> And below you find this link:
>
>    http://codespeak.net/lxml/build.html#building-lxml-on-macos-x
>
> Which contains the proper command
>
>    STATIC_DEPS=true sudo easy_install lxml
>


Your characterization of that web page is so fraudulent that I can
only say one thing in response:  You are a damn liar.


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


Re: installing lxml ?

2009-11-11 Thread 7stud
On Nov 11, 6:31 am, Jussi Piitulainen 
wrote:
> 7stud writes:
> > I'm trying to install lxml, but I can't figure out the installation
> > instructions.  Here:
> ...
> > My os is mac os x 10.4.11.   But this:
>
> > STATIC_DEPS=true easy_install lxml
>
> > is not a valid command:
>
> > $ sudo STATIC_DEPS=true easy_install lxml
> > Password:
> > sudo: STATIC_DEPS=true: command not found
>
> Maybe
>
>    STATIC_DEPS=true sudo easy_install lxml
>
> And be running Bash or some other Bourne type shell.
>

That worked. (The Terminal app on my mac uses bash by default.)

Unfortunately, easy_install was not able to install lxml!  Here is the
output:

---
$ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found
$ STATIC_DEPS=true sudo /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.2.3
Downloading http://codespeak.net/lxml/lxml-2.2.3.tgz
Processing lxml-2.2.3.tgz
Running lxml-2.2.3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-
r2obQa/lxml-2.2.3/egg-dist-tmp-7v5A1n
Building lxml version 2.2.3.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/bin/
easy_install", line 8, in 
load_entry_point('setuptools==0.6c11', 'console_scripts',
'easy_install')()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 1712, in main
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 1700, in with_ei_usage
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 1716, in 
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 211, in run
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 446, in easy_install
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 476, in install_item
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 655, in install_eggs
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 930, in build_and_install
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 919, in run_setup
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
sandbox.py", line 62, in run_setup
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
sandbox.py", line 105, in run
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
sandbox.py", line 64, in 
  File "setup.py", line 119, in 

  File "/tmp/easy_install-r2obQa/lxml-2.2.3/setupinfo.py", line 51, in
ext_modules
TypeError: build_libxml2xslt() got an unexpected keyword argument
'libiconv_version'
-- 
http://mail.python.org/mailman/listinfo/python-list


installing lxml ?

2009-11-11 Thread 7stud
I'm trying to install lxml, but I can't figure out the installation
instructions.  Here:

http://codespeak.net/lxml/installation.html

it says:

1) Get the easy_install tool.

Ok, I went to the easy_install website, downloaded, and installed it.
The last two lines of the output during installation said this:

Installing easy_install script to /Library/Frameworks/Python.framework/
Versions/2.6/bin
Installing easy_install-2.6 script to /Library/Frameworks/
Python.framework/Versions/2.6/bin


2) ...run the following as super-user (or administrator):

easy_install lxml

On MS Windows, the above will install the binary builds that we
provide. If there is no binary build of the latest release yet, please
search PyPI for the last release that has them and pass that version
to easy_install like this:
easy_install lxml==2.2.2

On Linux (and most other well-behaved operating systems), easy_install
will manage to build the source distribution as long as libxml2 and
libxslt are properly installed, including development packages, i.e.
header files, etc. Use your package management tool to look for
packages like libxml2-dev or libxslt-devel if the build fails, and
make sure they are installed.

On MacOS-X, use the following to build the source distribution, and
make sure you have a working Internet connection, as this will
download libxml2 and libxslt in order to build them:
STATIC_DEPS=true easy_install lxml

---

My os is mac os x 10.4.11.   But this:

STATIC_DEPS=true easy_install lxml

is not a valid command:

$ sudo STATIC_DEPS=true easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found

In any case, if I do this:

$ sudo easy_install lxml
sudo: easy_install: command not found

In other words, when I installed easy_install it did not add anything
to my PATH which points to the installation directory mentioned during
installation:

Installing easy_install script to /Library/Frameworks/Python.framework/
Versions/2.6/bin

Ok, so I need to use the full path to the easy_install program (which
is not mentioned ANYWHERE in the installation instructions), i.e.

/Library/Frameworks/Python.framework/Versions/2.6/bin/easy_install

...but this still isn't going to work:

$ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found


So what the heck is going on??

Attention developers: you may be one of the best programmers in the
world, but if you can't convey how to use your software to the average
user, then you are the equivalent of one of the worst programmers on
the planet.






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


Re: Function to apply superset of arguments to a function

2009-09-09 Thread 7stud
On Sep 9, 10:45 am, Andrey Fedorov  wrote:
> Hi all,
>
> I've written a function [1] called apply_some which takes a set of
> keywords arguments, filters only those a function is expecting, and
> calls the function with only those arguments. This is meant to
> suppress TypeErrors - a way to abstract the logic which checks what
> arguments a passed-in function accepts.
>
> For example:
>
> > def foo(x=1, y=2):
> >    return (x,y)
>
> > apply_some(foo, y=0, z="hi") // calls foo(y=0)
> > -> (1,0)
>
> I'd like to expand this to fill undefined arguments with None, but
> before I do, does anyone know of any packages/libraries which either
> do something similar or would make this code cleaner?
>
> Cheers,
> Andrey
>
> 1.http://gist.github.com/183375

It sounds like all you are doing is moving type checking out of the
original function and into another function.  In scripting languages,
like python, type checking is frowned upon.  The accepted idiom is to
use try-except.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Something confusing about non-greedy reg exp match

2009-09-07 Thread 7stud
On Sep 6, 8:46 pm, "gburde...@gmail.com"  wrote:
> If I do this:
>
> import re
> a=re.search(r'hello.*?money',  'hello how are you hello funny money')
>
> I would expect a.group(0) to be "hello funny money", since .*? is a
> non-greedy match. But instead, I get the whole sentence, "hello how
> are you hello funny money".
>
> Is this expected behavior?

Yes.  search() finds the *first* match.  The non-greedy quantifier
does not transform search() into a function that finds all possible
matches and then picks the shortest one.  Instead, the non-greedy
quantifier causes search() to return the shortest possible first match
(v. the default which is the "longest possible first match").  In your
case, there is only one possible first match, so the non-greedy
quantifier does nothing.

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


Re: simple string question

2009-09-06 Thread 7stud
On Sep 6, 11:29 pm, "jwither"  wrote:
> Given a string (read from a file) which contains raw escape sequences,
> (specifically, slash n), what is the best way to convert that to a parsed
> string, where the escape sequence has been replaced (specifically, by a
> NEWLINE token)?
>
> James Withers

1) What is a "parsed string"?
2) What is a "NEWLINE token"?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: efficiently splitting up strings based on substrings

2009-09-06 Thread 7stud
On Sep 6, 1:23 am, 7stud  wrote:
> On Sep 6, 1:14 am, 7stud  wrote:
>
>
>
> > On Sep 5, 5:29 pm, per  wrote:
>
> > > On Sep 5, 7:07 pm, "Rhodri James"  wrote:
>
> > > > On Sat, 05 Sep 2009 23:54:08 +0100, per  wrote:
> > > > > On Sep 5, 6:42 pm, "Rhodri James"  wrote:
> > > > >> On Sat, 05 Sep 2009 22:54:41 +0100, per  wrote:
> > > > >> > I'm trying to efficiently "split" strings based on what substrings
> > > > >> > they are made up of.
> > > > >> > i have a set of strings that are comprised of known substrings.
> > > > >> > For example, a, b, and c are substrings that are not identical to 
> > > > >> > each
> > > > >> > other, e.g.:
> > > > >> > a = "0" * 5
> > > > >> > b = "1" * 5
> > > > >> > c = "2" * 5
>
> > > > >> > Then my_string might be:
>
> > > > >> > my_string = a + b + c
>
> > > > >> > i am looking for an efficient way to solve the following problem.
> > > > >> > suppose i have a short
> > > > >> > string x that is a substring of my_string.  I want to "split" the
> > > > >> > string x into blocks based on
> > > > >> > what substrings (i.e. a, b, or c) chunks of s fall into.
>
> > > > >> > to illustrate this, suppose x = "00111". Then I can detect where x
> > > > >> > starts in my_string
> > > > >> > using my_string.find(x).  But I don't know how to partition x into
> > > > >> > blocks depending
> > > > >> > on the substrings.  What I want to get out in this case is: "00",
> > > > >> > "111".  If x were "00122",
> > > > >> > I'd want to get out "00","1", "22".
>
> > > > >> > is there an easy way to do this?  i can't simply split x on a, b, 
> > > > >> > or c
> > > > >> > because these might
> > > > >> > not be contained in x.  I want to avoid doing something inefficient
> > > > >> > like looking at all substrings
> > > > >> > of my_string etc.
>
> > > > >> > i wouldn't mind using regular expressions for this but i cannot 
> > > > >> > think
> > > > >> > of an easy regular
> > > > >> > expression for this problem.  I looked at the string module in the
> > > > >> > library but did not see
> > > > >> > anything that seemd related but i might have missed it.
>
> > > > >> I'm not sure I understand your question exactly.  You seem to imply
> > > > >> that the order of the substrings of x is consistent.  If that's the
> > > > >> case, this ought to help:
>
> > > > >> >>> import re
> > > > >> >>> x = "00122"
> > > > >> >>> m = re.match(r"(0*)(1*)(2*)", x)
> > > > >> >>> m.groups()
>
> > > > >> ('00', '1', '22')>>> y = "00111"
> > > > >> >>> m = re.match(r"(0*)(1*)(2*)", y)
> > > > >> >>> m.groups()
>
> > > > >> ('00', '111', '')
>
> > > > >> You'll have to filter out the empty groups for yourself, but that's
> > > > >> no great problem.
>
> > > > > The order of the substrings is consistent but what if it's not 0, 1, 2
> > > > > but a more complicated string? e.g.
>
> > > > > a = 1030405, b = 1babcf, c = fUUIUP
>
> > > > > then the substring x might be 4051ba, in which case using a regexp
> > > > > with (1*) will not work since both a and b substrings begin with the
> > > > > character 1.
>
> > > > Right.  This looks approximately nothing like what I thought your
> > > > problem was.  Would I be right in thinking that you want to match
> > > > substrings of your potential "substrings" against the string x?
>
> > > > I'm sufficiently confused that I think I'd like to see what your
> > > > use case a

Re: efficiently splitting up strings based on substrings

2009-09-06 Thread 7stud
On Sep 6, 1:14 am, 7stud  wrote:
> On Sep 5, 5:29 pm, per  wrote:
>
>
>
> > On Sep 5, 7:07 pm, "Rhodri James"  wrote:
>
> > > On Sat, 05 Sep 2009 23:54:08 +0100, per  wrote:
> > > > On Sep 5, 6:42 pm, "Rhodri James"  wrote:
> > > >> On Sat, 05 Sep 2009 22:54:41 +0100, per  wrote:
> > > >> > I'm trying to efficiently "split" strings based on what substrings
> > > >> > they are made up of.
> > > >> > i have a set of strings that are comprised of known substrings.
> > > >> > For example, a, b, and c are substrings that are not identical to 
> > > >> > each
> > > >> > other, e.g.:
> > > >> > a = "0" * 5
> > > >> > b = "1" * 5
> > > >> > c = "2" * 5
>
> > > >> > Then my_string might be:
>
> > > >> > my_string = a + b + c
>
> > > >> > i am looking for an efficient way to solve the following problem.
> > > >> > suppose i have a short
> > > >> > string x that is a substring of my_string.  I want to "split" the
> > > >> > string x into blocks based on
> > > >> > what substrings (i.e. a, b, or c) chunks of s fall into.
>
> > > >> > to illustrate this, suppose x = "00111". Then I can detect where x
> > > >> > starts in my_string
> > > >> > using my_string.find(x).  But I don't know how to partition x into
> > > >> > blocks depending
> > > >> > on the substrings.  What I want to get out in this case is: "00",
> > > >> > "111".  If x were "00122",
> > > >> > I'd want to get out "00","1", "22".
>
> > > >> > is there an easy way to do this?  i can't simply split x on a, b, or 
> > > >> > c
> > > >> > because these might
> > > >> > not be contained in x.  I want to avoid doing something inefficient
> > > >> > like looking at all substrings
> > > >> > of my_string etc.
>
> > > >> > i wouldn't mind using regular expressions for this but i cannot think
> > > >> > of an easy regular
> > > >> > expression for this problem.  I looked at the string module in the
> > > >> > library but did not see
> > > >> > anything that seemd related but i might have missed it.
>
> > > >> I'm not sure I understand your question exactly.  You seem to imply
> > > >> that the order of the substrings of x is consistent.  If that's the
> > > >> case, this ought to help:
>
> > > >> >>> import re
> > > >> >>> x = "00122"
> > > >> >>> m = re.match(r"(0*)(1*)(2*)", x)
> > > >> >>> m.groups()
>
> > > >> ('00', '1', '22')>>> y = "00111"
> > > >> >>> m = re.match(r"(0*)(1*)(2*)", y)
> > > >> >>> m.groups()
>
> > > >> ('00', '111', '')
>
> > > >> You'll have to filter out the empty groups for yourself, but that's
> > > >> no great problem.
>
> > > > The order of the substrings is consistent but what if it's not 0, 1, 2
> > > > but a more complicated string? e.g.
>
> > > > a = 1030405, b = 1babcf, c = fUUIUP
>
> > > > then the substring x might be 4051ba, in which case using a regexp
> > > > with (1*) will not work since both a and b substrings begin with the
> > > > character 1.
>
> > > Right.  This looks approximately nothing like what I thought your
> > > problem was.  Would I be right in thinking that you want to match
> > > substrings of your potential "substrings" against the string x?
>
> > > I'm sufficiently confused that I think I'd like to see what your
> > > use case actually is before I make more of a fool of myself.
>
> > > --
> > > Rhodri James *-* Wildebeest Herder to the Masses
>
> > it's exactly the same problem, except there are no constraints on the
> > strings.  so the problem is, like you say, matching the substrings
> > against the string x. in other words, finding out where x "aligns&quo

Re: efficiently splitting up strings based on substrings

2009-09-06 Thread 7stud
On Sep 5, 5:29 pm, per  wrote:
> On Sep 5, 7:07 pm, "Rhodri James"  wrote:
>
>
>
> > On Sat, 05 Sep 2009 23:54:08 +0100, per  wrote:
> > > On Sep 5, 6:42 pm, "Rhodri James"  wrote:
> > >> On Sat, 05 Sep 2009 22:54:41 +0100, per  wrote:
> > >> > I'm trying to efficiently "split" strings based on what substrings
> > >> > they are made up of.
> > >> > i have a set of strings that are comprised of known substrings.
> > >> > For example, a, b, and c are substrings that are not identical to each
> > >> > other, e.g.:
> > >> > a = "0" * 5
> > >> > b = "1" * 5
> > >> > c = "2" * 5
>
> > >> > Then my_string might be:
>
> > >> > my_string = a + b + c
>
> > >> > i am looking for an efficient way to solve the following problem.
> > >> > suppose i have a short
> > >> > string x that is a substring of my_string.  I want to "split" the
> > >> > string x into blocks based on
> > >> > what substrings (i.e. a, b, or c) chunks of s fall into.
>
> > >> > to illustrate this, suppose x = "00111". Then I can detect where x
> > >> > starts in my_string
> > >> > using my_string.find(x).  But I don't know how to partition x into
> > >> > blocks depending
> > >> > on the substrings.  What I want to get out in this case is: "00",
> > >> > "111".  If x were "00122",
> > >> > I'd want to get out "00","1", "22".
>
> > >> > is there an easy way to do this?  i can't simply split x on a, b, or c
> > >> > because these might
> > >> > not be contained in x.  I want to avoid doing something inefficient
> > >> > like looking at all substrings
> > >> > of my_string etc.
>
> > >> > i wouldn't mind using regular expressions for this but i cannot think
> > >> > of an easy regular
> > >> > expression for this problem.  I looked at the string module in the
> > >> > library but did not see
> > >> > anything that seemd related but i might have missed it.
>
> > >> I'm not sure I understand your question exactly.  You seem to imply
> > >> that the order of the substrings of x is consistent.  If that's the
> > >> case, this ought to help:
>
> > >> >>> import re
> > >> >>> x = "00122"
> > >> >>> m = re.match(r"(0*)(1*)(2*)", x)
> > >> >>> m.groups()
>
> > >> ('00', '1', '22')>>> y = "00111"
> > >> >>> m = re.match(r"(0*)(1*)(2*)", y)
> > >> >>> m.groups()
>
> > >> ('00', '111', '')
>
> > >> You'll have to filter out the empty groups for yourself, but that's
> > >> no great problem.
>
> > > The order of the substrings is consistent but what if it's not 0, 1, 2
> > > but a more complicated string? e.g.
>
> > > a = 1030405, b = 1babcf, c = fUUIUP
>
> > > then the substring x might be 4051ba, in which case using a regexp
> > > with (1*) will not work since both a and b substrings begin with the
> > > character 1.
>
> > Right.  This looks approximately nothing like what I thought your
> > problem was.  Would I be right in thinking that you want to match
> > substrings of your potential "substrings" against the string x?
>
> > I'm sufficiently confused that I think I'd like to see what your
> > use case actually is before I make more of a fool of myself.
>
> > --
> > Rhodri James *-* Wildebeest Herder to the Masses
>
> it's exactly the same problem, except there are no constraints on the
> strings.  so the problem is, like you say, matching the substrings
> against the string x. in other words, finding out where x "aligns" to
> the ordered substrings abc, and then determine what chunk of x belongs
> to a, what chunk belongs to b, and what chunk belongs to c.
>
> so in the example i gave above, the substrings are: a = 1030405, b =
> 1babcf, c = fUUIUP, so abc = 10304051babcffUUIUP
>
> given a substring like 4051ba, i'd want to split it into the chunks a,
> b, and c. in this case, i'd want the result to be: ["405", "1ba"] --
> i.e. "405" is the chunk of x that belongs to a, and "1ba" the chunk
> that belongs to be. in this case, there are no chunks of c.  if x
> instead were "4051babcffUU", the right output is: ["405", "1babcf",
> "fUU"], which are the corresponding chunks of a, b, and c that make up
> x respectively.
>
> i'm not sure how to approach this. any ideas/tips would be greatly
> appreciated. thanks again.


a = "1030405"
b = "1babcf"
c = "fUUIUP"
abc = "10304051babcffUUIUP"
data = "4051babcffU"

data_start = abc.find(data)
b_start = abc.find(b) - data_start
c_start = abc.find(c) - data_start

print data[:b_start]
print data[b_start:c_start]
print data[c_start:]

--output:--
405
1babcf
fU

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


Re: Sending email

2009-08-30 Thread 7stud
On Aug 28, 8:18 am, Fencer 
wrote:
> 7stud wrote:
>
> [snip]
>
> Thanks for your reply. After consulting the sysadmins here I was able to
> get it to work.
>
> - Fencer


Ok, but how about posting your code so that a future searcher will not
be left screaming, "WHAT THE EFF WAS THE SOLUTION!!"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending email

2009-08-28 Thread 7stud
On Aug 28, 2:37 am, Fencer 
wrote:
> Hello, I'm using Python version 2.6.2 and I discovered it has built-in
> libraries for sending email (imports smtplib and email). On the web I
> discovered how to send mail through smtp.gmail.com:
>
> mail_server = smtplib.SMTP()
>
> mail_server.connect('smtp.gmail.com')
> mail_server.ehlo()
> mail_server.starttls()
> mail_server.ehlo()
> mail_server.login('username', 'password')
>
> msg = MIMEText('Some message text')
> msg['Subject'] = 'Some subject'
> msg['From'] = 'Mr Underhill'
> msg['To'] = 'someemailaddress'
>
> me = 'myemailaddress'
> mail_server.sendmail(me, ['someemailaddress'], msg.as_string())
>
> That seems to work just fine but for the messages I will be sending I
> don't want to use my private GMail account.
> We have an SMTP server at work, and I checked its settings in the
> Thunderbird mail client and it's using SSL over port 465, so a bit
> different from how GMail's SMTP server is configured in Thunderbird.
>
> I altered my code slightly to account for this:
> mail_server = smtplib.SMTP_SSL()
> mail_server.connect('mysmtpserver.at.work', 465)
>
> Everything I left untouched. However, it doesn't work:
> Traceback (most recent call last):
>    File "C:\Users\fencer\workspace\Send Email\src\send_email.py", line
> 16, in 
>      mail_server.ehlo()
>    File "C:\Python26\lib\smtplib.py", line 382, in ehlo
>      self.putcmd(self.ehlo_msg, name or self.local_hostname)
>    File "C:\Python26\lib\smtplib.py", line 318, in putcmd
>      self.send(str)
>    File "C:\Python26\lib\smtplib.py", line 310, in send
>      raise SMTPServerDisconnected('please run connect() first')
> smtplib.SMTPServerDisconnected: please run connect() first
>
> As you can see, I'm on Windows Vista.
>
> What do I need to change in my code to fix this problem? Thunderbird
> manages to do it! :) Ideally, I would like send an email that the
> recipient can't reply to, but if doesn't work, it's fine too. I want to
> use this to send automated emails to students with account information
> for a course.
>
> - Fencer

The docs say:

---
class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[,
certfile[, timeout]])

A SMTP_SSL instance behaves exactly the same as instances of SMTP.
SMTP_SSL should be used for situations where SSL is required from the
beginning of the connection and using starttls() is not appropriate.
---

So try getting ride of these two lines:

> mail_server.starttls()
> mail_server.ehlo()

There's also some info on google about a bug in this regard, so check
to see when you installed python 2.6.2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print() and unicode strings (python 3.1)

2009-08-26 Thread 7stud
On Aug 25, 6:34 am, Nobody  wrote:
> The underlying OS primitive can only handle bytes. If you read or write a
> (unicode) string, Python needs to know which encoding is used. For Python
> file objects created by the user (via open() etc), you can specify the
> encoding; for those created by the runtime (e.g. sys.stdin), Python uses
> the locale's LC_CTYPE category to select an encoding.
>
> Data written to or read from text streams is encoded or decoded using the
> stream's encoding. Filenames are encoded and decoded using the
> filesystem encoding (sys.getfilesystemencoding()). Anything else uses the
> default encoding (sys.getdefaultencoding()).
>
> In Python 3, text streams are handled using io.TextIOWrapper:
>
>        http://docs.python.org/3.1/library/io.html#text-i-o
>
> This implements a stream which can read and/or write text data on top of
> one which can read and/or write binary data. The sys.std{in,out,err}
> streams are instances of TextIOWrapper. You can get the underlying
> binary stream from the "buffer" attribute, e.g.:
>
>         sys.stdout.buffer.write(b'hello world\n')
>
> If you need to force a specific encoding (e.g. if the user has specified
> an encoding via a command-line option), you can detach the existing
> wrapper and create a new one, e.g.:
>
>         sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 
> new_encoding)

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


Re: Need help with Python scoping rules

2009-08-26 Thread 7stud
On Aug 25, 7:26 pm, Dave Angel  wrote:
> Stephen Fairchild wrote:
> > You are trying to run code in a class that does not exist yet.
>
> > def Demo():
> >     def fact(n):
> >         if n < 2:
> >             return 1
> >         else:
> >             return n * fact(n - 1)
> >     return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar":
> > fact(5)})
> > Demo = Demo()
>
> > d = Demo()
> > print d._classvar    # prints 120
> > print d.fact(7)      # prints 5040
> > print Demo           # prints 
>
>
>
> In all these messages, something I haven't seen pointed out is that
> fact() has no self argument.  
>

An "argument" is something that is specified in the the function
call.  I assume you are trying to state something like, "fact() is not
defined with a parameter variable named self".  However, that has
never been a requirement in python:


class A(object):

def fact(n):
print n

fact("hello")


a = A()
a.fact()

--output:--
hello
<__main__.A object at 0x7faf0>



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


Re: Need help with Python scoping rules

2009-08-25 Thread 7stud
On Aug 25, 12:11 pm, John Posner  wrote:
> Diez said:
>
>
>
> > Classes are not scopes.
>
> > So the above doesn't work because name resolution inside functions/methods
> > looks for local variables first, then for the *global* scope. There is no
> > class-scope-lookup.
>
> Buthttp://docs.python.org/tutorial/classes.htmlsays, in Section 9.3 "A
> First Look at Classes":
>
> When a class definition is entered, a new namespace is created,
> and used as the local scope — thus, all assignments to local variables
> go into this new namespace. In particular, function definitions bind
> the name of the new function here.
>
> The following example confirms this:
>
> class Spam(object):
> clsvar_1 = 555
> clsvar_2 = clsvar_1 + 222
>
> def __init__(self):
> print "Spam instance initialized"
>
> sp = Spam()
> print sp.clsvar_1, sp.clsvar_2
>
> output:
> Spam instance initialized
> 555 777
>
> Does the OP (kj) have a legitimate gripe, though? I confess that I know


I guess a counter example would be something like this:

y = "hello"

class Demo(object):
y = "goodbye"

def __init__(self):
self.x = 10
print y

Demo()

--output:--
hello


>
> nothing about Python's implementation -- I'm strictly a user. So it's
> just a suspicion of mine that
> something special enables a recursive function definition to refer to
> the function's own name before the definition has been completed.
>

python ignores the names inside a function when it creates the
function.  This "program" will not produce an error:


def f():
print x

python parses the file and creates the function object and assigns the
function object to the variable f.  It's not until you execute the
function that python will raise an error.  The same thing happens with
the recursive function.


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


Re: print() and unicode strings (python 3.1)

2009-08-25 Thread 7stud
On Aug 24, 10:09 pm, Ned Deily  wrote:
> In article
> ,
>
>
>
>  7stud  wrote:
> > On Aug 24, 2:41 pm, "Martin v. Löwis"  wrote:
> > > > I can't figure out a way to programatically set the encoding for
> > > > sys.stdout.  So where does that leave me?
>
> > > You should be setting the terminal encoding administratively, not
> > > programmatically.
>
> > The terminal encoding has always been utf-8.  It was not set
> > programmatically.
>
> > It seems to me that python 3.1's string handling is broken.
> > Apparently, in python 3.1 I am unable to explicitly set the encoding
> > of a string and print() it out with the result being human readable
> > text.  On the other hand, if I let python do the encoding implicitly,
> > python uses a codec I don't want it to.
>
> If you are running on a Unix-y system, check your locale settings (LANG,
> LC.*, et al).  I think you'll likely find that your locale is really not
> UTF-8.   The following was on Python 3.1 on OS X 10.5, similar results
> on Debian Linux:
>
> $ cat t3.py
> import sys
> print(sys.stdout.encoding)
> s = "¤"
> print(s.encode("utf-8"))
> print(s)
>
> $ export LANG=en_US.UTF-8
> $ python3.1 t3.py
> UTF-8
> b'\xe2\x82\xac'
> ¤
>
> $ export LANG=C
> $ python3.1 t3.py
> US-ASCII
> b'\xe2\x82\xac'
> Traceback (most recent call last):
>   File "t3.py", line 7, in 
> print(s)
> UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in
> position 0: ordinal not in range(128)
>
> --
>  Ned Deily,
>  n...@acm.org

Hi,

Thanks for the response.  My OS is mac osx 10.4.11.  I'm not really
sure how to check my locale settings.  Here is some stuff I tried:

$ echo $LANG

$ echo $LC_ALL

$ echo $LC_CTYPE

$ locale
LANG=
LC_COLLATE="C"
LC_CTYPE="C"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL="C"

$man locale
...
...
...

ENVIRONMENT:
LANG
Used as a substitute for any unset LC_* variable.  If LANG is unset it
will act as if set to "C".  If any of LANG or LC_* are set to invalide
values locale acts as if they are all unset.

===

As in your last example, my 'C' settings mean that an ascii codec is
used somewhere to encode() the unicode string.

--
The locale C or POSIX is a portable locale; its LC_CTYPE part
corresponds to the 7-bit ASCII character set.

http://linux.about.com/library/cmd/blcmdl3_setlocale.htm
--


Is this the way it works:


1) python sets the codec for sys.stdout to the LANG environment
variable.
2) It doesn't matter that my terminal's encoding is set to utf-8
because output has to pass through sys.stdout first.

So:

a) My terminal's environment is telling python(and all other programs
running in the terminal) that output sent to sys.stdout must be
encoded in ascii.
b) The solution is to set a LANG environment variable.


Why does echoing $LC_ALL or $LC_CTYPE just give me a blank string?


Previously, I've set environment variables that I want to be
permanent, e.g PATH, in ~/.bash_profile, so I did this:

~/.bash_profile:
--
...
...
LANG="en_US.UTF-8"
export LANG

and now python 3.1 acts like I expect it to:

---
import locale
import sys

print(locale.getlocale(locale.LC_CTYPE))
print(sys.stdout.encoding)


s = "€"
print(s)

print(s.encode("utf-8"))

--output:--
('en_US', 'UTF8')
UTF-8
€
b'\xe2\x82\xac'
--

In conclusion, as far as I can tell, if your python 3.1 program tries
to output a unicode string, and the unicode string cannot be encoded
by the codec specified in the user's LANG environment variable**, then
the user will get an encode error. Just because the programmer's
system can handle the output doesn't mean that another user's system
can.  I guess that's the way it goes: if a user's environment is
telling all programs that it only wants ascii output to go to the
screen(sys.stdout), you can't(or shouldn't) do anything about it.

**Or if the LANG environment variable is not present, then the codec
corresponding to the locale settings(C' corresponds to ascii).

some good locale info:
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_19.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to display photos

2009-08-24 Thread 7stud
On Aug 24, 8:01 pm, Paul Rubin  wrote:
> samwyse  writes:
> > My big question is, what's the
> > best way to display the photos.  I've used PIL in the past, but IIRC
> > it uses an external program.  Pygame is the next obvious choice, but
> > like PIL it requires an add-in.  That leaves Tkinter.  Has anyone used
> > it to display .JPG files, perhaps with rescaling to fit my screen?
>
> I've displayed images with tkinter -- I remember there is some kind of
> trick you have to do to prevent them from being gc'd prematurely but
> I've forgotten the specifics.  
>

You store the images in a list or dictionary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print() and unicode strings (python 3.1)

2009-08-24 Thread 7stud
On Aug 24, 2:41 pm, "Martin v. Löwis"  wrote:
> > I can't figure out a way to programatically set the encoding for
> > sys.stdout.  So where does that leave me?
>
> You should be setting the terminal encoding administratively, not
> programmatically.
>

The terminal encoding has always been utf-8.  It was not set
programmatically.

It seems to me that python 3.1's string handling is broken.
Apparently, in python 3.1 I am unable to explicitly set the encoding
of a string and print() it out with the result being human readable
text.  On the other hand, if I let python do the encoding implicitly,
python uses a codec I don't want it to.



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


Re: print() and unicode strings (python 3.1)

2009-08-24 Thread 7stud
On Aug 24, 12:19 pm, Stefan Behnel  wrote:
> 7stud wrote:
> > python 3.1 won't let me
> > explicitly encode my unicode string
>
> Sure it does. But encoding a non-ASCII string to ASCII will necessarily fail.
>

As you should be able to see in the python 3.1 example I posted, I did
not encode the string using the ascii codec.  I encoded it with the
utf-8 codec, and unfortunately in python 3.1 that creates a "bytes
string", and print()'ing a bytes string does not produce human
readable text.


> > and python 3.1 implicitly does
> > the encoding with the wrong codec.
>
> That's not a Python problem, though. Your terminal is configured for
> US-ASCII, so you can't output anything but US-ASCII characters.
>

My terminal is configured for utf-8, and from the output of the python
2.6 example I posted, it should be apparent that my terminal is
capable of rendering the euro character.



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


Re: print() and unicode strings (python 3.1)

2009-08-24 Thread 7stud
On Aug 24, 9:56 am, "Martin v. Löwis"  wrote:
> > I don't understand why I'm getting an encode error in python 3.1.
>
> The default encoding is not relevant here at all. Look at
> sys.stdout.encoding.
>
> Regards,
> Martin

Hi,

Thanks for the response.  I get US-ASCII for both 2.6 and 3.1:

===python 3.1==
import sys

print(sys.stdout.encoding)


$ python3.1 1test.py
US-ASCII

I can't figure out a way to programatically set the encoding for
sys.stdout.  So where does that leave me? python 3.1 won't let me
explicitly encode my unicode string, and python 3.1 implicitly does
the encoding with the wrong codec.  And why would any programmer rely
on python 3.1's implicit encoding of unicode strings anyway?
Presumably, different systems will have different encodings for
sys.stdout, some encodings might cause encode errors.

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


print() and unicode strings (python 3.1)

2009-08-24 Thread 7stud
==python 2.6 ==
import sys

print sys.getdefaultencoding()

s = u"\u20ac"
print s.encode("utf-8")


$ python2.6 1test.py
ascii
€


=python 3.1 ===
import sys

print(sys.getdefaultencoding())

s = "€"
print(s.encode("utf-8"))
print(s)


$ python3.1 1test.py
utf-8
b'\xe2\x82\xac'

Traceback (most recent call last):
File "1test.py", line 7, in 
print(s)
UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in
position 0: ordinal not in range(12


I don't understand why I'm getting an encode error in python 3.1.

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


Re: Monkeypatching an object to become callable

2009-08-09 Thread 7stud
On Aug 9, 1:02 pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
>
> >>> class foo(object):
>
> ...   pass
> ...>>> t = foo()
> >>> def test():
>
> ...   print 'bar'
> ...>>> t()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__ = test
> >>> t()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__()
>
> bar
>
> Is there an additional trick to get it to work?
>
> Best,
>
>    -Nikolaus
>
> --
>  »Time flies like an arrow, fruit flies like a Banana.«
>
>   PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


With an old-style class your code will work:

class A:
pass

def test():
print "test"

a = A()
a.__call__ = test

a()

--output:--
test


a2 = A()
a2()

--output:--

a2()
AttributeError: A instance has no __call__ method



Another option is to use the *decorator pattern*.  The decorator
pattern can be used when you want to add additional methods and
attributes to an object, and you don't want to disturb the original
class:

class A(object):
def __init__(self, x):
self.x = x

def sayhi(self):
print "hi"


class Wrapper(object):
def __init__(self, obj, func):
self.obj = obj
self.func = func

def __call__(self, *args):
return self.func(*args)

def __getattr__(self, name):
return object.__getattribute__(self.obj, name)


def test():
print "test"

a = A(10)
w = Wrapper(a, test)
w()
print w.x
w.sayhi()

--output:--
test
10
hi

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


Re: Upgrade Python on a Mac

2009-03-30 Thread 7stud
On Mar 3, 4:01 am, Graham Dumpleton 
wrote:
> On Mar 3, 8:53 am, Rey Bango  wrote:
>
> > Hi,
>
> > I'd like to upgrade the installed version of Python that came standard
> > on OS X (Leopard) with either 2.6.1 or 3.0.1. Before I stick my foot
> > in it, I just wanted to get a better understanding of the process.
>
> > If I download the disk image installer from 
> > here:http://www.python.org/download/
> > will it allow me to upgrade my existing version or is it more involved
> > (eg: making a new build).
>
> > I've looked through the python.org page for upgrade instructions for a
> >Macand haven't found it.
>
> > Any help would be appreciated.
>
> Beware of the official Python binary installers for MacOS X if wanting
> to do Python web development.
>
> Based on feedback these installers have only been compiled for 32 bit
> architectures. This makes them useless if you want to run mod_python
> or mod_wsgi with Apache that comes with MacOS X as it runs as 64 bit
> and relies on the Python framework having 64 bit, which these
> installers do not provide.
>
> If this is going to affect you, build from source code. Configure
> options required would be, as an example:
>
> ./configure --prefix=/usr/local/python-3.0  \
>  --enable-framework=/usr/local/python-3.0/frameworks \
>  --enable-universalsdk=/ MACOSX_DEPLOYMENT_TARGET=10.5 \
>  --with-universal-archs=all
>


Which of the following is the "official Python binary installer for
MacOS X"?

-
Python-2.6.1.tar.bz2

python-2.6.1-macosx2008-12-06.dmg
-

and is the problem with 3.0 specifically or all versions?


> Note that not all MacPorts installers have been both 32/64 bit either.
> Not sure if they have fixed this issue.
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: exception in urllib2

2009-02-01 Thread 7stud
On Feb 1, 3:34 am, asit  wrote:
> I hv been developing a link scanner. Here the objective is to
> recursively scan a particular web site.
>
> During this, my script methttp://images.google.co.in/imghp?hl=en&tab=wi
> and passed it to the scan function, whose body is like this..
>
> def scan(site):
>     log=open(logfile,'a')
>     log.write(site + "\n")
>     site = "http://"; + site.lower()
>     try:
>         site_data = urllib.urlopen(site)
>         parser = MyParser()
>         parser.parse(site_data.read())
>     except(IOError),msg:
>         print "Error in connecting site ", site
>         print msg
>     links = parser.get_hyperlinks()
>     for l in links:
>         log.write(l + "\n")
>
> But it throws a weird exception like this...
>
> Traceback (most recent call last):
>   File "I:\Python26\linkscan1.py", line 104, in 
>     main()
>   File "I:\Python26\linkscan1.py", line 95, in main
>     scan(lk)
>   File "I:\Python26\linkscan1.py", line 65, in scan
>     site_data = urllib.urlopen(site)
>   File "I:\Python26\lib\urllib.py", line 87, in urlopen
>     return opener.open(url)
>   File "I:\Python26\lib\urllib.py", line 203, in open
>     return getattr(self, name)(url)
>   File "I:\Python26\lib\urllib.py", line 327, in open_http
>     h = httplib.HTTP(host)
>   File "I:\Python26\lib\httplib.py", line 984, in __init__
>     self._setup(self._connection_class(host, port, strict))
>   File "I:\Python26\lib\httplib.py", line 656, in __init__
>     self._set_hostport(host, port)
>   File "I:\Python26\lib\httplib.py", line 668, in _set_hostport
>     raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
> httplib.InvalidURL: nonnumeric port: ''
>
> How can i handle this ???

"Handle" as in how do I catch that exception?  The exception's name is
give in the error message.  Look at the last line.  To catch that
exception, you can do this:

import httplib   #that's the module the exception lives in
 #as indicated in error message

try:



except httplib.InvalidURL, e:
print e
print "Bad url"




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


Re: exception in urllib2

2009-02-01 Thread 7stud
On Feb 1, 3:34 am, asit  wrote:
> I hv been developing a link scanner. Here the objective is to
> recursively scan a particular web site.
>
> During this, my script methttp://images.google.co.in/imghp?hl=en&tab=wi
> and passed it to the scan function, whose body is like this..
>
> def scan(site):
>

So you have this:

site=http://images.google.co.in/imghp?hl=en&tab=wi

??



>     log=open(logfile,'a')
>     log.write(site + "\n")
>     site = "http://"; + site.lower()
>

So now:

site = "http://"; + "http://images.google.co.in/imghp?hl=en&tab=wi";

Hmmm...let's see what happens when I run the following program:


import urllib

site = "http://"; + "http://images.google.co.in/imghp?hl=en&tab=wi";
html = urllib.urlopen(site)

--output:--
Traceback (most recent call last):
  File "6test.py", line 4, in ?
html = urllib.urlopen(site)
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/urllib.py", line 82, in urlopen
return opener.open(url)
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/urllib.py", line 190, in open
return getattr(self, name)(url)
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/urllib.py", line 303, in open_http
h = httplib.HTTP(host)
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/httplib.py", line 1097, in __init__
self._setup(self._connection_class(host, port, strict))
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/httplib.py", line 586, in __init__
self._set_hostport(host, port)
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/httplib.py", line 598, in _set_hostport
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
httplib.InvalidURL: nonnumeric port: ''


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


Re: New to python, open source Mac OS X IDE?

2009-01-28 Thread 7stud
On Jan 27, 6:07 pm, Burukena  wrote:
> On 1/27/09 8:44 PM, James Stroud wrote:
>
> > joseph.a.mar...@gmail.com wrote:
> >> Greetings! I've heard enough raving about Python, I'm going to see for
> >> myself what all the praise is for!
>
> >> I'm on a Mac. I use Netbeans for Java, PHP, and C if needed. Do you
> >> even use an IDE for Python?
>
> >> Any recommendations on open source Python environments?
>
> >> Thanks!
>
> > Try open komodo. I haven't used it because vim is my IDE, but it looks
> > pretty good.
>
> > James
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Vim and a terminal works for me, specifically with screen.

What does 'with screen' mean?

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


Re: Start Python at client side from web app

2009-01-21 Thread 7stud
On Jan 21, 1:10 am, Thomas Guettler  wrote:
> Hi,
>
> I want to start Python at the client side from a web application. The
> app is an intranet application, and all client PCs are under our control (we
> can install software on them).
>
> But I don't want to update the installation too often. Here is my idea:
>
> We create a custom mime-type and register it on the client PC. The web 
> application
> can send signed python code to the client PC. If the signature is correct,
> the code will be executed at the client.

How does a web application on the client execute python code?
--
http://mail.python.org/mailman/listinfo/python-list


Re: output problem

2009-01-18 Thread 7stud
On Jan 16, 8:24 am, "Jean-Paul VALENTIN"  wrote:
> Feature? the output of below Hello program he0.py started from command
> line looks as follows:
> F:\prompt>he0.py
> Hello
> F:\prompt>
>
> 'Hello' was sent with sys.stdout.write, so "without newline".
> But why cannot be output (more logically):
> F:\prompt>he0.py
> HelloF:\prompt>
>
> Is it normal? Is there any means or workaround to obtain that output if
> I wish??
> 
> __
> #!/usr/bin/python
> #-*- coding: iso-8859-15 -*-
> import sys
> sys.stdout.write('Hello')
>

Not on a Mac:

import sys
sys.stdout.write("hello")

output:
$ python 6test.py
hello$

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


Re: smtplib "authentication required" error

2008-05-17 Thread 7stud
On May 17, 12:18 pm, cher <[EMAIL PROTECTED]> wrote:
> Hey,
>
> Don't know if you can help, but I'm trying to import archived messages
> from Thunderbird into my gmail account and keep getting these types of
> errors.  I am using the GML program to help incorporate, but the SMTP
> server is not being recognized by gmail.  Am I doing something wrong?  
> Anything else I can try?
> SMTP I've tried:
>     smtp.gmail.com
>     gsmtp56.google.com
>
> Error Val : (530, '5.7.0 Must issue a STARTTLS command first.
> m29sm9416768poh.4',
> *** 76 ERROR SENDING MESSAGE FROM: [EMAIL PROTECTED]
> *** UNABLE TO CONNECT TO SERVER OR SEND MESSAGE. ERROR FOLLOWS.
> Error Type: smtplib.SMTPSenderRefused
> Error Val : (530, '5.7.0 Must issue a STARTTLS command first.
> n22sm9448670pof.3', '[EMAIL PROTECTED]')
>
> Thanks,
> Cher

Can you get the following program to work?


#Uses gmail to send an email to someone

import smtplib

sender = "Tom"
to = "Sally"
subject = "Test smtplib"

headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to,
subject)
msg = headers + "Hello.  How are you?"

mailserver = smtplib.SMTP("smtp.gmail.com", 587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login("your_gmail_email_address", "your_gmail_password")
mailserver.sendmail("your_gmail_email_addres",
"a_destination_email_address", msg)
mailserver.close()

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


Re: Cookies and CookieJar

2008-05-17 Thread 7stud
Larry Bates wrote:
> I'm struggling with a project using mechanize and cookies to screen scape a
> website.  The site requires a client created cookie for authentication.

Are you sure that is correct?  As far as I know, the usual course of
events is for a site to set a cookie header in the response it sends
back to the client browser, which gets stored on the client's
computer.  Then when the browser makes subsequent requests to that
site, the browser will automatically include the cookies that were set
by that site.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies and CookieJar

2008-05-17 Thread 7stud
On May 16, 9:21 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> I'm struggling with a project using mechanize and cookies to screen scape a
> website.  The site requires a client created cookie for authentication.  Below
> is the code I'm attempting to use with the traceback I'm getting:
>
>  >>> import Cookie
>  >>> c=Cookie.SimpleCookie()
>  >>> c["Manageopen"]="cards"
>  >>> c['Manageopen']['expires'] = 0
>  >>> c['Manageopen']['path'] = "/"
>  >>> c['Manageopen']['domain'] = ".domain.com"
>  >>> c['Manageopen']['secure'] = ""
>  >>> c.output()
> 'Set-Cookie: Manageopen=cards; Domain=.domain.com; expires=Fri, 16-May-2008
> 14:06:00 GMT; Path=/'
>  >>> import cookielib
>  >>> cj=cookielib.CookieJar()
>  >>> cj.set_cookie(c)
> Traceback (most recent call last):
>    File "", line 1, in 
>    File "C:\Python25\lib\cookielib.py", line 1617, in set_cookie
>      if cookie.domain not in c: c[cookie.domain] = {}
> AttributeError: 'SimpleCookie' object has no attribute 'domain'
>  >>>
>
> I also tried:
>
>  >>> cj.set_cookie(c["Manageopen"])
> Traceback (most recent call last):
>    File "", line 1, in 
>    File "C:\Python25\lib\cookielib.py", line 1617, in set_cookie
>      if cookie.domain not in c: c[cookie.domain] = {}
> AttributeError: 'Morsel' object has no attribute 'domain'
>
> I've looked at everything I can find via Google and nothing seems to help.
>
> Thanks in advance.
>
> Regards,
> Larry

Hi,

In the python docs, set_cookie() is defined like this:

---
set_cookie(cookie)
Set a Cookie, without checking with policy to see whether or not it
should be set.
---

The Cookie mentioned there is a an object of the Cookie class which is
defined in the cookielib module.  On the other hand,
Cookie.SimpleCookie() creates an object of a class called SimpleCookie
(and SimpleCookie inherits from a class called BaseCookie).
Therefore, the object returned by Cookie.SimpleCookie() is not a
Cookie--it's a SimpleCookie.  Just because the module that contains
the SimpleCookie class is called Cookie does not mean that
SimpleCookie inherits from the Cookie class or that SimpleCookie has
any connection to the Cookie class located in the cookielib module.
If that's too confusing, here is the way the python modules are set
up:

Cookie module:
-
BaseCookie class
|
V
SimpleCookie class




cookielib module

Cookie class

CookieJar class
---set_cookie(Cookie)


What you did in your code was you supplied set_cookie() with a
SimpleCookie object, and set_cookie() expects a Cookie object.
SimpleCookie objects are a mapping and you access the data using the
notation:

>  >>> c['Manageopen']['domain'] = ".domain.com"

But if you open up cookilib.py and look at the line in the error
message:

> File "C:\Python25\lib\cookielib.py", line 1617, in set_cookie

you will see that the code uses the notation:

>      if cookie.domain ...

That's because the Cookie class defines simple objects that have
attributes that are accessed normally, i.e. with dot notation.


> The site requires a client created cookie for authentication.

A "cookie" is just one of the headers in a request.  Instead of using
a url string to retrieve a web page with urllib2.urlopen(), you can
use a Request object.  And Request objects allow you to set headers,
which means you can set a cookie header.

But the site will probably check every subsequent request for that
cookie header as well, so that means you will need to add the header
to every subsequent request you make.  That is where CookieJar can
help you.  It can store cookies in a file and then automatically add
them to every request for you.  It's a bit complicated though.  See
here:

http://www.voidspace.org.uk/python/articles/cookielib.shtml










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


Re: write to specific line in file?

2008-05-16 Thread 7stud
globalrev wrote:
> i ahve a program that takes certain textsnippets out of one file and
> inserts them into another.
>
> problem is it jsut overwrites the first riow every time.
>
> i want to insert every new piece of text into the next row.
> so:
> 1. how do i write to a new line every time i write to the file?
>
> 2. if i dont want to write to a new line but just want to insert it
> after the last token in the file, how do i do then?

Generally, you can't "insert" anything into a file.  You can either
append to the end of a file, or you can rewrite the whole file.  It
sounds like you probably want to read the file into an array using
readlines().  Then manipulate that array however you want--appending
and inserting--and when you are done, overwrite the file with your
array.

However, you should be aware that as soon as you open a file for
writing all the data is erased, and if your program should happen to
crash right then, the array containing the data will disappear into
the ether and your file will be empty--in other words all your data
will be gone.  To prevent such an occurence, you should write your
final data to another file, then delete the original file, and finally
change the other file's name to the original file name.

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


Re: downloading a link with javascript in it..

2008-05-12 Thread 7stud
On May 12, 4:59 pm, 7stud <[EMAIL PROTECTED]> wrote:
> On May 12, 1:54 pm, Jetus <[EMAIL PROTECTED]> wrote:
>
> > I am able to download this page (enclosed code), but I then want to
> > download a pdf file that I can view in a regular browser by clicking
> > on the "view" link. I don't know how to automate this next part of my
> > script. It seems like it uses Javascript.
> > The line in the page source says
>
> > href="javascript:openimagewin('JCCOGetImage.jsp?
> > refnum=DN2007036179');" tabindex=-1>
>
> 1) Use BeautifulSoup to extract the path:
>
> JCCOGetImage.jsp?refnum=DN2007036179
>
> from the html page.
>

BeautifulSoup will allow you to locate and extract the href attribute:

javascript:openimagewin('JCCOGetImage.jsp?refnum=DN2007036179');

See: "The attributes of Tags" in the BS docs.

Then you can use string functions(preferable) or a regex to get
everything between the parentheses(remove the quotes around the path,
too)
--
http://mail.python.org/mailman/listinfo/python-list


Re: downloading a link with javascript in it..

2008-05-12 Thread 7stud
On May 12, 1:54 pm, Jetus <[EMAIL PROTECTED]> wrote:
> I am able to download this page (enclosed code), but I then want to
> download a pdf file that I can view in a regular browser by clicking
> on the "view" link. I don't know how to automate this next part of my
> script. It seems like it uses Javascript.
> The line in the page source says
>
> href="javascript:openimagewin('JCCOGetImage.jsp?
> refnum=DN2007036179');" tabindex=-1>
>

1) Use BeautifulSoup to extract the path:

JCCOGetImage.jsp?refnum=DN2007036179

from the html page.


2) The path is relative to the current url, so if the current url is:

http://www.landrecords.jcc.ky.gov/records/S3DataLKUP.jsp

Then the url to the page you want is:

http://www.landrecords.jcc.ky.gov/records/JCCOGetImage.jsp?refnum=DN2007036179

You can use urlparse.urljoin() to join a relative path to the current
url:


import urlparse

base_url = 'http://www.landrecords.jcc.ky.gov/records/S3DataLKUP.jsp'
relative_url = 'JCCOGetImage.jsp?refnum=DN2007036179'

target_url = urlparse.urljoin(base_url, relative_url)
print target_url

--output:--
http://www.landrecords.jcc.ky.gov/records/JCCOGetImage.jsp?refnum=DN2007036179



3) Python has a webbrowser module that allows you to open urls in a
browser:

import webbrowser

webbrowser.open("www.google.com")


You could also use system() or os.startfile()[Windows], to do the same
thing:

os.system(r'C:\"Program Files"\"Mozilla Firefox"\firefox.exe')

#You don't have to worry about directory names
#with spaces in them if you use startfile():
os.startfile(r'C:\Program Files\Mozilla Firefox\firefox.exe')


All the urls you posted give me errors when I try to open them in a
browser, so you will have to sort out those problems first.



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


Re: File Creation Not Working In A Thread Class?

2008-05-11 Thread 7stud
On May 11, 5:50 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> bc90021 wrote:
> > You are a perfect example of exactly what I was talking about, and why
> > the Python community is such a poor one.
>
> I though you were treated quite fairly all things considered.   (You
> started the personal attacks, the whining about the group, the
> accusations of arrogance, and the refusal to believe we all *knew* the
> error was in your file name calculation and not in Python threads.)
>
> This group is widely acknowledged as one of the more friendly groups
> around,  and in fact we keep it that way by coming down rather hard on
> those who abuse either the members of the group or the purpose of the
> group.

That is a blantant lie.   This group has well known members that are
some of the biggest jackasses I've ever encountered on the internet.
I've never heard a peep out of anyone criticizing their behavior.  If
I were their employer, and I read some of the stuff they posted, I
would fire them on the spot.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Creation Not Working In A Thread Class?

2008-05-11 Thread 7stud
On May 11, 2:11 pm, bc90021 <[EMAIL PROTECTED]> wrote:
> [CUT]
>
> > I have in no way assumed that you are stupid.  I have tried to help you
> > formulate your problem better so that people on the list can help you.
> > I believe I have done so respectfully, with the aim of introducing you
> > to the modus operandi of this group.
>
> I appreciate your help.  However, the comments I got from other people
> that "I'm sure you have quotes here..." type comments are incredibly
> insulting.  To tell someone that you're sure that they have quotes around
> something when they don't is the height of arrogance and rudeness.
>

The best way to get help is to post a simple example that demonstrates
your problem and that anyone can run and get the same error you are
getting.  That means you need take your real code and you start
hacking out the bits that are irrelevant to the problem.  With
judicious use of print statements you should be able to narrow the
problem down.

Your first post was about as far away from that as it could be.  Your
first post was essentially equivalent to asking:

> Why does this line:

>print name

>display "Jack" and not "Jill".

When you post a question like that, then you are either going to be
met with silence or people will attempt to debug your imaginary code
and guess at the problem, which sometimes works and sometimes
doesn't.  If you find the guesses insulting, then post a better model
of your problem.  The fact that you found these guesses insulting,
even though they were respectfully given and they were the obvious
answers in light of how little information you gave, means you are
probably going to have problems on any newsgroup you post to.

The python community has some real jerks in it, but you didn't meet
any of them in this thread.





> >> (I really must say that so far the help I am getting in the Python
> >> community is a big let down.  Whether it's on IRC or here, everyone has
> >> an arrogance that I don't find anywhere else in the open source
> >> community, and it seriously makes me question the choice of language
> >> that I've made.)
>
> > Don't judge too quickly.  I think this newsgroup is on the whole
> > extremely helpful.  I have learnt a lot from it.  But you have to get
> > used to its ways, and until you are familiar with them, approach it with
> > humility.
>
> Unfortunately, this is not my first interaction with the Python IRC
> communities or Python newsgroups.  I had tried working with this language
> a while back (around 2000) and the answers I got were unhelpful and
> usually rude.  I decided to give it another shot for the program I'm
> writing, and I'm regretting that.  It's possible that I'm to blame - I'm
> the common factor in both instances, but at the same time, when you ask a
> question in #python and NO ONE ANSWERS at all, and they all just sit
> there not talking at all, what's the point of having the IRC channel?  If
> newbies can't go there for help, what's the point?  When there are 70
> people in a channel, and no one even acknowledges your question has been
> asked, where does one go for help?  It's like talking to yourself.
>
> >> The error message was at the top of the thread (am I incapable of
> >> posting it, or are you incapable of following a thread?), but here it
> >> is again:
>
> >> IOError: [Errno 2] no such file u'tempfileName'
>
> > This is different from the error message that you posted in your
> > original message.
>
> > Anyway, what is useful to us is a full traceback, no just an error
> > message.
>
> It is not "different" except that I posted the full name the second
> time.  (tempfileName instead of the previously simplified fileName)  The
> code itself is actually irrelevant, in my humble opinion.  In one place a
> file creation line does not work; in the second place it does.  How can
> the same line of code do two different things in two places?  Either it
> creates a file or it doesn't.  It should create the file in either place,
> regardless of where it's being called.
>
> Either way, I figured it out.

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


Re: File Creation Not Working In A Thread Class?

2008-05-11 Thread 7stud
On May 11, 2:01 pm, 7stud <[EMAIL PROTECTED]> wrote:
> On May 11, 1:28 pm, bc90021 <[EMAIL PROTECTED]> wrote:
>
>
>
> > > ...and the exact error message was?
>
> > > Here is a tip: if you want people to help you, then you have to help
> > > them to help you.  Personally, I wouldn't respond to anymore of your
> > > questions because you seem incapable of posting the information that was
> > > requested.
>
> > So far, the people who have answered this post have gone on the
> > assumption that I'm stupid.  I'm not.  I took perfectly working code,
> > cut it from one class, and put it in another.  It stopped working in the
> > second class.  I've spent days on this and trust me, given what I've
> > experienced of the Python community so far, if I didn't have to ask, I
> > wouldn't.
>
> > (I really must say that so far the help I am getting in the Python
> > community is a big let down.  Whether it's on IRC or here, everyone has
> > an arrogance that I don't find anywhere else in the open source
> > community, and it seriously makes me question the choice of language that
> > I've made.)
>
> > The error message was at the top of the thread (am I incapable of posting
> > it, or are you incapable of following a thread?), but here it is again:
>
> > IOError: [Errno 2] no such file u'tempfileName'
>
> Well, it appears to me that this error message is different than the
> one in your first post.  But maybe I'm on LSD right now and things
> will be appear differently tomorrow.
>
> In addition, I've never seen a python error message that doesn't
> include the traceback, which you were asked to post, but apparently
> are still incapbable of doing.  Also, any line numbers in the error
> message should be marked in your code with comments.  That will help
> other people help you, remember?

In addition, posting the exact output from this:

>print "We're in copying, and tempfileName is: %s...\n" % tempfileName
> #The above line correctly prints the temporary file name every time!
> The directory exists, too!

would be helpful.

In addition, reducing your code to a simple 10 line example that
produces the same problem and that anyone can run would be helpful.
You might find that making the effort to produce a simple 10 line
example that mimics the problem, will actually result in your solving
the problem yourself.


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


Re: File Creation Not Working In A Thread Class?

2008-05-11 Thread 7stud
On May 11, 1:28 pm, bc90021 <[EMAIL PROTECTED]> wrote:
> > ...and the exact error message was?
>
> > Here is a tip: if you want people to help you, then you have to help
> > them to help you.  Personally, I wouldn't respond to anymore of your
> > questions because you seem incapable of posting the information that was
> > requested.
>
> So far, the people who have answered this post have gone on the
> assumption that I'm stupid.  I'm not.  I took perfectly working code,
> cut it from one class, and put it in another.  It stopped working in the
> second class.  I've spent days on this and trust me, given what I've
> experienced of the Python community so far, if I didn't have to ask, I
> wouldn't.
>
> (I really must say that so far the help I am getting in the Python
> community is a big let down.  Whether it's on IRC or here, everyone has
> an arrogance that I don't find anywhere else in the open source
> community, and it seriously makes me question the choice of language that
> I've made.)
>
> The error message was at the top of the thread (am I incapable of posting
> it, or are you incapable of following a thread?), but here it is again:
>
> IOError: [Errno 2] no such file u'tempfileName'

Well, it appears to me that this error message is different than the
one in your first post.  But maybe I'm on LSD right now and things
will be appear differently tomorrow.

In addition, I've never seen a python error message that doesn't
include the traceback, which you were asked to post, but apparently
are still incapbable of doing.  Also, any line numbers in the error
message should be marked in your code with comments.  That will help
other people help you, remember?



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


Re: File Creation Not Working In A Thread Class?

2008-05-11 Thread 7stud
bc90021 wrote:
> Hi All,
>
> Thanks in advance for any and all help!
>
> I have this code:
>
> g = open(fileName, 'a')
>
> where fileName is defined before the line it's used in.  It works fine
> when I use it outside a thread class.
>
> When I put the same line in a thread class, it no longer works, and I get
> an error:
>
> IOError: [Errno 2] no such file u'fileName'
>
> Are threads not allowed to create files?

...oh yeah:

import threading
import time

fname = "data.txt"
f = open(fname)
print f.read()
f.close()

f = open(fname, "a")
f.write("some text\n")
f.close()

f = open(fname)
print f.read()
f.close()


class MyThread(threading.Thread):
def __init__(self, file_name):
threading.Thread.__init__(self)

def run(self):
time.sleep(3)

f = open(fname)
print f.read()
f.close()

f = open(fname, "a")
f.write("other text\n")
f.close()

f = open(fname)
print f.read()
f.close()


my_t = MyThread(fname)
my_t.start()
my_t.join()


--output:--
hello
world

hello
world
some text

hello
world
some text

hello
world
some text
other text
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Creation Not Working In A Thread Class?

2008-05-11 Thread 7stud
On May 11, 12:42 pm, bc90021 <[EMAIL PROTECTED]> wrote:
> > It's difficult to know what's wrong with the code you posted because:
>
> > * it is not self-contained: otherFile, fileName, pattern are names
> >   which you do not define;
>
> > * the IOError you reported earlier can't arise as a result of running
> >   this code.
>
> > * you claim it works unless you put it in a subclass of
> >   threading.Thread.  Why don't you post this instead, and show us the
> >   traceback?
>
> > HTH
>
> > FWIW, my crystal ball (whose predictions I don't usually report!) tells
> > me the same as Garry Herron's.
>
> Here's the thread class:
>
> #single file is the file we're working on, whose name is passed into the 
> class and which does exist
> #matrix is a list of lists that contains info about the files - for this 
> example, [c][0] contains a string, [c][2] contains true or false, and [c][3] 
> contains a pattern to match
> #tfValue is another true or false value
>
> class FileProcThread(threading.Thread):
>         def __init__(self, singleFile, matrix, tfValue):
>                 self.singleFile = singleFile
>                 self.matrix = matrix
>                 self.tfValue = tfValue
>                 threading.Thread.__init__(self)
>         def run(self):
>                 (dirName, fileName) = os.path.split(self.singleFile)
>                 f = open(self.singleFile).readlines()
>                 copying = False
>                 for i in range(len(f)):
>                         for c in range (len(self.matrix)):
>                                 if (re.search(self.matrix[c][3], f[i])):
>                                         if (self.matrix[c][2] == True):
>                                                 copying = True
>                                                 if os.name == "posix":
>                                                         if (self.tfValue == 
> False):
>                                                                 tempfileName 
> = "\"proctemp/" + self.matrix[c][0] + "_tmp_" + fileName +
> ".txt\""
>                                                         else:
>                                                                 tempfileName 
> = "\"proctemp/" + self.matrix[c][0] + "_other.txt\""
>                                                 else:
>                                                         if (self.tfValue == 
> False):
>                                                                 tempfileName 
> = "\"proctemp\\" + self.matrix[c][0] + "_tmp_" + fileName + ".txt\""
>                                                         else:
>                                                                 tempfileName 
> = "\"proctemp\\" + self.matrix[c][0] + "_other.txt\""
>                                         else:
>                                                 copying = False
>                                 if (re.search(self.matrix[c][4], f[i])):
>                                         copying = False
>                         if (copying):
>                                 print "We're in copying, and tempfileName is: 
> %s...\n" % tempfileName
>                                 #The above line correctly prints the 
> temporary file name every time!  The directory exists, too!
>                                 g = open(tempfileName, 'a')  #This does not 
> work.  Notice I do NOT have quotes around tempfileName, as I said.
>                                 g.write(f[i])
>                                 g.close()
>
> Like I said, this works FINE outside the thread class.  I hope that the 
> formatting comes through...

...and the exact error message was?

Here is a tip: if you want people to help you, then you have to help
them to help you.  Personally, I wouldn't respond to anymore of your
questions because you seem incapable of posting the information that
was requested.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with custom events in wxpython

2008-05-11 Thread 7stud
On May 11, 7:23 am, Jimmy <[EMAIL PROTECTED]> wrote:
> hi, all
>
> I'm having a problem with creating custom events in wxpython.
>
> I have a class A handling some data processing work and another class
> B of GUI matter. I need GUI to display information when data in A is
> updated.
> I know cutom events in wxpython may work. But I found no material
> paricularly
> helpful :(
>
> can anyone write me some demo code to show how to do this ...


This example works for me:


import wx

class MyCustomEvent(wx.PyCommandEvent): #or wx.PyEvent
def __init__(self, event_type, id):
wx.PyCommandEvent.__init__(self, event_type, id)

class A(object):  #Data Processing class
def __init__(self, widget_to_update):
self.widget_to_update = widget_to_update

#create the custom event:
self.my_event_type = wx.NewEventType()
self.EVT_MY_CUSTOM_EVENT =
wx.PyEventBinder(self.my_event_type, 1)
#Note: you need to make EVT_MY_CUSTOM_EVENT persist so that you
#can refer to it in a later call to Bind()

def process_data(self): #create thread here
finished = True

if finished:
self.update_gui()


def update_gui(self):
#create a custom event object and enter it in the event queue:
my_evt_obj = MyCustomEvent(self.my_event_type,
self.widget_to_update.GetId() )
 
self.widget_to_update.GetEventHandler().ProcessEvent(my_evt_obj)


class B(object):  #Gui class
def __init__(self):
frame = wx.Frame(None, -1, "My Window")

panel = wx.Panel(frame, -1)
button = wx.Button(panel, -1, "Start Data Processing",
pos=(100, 10))
button.Bind(wx.EVT_BUTTON, self.onclick)

self.text_ctrl = wx.TextCtrl(panel, -1, "Hello World",
pos=(100, 50), size=(200, 20))

self.a = A(self.text_ctrl)
frame.Bind(self.a.EVT_MY_CUSTOM_EVENT,
self.on_my_custom_event)

frame.Show()

def onclick(self, event):
self.a.process_data()

def on_my_custom_event(self, event):
self.text_ctrl.SetValue("Finished Processing Data")


app = wx.PySimpleApp(redirect=False)
b = B()
app.MainLoop()




However, I couldn't get similar code to work when I derived the event
class from wx.PyEvent and used Bind() directly on the TextCtrl
(command events propagate up the container hierarchy while regular
events don't):

import wx

class MyCustomEvent(wx.PyEvent): #or wx.PyEvent
def __init__(self, event_type, id):
wx.PyEvent.__init__(self, event_type, id)

class A(object):  #Data Processing class
def __init__(self, widget_to_update):
self.widget_to_update = widget_to_update

#create the custom event:
self.my_event_type = wx.NewEventType()
self.EVT_MY_CUSTOM_EVENT =
wx.PyEventBinder(self.my_event_type, 1)

def process_data(self): #create thread here
finished = True
if finished:
self.update_gui()


def update_gui(self):
#create a custom event object and enter it in the event queue:
my_evt_obj = MyCustomEvent(self.my_event_type,
self.widget_to_update.GetId() )
 
self.widget_to_update.GetEventHandler().ProcessEvent(my_evt_obj)


class B(object):  #Gui class
def __init__(self):
frame = wx.Frame(None, -1, "My Window")

panel = wx.Panel(frame, -1)
button = wx.Button(panel, -1, "Start Data Processing",
pos=(100, 10))
button.Bind(wx.EVT_BUTTON, self.onclick)

self.text_ctrl = wx.TextCtrl(panel, -1, "Hello World",
pos=(100, 50), size=(200, 20))

self.a = A(self.text_ctrl)
self.text_ctrl.Bind(self.a.EVT_MY_CUSTOM_EVENT,
self.on_my_custom_event)

frame.Show()

def onclick(self, event):
self.a.process_data()

def on_my_custom_event(self, event):
self.text_ctrl.SetValue("Finished Processing Data")

app = wx.PySimpleApp(redirect=False)
b = B()
app.MainLoop()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is using range() in for loops really Pythonic?

2008-05-10 Thread 7stud
On May 10, 8:19 pm, John Salerno <[EMAIL PROTECTED]> wrote:
> I know it's popular and very handy, but I'm curious if there are purists
> out there who think that using something like:
>
> for x in range(10):
>     #do something 10 times
>
> is unPythonic. The reason I ask is because the structure of the for loop
> seems to be for iterating through a sequence. It seems somewhat
> artificial to use the for loop to do something a certain number of
> times, like above.
>

x = range(10)
print x

--output:--
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
--
http://mail.python.org/mailman/listinfo/python-list


Re: where do I begin with web programming in python?

2008-05-02 Thread 7stud
On May 1, 3:25 pm, jmDesktop <[EMAIL PROTECTED]> wrote:
> I have been to the main python site, but am still confused.  I have
> been using .net, so it may be obvious how to do this to everyone
> else.  I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.
>
> Thank you for any help.

Directions for a simple CGI script:

1) Start apache.

2) Use a text editor to create a webpage with a link:



Python CGI Test




http://localhost/cgi-bin/first.py";>click me





Save that file with a .htm extension anywhere on your computer, e.g.
name the file test.htm and save it in C:\My Documents.


3) The value of the link's href attribute is a special url.  The url
starts with "http://localhost";, or it may need to start with something
like http://localhost:8080"; depending on what port number you
installed Apache on.  If you used the default port when you installed
Apache, then the first part of the url will be "http:/localhost".

The rest of the url is the relative path to your cgi script.  The path
is relative to your Apache2 folder.  For instance, my directory
structure looks like this:

Apache2
htdocs
cgi-bin
first.py
etc.

So the relative path to my cgi script is "/cgi-bin/first.py".

4) Create a cgi script:

#!/usr/bin/env python

#For Windows, instead of the above line use
#something like: #!C:\Python25\python.exe
#instead.  The path after "#!" should be the
#path to wherever python.exe is on your computer.

import cgitb; cgitb.enable()

#The above line will cause error messages to
#be sent to your browser, which is helpful for
#debugging.  Otherwise, your browser will just
#show a blank page when there is an error in your
#script

print "Content-type: text/html"
print
print "Hello World"


The first print statement is the minimum header you need when
responding to a web page.  After you print all the headers you desire,
then you need to print a blank line.  After the blank line, you print
the html that you want the browser to display.


5) On Unix: you have to set the file permissions for your cgi script.
Everyone must be able to read and execute your cgi script:

$ chmod 755 first.py


6) Start your web browser, and click on File>Open and navigate to
your .htm file.  When your html page opens in your browser, click on
the link.  The link will call your python cgi script, the cgi script
will respond my sending some html to your browser, then your browser
will display the html.


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


Re: Inheritance confusion

2008-04-19 Thread 7stud
On Apr 19, 12:37 am, Hook <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm having a problem with multiple inheritance - it's clearly something
> I've missed, but the web pages and books that I've consulted aren't
> helping, so I'll throw myself on the mercy and collective wisdom of
> Usenet!
>
> I've got 4 files (what I'll show has the active content removed for
> brevity):
>
> Errors_m.py
> ~~~
> class Errors (object) :
>     def __init__ (self, params) :
>         pass
>
>     def Error (self, string) :
>         return 100
>
> DT_m.py
> ~~~
> class DT (object) :
>     def __init__ (self, params) :
>                 pass
>
>     def Date (self, epoch, pattern = 'd mmm ') :
>         dt = datetime.datetime.fromtimestamp (epoch)
>
> Hook_m.py
> ~
> from DT_m import DT
> from Error_m import Errors
>
> class Hook (Errors, DT) :
>     def __init__ (self, params) :
>         DT.__init__ (self, params)
>         Errors.__init__ (self, params)
>
> DB_m.py
> ~~~
> from Hook_m import Hook
>
> class DB (Hook) :
>     def __init__ (self, params) :
>         Hook.__init__ (self, params)
>
> And a test script:
>
> #!/usr/bin/python
>
> import os
> import re
> import string
> import sys
>
> from DB_m import DB
>
> Dict = dict ()
> Dict ['logdir'] = '/tmp/log'
> Dict ['diag']   = 1
>
> Obj = DB (Dict)
> print dir (Obj)
> Obj.Connect ('Database')
>
> When I run the script I get this:
>
> Traceback (most recent call last):
>   File "./3.py", line 20, in 
>     Obj.Connect ('Database')
>   File "/mnt/isis/Projects/Python/Learning/DB_m.py", line 102, in Connect
>     self.TRACE ("DB::Connect (" + database + "," + mode)
>   File "/mnt/isis/Projects/Python/Learning/Hook_m.py", line 314, in TRACE
>     self.DailyLog (msg)
>   File "/mnt/isis/Projects/Python/Learning/Hook_m.py", line 98, in
> DailyLog
>     dt          = self.Date (time ())
> TypeError: 'module' object is not callable
>
> Googling the "TypeError" message suggests that I've got a module and
> class with the same name, but I can't see that I have.
>
> Can someone point me in the right direction please?
>
> If you need to see all the source, can do, but it's certainly too much
> for an intro message!
>
> Thanks,
>
> Hook


import time

time()

--output:--
Traceback (most recent call last):
  File "test1.py", line 3, in ?
time()
TypeError: 'module' object is not callable


Did you do that somewhere?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to print a unicode string?

2008-04-18 Thread 7stud
On Apr 18, 6:36 pm, 7stud <[EMAIL PROTECTED]> wrote:
> On Apr 18, 5:38 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > I'd like to print out a unicode string.
>
> > I'm running Python inside Emacs, which understands utf-8, so I want to
> > force Python to send utf-8 to sys.stdout.
>
> > From what I've googled, I think I need to set my locale. I don't
> > understand how.
>
> > import locale
> > print locale.getlocale()
> > --> (None,None)
> > print locale.getdefaultlocal()
> > --> ('en_GB','cp1252')
> > print locale.normalize('en_GB.utf-8')
> > --> en_GB.UTF8
> > locale.setlocale(locale.LC_ALL,'en_GB.UTF8')
> > -->  locale.Error: unsupported locale setting
>
> > I'd be grateful for advice.
> > Damon.
>
> u_str = u'hell\u00F6 w\u00F6rld'  #o's with umlauts
>
> print u_str.encode('utf-8')
>
> --output:--
> hellö wörld

Or maybe you want this:

u_str = u'hell\u00F6 w\u00F6rld'
regular_str = u_str.encode('utf-8')
print repr(regular_str)

--output:--
'hell\_x_c3\_x_b6 w\_x_c3\_x_b6rld'
#underscores added to keep your browser from rendering the utf-8
characters
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to print a unicode string?

2008-04-18 Thread 7stud
On Apr 18, 5:38 pm, [EMAIL PROTECTED] wrote:
> I'd like to print out a unicode string.
>
> I'm running Python inside Emacs, which understands utf-8, so I want to
> force Python to send utf-8 to sys.stdout.
>
> From what I've googled, I think I need to set my locale. I don't
> understand how.
>
> import locale
> print locale.getlocale()
> --> (None,None)
> print locale.getdefaultlocal()
> --> ('en_GB','cp1252')
> print locale.normalize('en_GB.utf-8')
> --> en_GB.UTF8
> locale.setlocale(locale.LC_ALL,'en_GB.UTF8')
> -->  locale.Error: unsupported locale setting
>
> I'd be grateful for advice.
> Damon.

u_str = u'hell\u00F6 w\u00F6rld'  #o's with umlauts

print u_str.encode('utf-8')

--output:--
hellö wörld
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, image not appearing in function but without function

2008-04-13 Thread 7stud
On Apr 13, 11:12 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sun, 13 Apr 2008 08:57:29 -0700, skanemupp wrote:
> > why is the first program not working? when i click the screen the map
> > is not appearing.
>
> > the second program works.
>
> > from Tkinter import *
>
> > master = Tk()
>
> > w = Canvas(master, width=700, height=600)
> > w.pack(expand = YES, fill = BOTH)
>
> > def mapper():
> >     mapq = PhotoImage(file = 'C:\Users\saftarn\Desktop\world-map.gif')
> >     w.create_image(10, 10, image = mapq, anchor = NW)
>
> > def key(event):
> >     print "pressed", repr(event.char)
>
> > def callback(event):
> >     w.focus_set()
> >     print "clicked at", event.x, event.y
> >     mapper()
> >     print 'yo'
> >     square = w.create_oval(event.x-5,event.y-5,event.x+5,event.y+5,
> > fill="black")
>
> > w.bind("", key)
> > w.bind("", callback)
> > w.pack()
>
> > mainloop()
>
> Python doesn't know that the Tk side still needs the image and frees the
> memory when `mapper()` is done and `mapq` the only name to the `PhotoImage`
> instance goes out of scope.
>
> Ciao,
>         Marc 'BlackJack' Rintsch


...so you should do something like this(untested):


def mapper(height, width, widget, img, position):
   widget.create_image(height, width, image=img, anchor=position)

w = Canvas(master, width=700, height=600)
w.pack(expand = YES, fill = BOTH)

#Create a permanent reference to the image, i.e. the variable is not
#created inside a function:
my_img = PhotoImage(file = 'C:\Users\saftarn\Desktop\world-map.gif')

mapper(10, 10, w, my_img, NW)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 Basic authentication, what am I doing wrong?

2008-04-13 Thread 7stud
Michel Bouwmans wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> Hey everybody,
>
> I'm having a little problem with urllib2 and Basic HTTP authentication.
>
> I have the following code:
>
> auth = urllib2.HTTPPasswordMgrWithDefaultRealm()
> auth.add_password(None, 'https://webmail.osg-erasmus.nl/oneNet/NetStorage/',
> user, password)
> authhandler = urllib2.HTTPBasicAuthHandler(auth)
>
> opener = urllib2.build_opener(auth)
> opener.addheaders = [('User-agent', 'Mozilla/5.0 Something/1.0')]
>
> try:
> return
> self.opener.open('https://webmail.osg-erasmus.nl/oneNet/NetStorage/')
> except urllib2.HTTPError, e:
> print e.code
> print e.headers
>
> This however does not allow me to authenticate. I keep getting back a 401:
>
> 401
> Date: Sun, 13 Apr 2008 18:11:32 GMT
> Server: Apache/2.0.54 (NETWARE) mod_perl/1.99_12 Perl/v5.8.4 PHP/5.0.5
> mod_nsn/1.0_0 mod_jk/1.2.14
> Set-Cookie: novellsession1=8KuAO0iLyAEAAA==; path=/
> WWW-Authenticate: Basic realm="ERASMUS-TREE"
> Vary: accept-language,accept-charset
> Accept-Ranges: bytes
> Connection: close
> Transfer-Encoding: chunked
> Content-Type: text/html; charset=iso-8859-1
> Content-Language: en
>
> Using this nice class (adapted to urllib2) as a basehandler I see that no
> Authentication-header is being send out:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440574
>
> What am I doing wrong here? I spend almost my entire free time today on this
> and couldn't find any problem with my code, anyone else has a thought?
> Thanks in advance.


Can you get something like the following to work:

import urllib2

pword_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
pword_manager.add_password(None, 'http://localhost/
pwordProtectedStuff/', 'jane', 'janes_password')

authentication_handler = urllib2.HTTPBasicAuthHandler(pword_manager)
my_custom_urlopen_function =
urllib2.build_opener(authentication_handler)
urllib2.install_opener(my_custom_urlopen_function)

f = urllib2.urlopen('http://localhost/pwordProtectedStuff/test.htm')
print f.read()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about Boost.Python & bjam

2008-04-12 Thread 7stud
On Apr 12, 4:53 am, Till Kranz <[EMAIL PROTECTED]
goettingen.de> wrote:
> Hi,
>
> I tried to get started with Boost.Python. unfortunately I never used the
> bjam build system before. As it is explained in the documentation I tried
> to adapt the the files form the examples directory. I copied 'Jamroot',
> 'boost_build.jam' and 'extending.cpp' to '~/test/'. But I am lost as to
> what to do now. The docu says I should adjust the 'use-project' path. But
> what to? I am using a Gentoo system, so there is no boost directory. The
> librarys are in /usr/lib/ the boost build stuff is in
> /usr/share/boost-build and the include files are in /usr/include/boost/.
>
> If anyone could post minimal Jamroot & boost_build.jam files for this
> setting I would be realy grateful. I think I will be able to figure out
> everything else, once I have a working example.
>
> Thanks in advance
>
>         Till

A few months ago, I spent a whole day trying to install boost python.
I failed.  After that, I decided I'd never go near boost again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, a lot of buttons, make prog shorter?

2008-04-06 Thread 7stud
On Apr 6, 8:50 pm, [EMAIL PROTECTED] wrote:
> should i not use self. in Clean() and Calculate() either?
>

You probably shouldn't be using classes at all.  When you are trying
to learn the basics of a language, you don't want to complicate things
further with classes.  Copying a program off the internet and trying
to modify it for your own purposes is usually going to be a lot more
work than writing the whole thing from scratch yourself.  In addition,
when you write the whole thing yourself, you'll have a better
understanding of how things work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, a lot of buttons, make prog shorter?

2008-04-06 Thread 7stud
On Apr 6, 4:12 pm, 7stud <[EMAIL PROTECTED]> wrote:
> You said you were an experienced programmer, but you keep posting code
> with the same mistakes over and over again.  Why are you attaching the
> buttons to self?

Remember this:

> Another thing you should be aware of: self is like a class wide
> bulletin board. If you are writing code inside a class method, and
> there is data that you want code inside another class method to be
> able to see, then post the data on the class wide bulletin board, i.e.
> attach it to self.  But in your code, you are doing this:
>
> self.btnDisplay = Button(self, text="7", default=ACTIVE)
> self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> self.btnDisplay = Button(self, text="8", default=ACTIVE)
> self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
> As a result, your code continually overwrites self.btnDisplay.  That
> means you aren't preserving the data assigned to self.btnDisplay.
> Therefore, the data does not need to be posted on the class wide
> bulletin board for other class methods to see.  So just write:
>
> btnDisplay = Button(self, text="7", default=ACTIVE)
> btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> btnDisplay = Button(self, text="8", default=ACTIVE)
> btnDisplay.grid(row=5, column=1, padx=5, pady=5)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, a lot of buttons, make prog shorter?

2008-04-06 Thread 7stud
On Apr 6, 1:59 pm, [EMAIL PROTECTED] wrote:
> is there anyway to make this shorter? i hate having these big blocks
> of similar-looking code, very unaesthetic.
> maybe doesnt matter good-code-wise?
> anyway can i make some function that makes this shorter?
> like put the etiquettes on the button froma string of
> '123+456-789*0Cr/' ?
> problem is the command and lambda-func for each button is different.
>
>         self.btnDisplay = Button(self,text='1',command=lambda
> n="1":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=3, column=0)
>
>         self.btnDisplay = Button(self,text='2',command=lambda
> n="2":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=3, column=1)
>
>         self.btnDisplay = Button(self,text='3',command=lambda
> n="3":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=3, column=2)
>
>         self.btnDisplay = Button(self,text='+',command=lambda
> n="+":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=3, column=3)
>
>         self.btnDisplay = Button(self,text='4',command=lambda
> n="4":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=4, column=0)
>
>         self.btnDisplay = Button(self,text='5',command=lambda
> n="5":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=4, column=1)
>
>         self.btnDisplay = Button(self,text='6',command=lambda
> n="6":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=4, column=2)
>
>         self.btnDisplay = Button(self,text='-',command=lambda
> n="-":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=4, column=3)
>
>         self.btnDisplay = Button(self,text='7',command=lambda
> n="7":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=5, column=0)
>
>         self.btnDisplay = Button(self,text='8',command=lambda
> n="8":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=5, column=1)
>
>         self.btnDisplay = Button(self,text='9',command=lambda
> n="9":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=5, column=2)
>
>         self.btnDisplay = Button(self,text='*',command=lambda
> n="*":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=5, column=3)
>
>         self.btnDisplay = Button(self,text='0',command=lambda
> n="0":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=6, column=0)
>
>         self.btnDisplay =
> Button(self,text='C',command=self.Clean,width=2,height=2)
>         self.btnDisplay.grid(row=6, column=1)
>
>         self.btnDisplay = Button(self,text='r',command=lambda
> n="r":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=6, column=2)
>
>         self.btnDisplay = Button(self,text='/',command=lambda
> n="/":self.Display(n),width=2,height=2)
>         self.btnDisplay.grid(row=6, column=3)

You said you were an experienced programmer, but you keep posting code
with the same mistakes over and over again.  Why are you attaching the
buttons to self?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, add pressed buttons onto string display string, how to?

2008-04-05 Thread 7stud
> > Just like the message says: You are trying to use `str` (on the right hand
> > side of the assignment) before anything is bound to that name.
>
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> i know but i want the variable str(which i found out is a reserved
> word so i changed it) to be accessible all over __init__ right?
>

"all over __init__" ? You could practice with a trivial example to
discover how things work in python:

def f():
num = 10
print num

f()

def g():
print num
num = 10

g()


> so i tried to delcare it in __init__ in the beginning of the framework
> class but then when i access it in the method Display i get that
> error.
>
> so how should i declare this variable to be able to access it
> everywhere?
>

You don't declare variables in python.  You just start using a
variable when you need it.  In other words you don't do this:

string my_str
my_str = "hello"

You just write:

my_str = "hello"


> i want another method "calculate" that can access the same string
> later and do the calculations(writing some other code now that will
> read and interpret that).

Does this look familiar:

> Another thing you should be aware of: self is like a class wide
> bulletin board. If you are writing code inside a class method, and
> there is data that you want code inside another class method to be
> able to see, then post the data on the class wide bulletin board, i.e.
> attach it to self.  But in your code, you are doing this:
>
> self.btnDisplay = Button(self, text="7", default=ACTIVE)
> self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> self.btnDisplay = Button(self, text="8", default=ACTIVE)
> self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
> As a result, your code continually overwrites self.btnDisplay.  That
> means you aren't preserving the data assigned to self.btnDisplay.
> Therefore, the data does not need to be posted on the class wide
> bulletin board for other class methods to see.  So just write:
>
> btnDisplay = Button(self, text="7", default=ACTIVE)
> btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> btnDisplay = Button(self, text="8", default=ACTIVE)
> btnDisplay.grid(row=5, column=1, padx=5, pady=5)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, add pressed buttons onto string display string, how to?

2008-04-05 Thread 7stud
On Apr 5, 1:55 pm, 7stud <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > using tkinter and python i now have a small App (that will hopefully
> > soon be a fully functioning calculator) where u can push buttons and
> > the corresponding number or operator is shown.
>
> > when u press 1, "1" appears on the screen, pres + and "+" appears etc.
>
> > at the moment every output overwrites the previous so what i want to
> > do is obviosuly to add every new output to a string so that i can read
> > the string and perform the calculation.
>
> > so i want:
> > *  when pushing the button push the token of the button onto a string
> > * display the new string, ie "1+2" for example
> > * want to be able to access this string when pressing calculate so i
> > can figure out which operators should
> > be done first so it can solve something like this: "(1+2*3)(3-4/2)"
> > and not just simple "1+2"-stuff.
>
> > do i have to have some global string-variable in the GUIframework
> > then? im not sure where to start...
>
> input = "hello"
> input += " world"
> print input
>
> --output:--
> hello
>
> A caculator program is pretty complex.  Based on your rudimentary
> questions, I don't think you have enough programming experience to
> tackle a project like that yet.

--output:--
hello world
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, add pressed buttons onto string display string, how to?

2008-04-05 Thread 7stud


[EMAIL PROTECTED] wrote:
> using tkinter and python i now have a small App (that will hopefully
> soon be a fully functioning calculator) where u can push buttons and
> the corresponding number or operator is shown.
>
> when u press 1, "1" appears on the screen, pres + and "+" appears etc.
>
> at the moment every output overwrites the previous so what i want to
> do is obviosuly to add every new output to a string so that i can read
> the string and perform the calculation.
>
> so i want:
> *  when pushing the button push the token of the button onto a string
> * display the new string, ie "1+2" for example
> * want to be able to access this string when pressing calculate so i
> can figure out which operators should
> be done first so it can solve something like this: "(1+2*3)(3-4/2)"
> and not just simple "1+2"-stuff.
>
> do i have to have some global string-variable in the GUIframework
> then? im not sure where to start...
>

input = "hello"
input += " world"
print input

--output:--
hello

A caculator program is pretty complex.  Based on your rudimentary
questions, I don't think you have enough programming experience to
tackle a project like that yet.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-05 Thread 7stud
On Apr 5, 12:02 am, [EMAIL PROTECTED] wrote:
> am i not doing that then? did u look at the code? where do i add the
> bind if this:
> btnDisplay = Button(self, text="1", command=self.Display)
>         btnDisplay.grid(row=3, column=0, padx=5, pady=5)
>
> is not enough?
>
> def Display(self, event_obj):
>         button = event_obj.widget
>         text = button.cget("text")
>
>         if text=="1":
>             print 1
>
> i get this exception so i need to pass another argument? im passing 2
> no?
>

1) Post the line in your code that passes two arguments to Display.

2) Post the line in yoru code where you call Display. "call" means
"execute", and '()' is used after a function name to execute the
function.


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


Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-05 Thread 7stud
[EMAIL PROTECTED] wrote:
>
> one thing i dont rally get, i ahve to add my_button.bind() somewhere?
> i changed the stuff u said though and i get this error(the program
> executes though and i can press the buttons):
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
> return self.func(*args)
> TypeError: Display() takes exactly 2 arguments (1 given)
>
>
> current version:
> #! /usr/bin/env python
> from Tkinter import *
> import tkMessageBox
>
> class GUIFramework(Frame):
> """This is the GUI"""
>
> def __init__(self,master=None):
> """Initialize yourself"""
>
> """Initialise the base class"""
> Frame.__init__(self,master)
>
> """Set the Window Title"""
> self.master.title("Calculator")
>
> """Display the main window"
> with a little bit of padding"""
> self.grid(padx=10,pady=10)
> self.CreateWidgets()
>
> def CreateWidgets(self):
>
> enText = Entry(self)
> enText.grid(row=0, column=0, columnspan=8, padx=5, pady=5)
>
> enText = Entry(self)
> enText.grid(row=1, column=0, columnspan=8, padx=5, pady=5)
>
> btnDisplay = Button(self, text="1", command=self.Display)
> btnDisplay.grid(row=3, column=0, padx=5, pady=5)


You still have this in your code:

btnDisplay = Button(self, text="1", command=self.Display)

I suggest you reread my earlier post again.   Or, follow the advice
given by Marc 'BlackJack' Rintsch (preferable).  But whatever you do,
don't use both command and bind().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread 7stud
On Apr 4, 7:06 pm, [EMAIL PROTECTED] wrote:
> 1st question:
>
> when i run this program 1 will be printed into the interpreter when i
> run it BUT without me clicking the actual button.
> when i then click the button "1", nothing happens.
>
> obv i dont want any output when i dont push the button but i want it
> when i do.
>
> what am i doing wrong here?
>
> 2nd question:
>
> i want all the buttons to have the same size. i thought i should use
> row/columnspan but i dont get that to work.
> how should i do?
>
> [code]
> #! /usr/bin/env python
> from Tkinter import *
> import tkMessageBox
>
> class GUIFramework(Frame):
>     """This is the GUI"""
>
>     def __init__(self,master=None):
>         """Initialize yourself"""
>
>         """Initialise the base class"""
>         Frame.__init__(self,master)
>
>         """Set the Window Title"""
>         self.master.title("Calculator")
>
>         """Display the main window"
>         with a little bit of padding"""
>         self.grid(padx=10,pady=10)
>         self.CreateWidgets()
>
>     def CreateWidgets(self):
>
>         self.enText = Entry(self)
>         self.enText.grid(row=0, column=0, columnspan=8, padx=5,
> pady=5)
>
>         self.enText = Entry(self)
>         self.enText.grid(row=1, column=0, columnspan=8, padx=5,
> pady=5)
>
>         self.btnDisplay = Button(self, text="1",
> command=self.Display(1))
>         self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="2", default=ACTIVE)
>         self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="3", default=ACTIVE)
>         self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="+", default=ACTIVE)
>         self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="4", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="5", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="6", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="-", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="7", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="8", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="9", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="*", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="0", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="C", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="r", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="/", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)
>
>     def Display(self, xbtn):
>         if xbtn==1:
>             print 1
>
> if __name__ == "__main__":
>     guiFrame = GUIFramework()
>     guiFrame.mainloop()
>
> [/code]



If you have this function:

def f():
   print 1
   return 10

and you write:

result = f()

The '()' is the function execution operator; it tells python to
execute the function.  In this case, the function executes, and then
the return value of the function is assigned to the variable result.
If a function does not have a return statement, then the function
returns None by default.

The same thing is happening in this portion of your code:

command = self.Display(1)

That code tells python to execute the Display function and assign the
function's return value to the variable command.  As a result Display
executes and 1 is displayed.  Then since Dispay does not have a return
statement, None is returned, and None is assigned to command.
Obviously, that is not what you want to do.

What you want to do is assign a "function reference" to command so
that python can execute the function sometime later when you click on
the button.  A function reference is just the function name without
the '()' after it.  So you would write:

command = self.Display

But writing it like that doesn't allow *you* to pass any arguments to
Display().  In addition, *tkinter* does not pass any arguments to
Display when tkinter calls Display in response to a button click.  As
a result, there is no way to pass an argument to Display.

However, there is another way to cause a function 

Re: Is there any way to say ignore case with "in"?

2008-04-04 Thread 7stud
On Apr 4, 2:43 pm, [EMAIL PROTECTED] wrote:
> Is there any way in python to say
>
>     if string1 in string2:
>         
>
> ignoring the case of string1 and string2?
>
> I know I could use:-
>
>     if lower(string1) in lower(string2):
>         
>
> but it somehow feels there ought to be an easier (tidier?) way.
>

Easier?  You mean like some kind of mind meld?

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


Re: Parsing HTML?

2008-04-03 Thread 7stud
On Apr 3, 12:39 am, [EMAIL PROTECTED] wrote:
> BeautifulSoup does what I need it to.  Though, I was hoping to find
> something that would let me work with the DOM the way JavaScript can
> work with web browsers' implementations of the DOM.  Specifically, I'd
> like to be able to access the innerHTML element of a DOM element.
> Python's built-in HTMLParser is SAX-based, so I don't want to use
> that, and the minidom doesn't appear to implement this part of the
> DOM.
>

innerHTML has never been part of the DOM.  It is however a defacto
browser standard.  That's probably why you aren't having any luck
using a python module that implements the DOM.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class / module introspection?

2008-04-02 Thread 7stud
On Apr 2, 1:27 pm, Brian Munroe <[EMAIL PROTECTED]> wrote:
> On Apr 2, 12:07 pm, Brian Munroe <[EMAIL PROTECTED]> wrote:
>
>
>
> > This gives me ['system1','system2'] - which I can then use __import__
> > on.
>
> Addendum, thanks Bruno!
>
> I also required the helper function (my_import) from the Python docs
>

You don't need that helper function, which is a little tricky to
follow:

If you have a module name as a string, you can use the builtin
function __import__ to import the module, e.g.

x = __import__("mymod")
x.myfunc()

Note that you have to assign the return value of __import__ to a
variable.  Thereafter you use the variable to access the module's
functions.

However, when you use __import__ with a package, it behaves in a
peculiar manner: it returns the top level package object.  For
example, if you write:

x = __import__("mypackage.subpack.myfuncs")


then x is a reference to mypackage--not mypackage.subpack.myfuncs.  In
order to execute a function in the module myfuncs, you need to write:

x.subpack.myfuncs.f().

Or, if you check the docs, you can make __import__ return the
rightmost module in the module string by writing:

x = __import__("mypackage.subpack.myfuncs", globals(), locals(),
["subpack.myfuncs"])

The last argument is what makes __import__ return a lower level module
in the package hierarchy.


To solve your problem, you can do something like the following:

Directory structure
---

../mypackage
   __init__.py

   /system1
   __init__.py
   myfuncs.py

   /system2
   __init__.py
   myfuncs.py


system1/myfuncs.py

def f():
print "system1 here"


system2/myfuncs.py
-
def f():
print "system2 here"




import sys
import os

#Get all the file names contained in mypackage:
fnames = os.listdir("../mypackage")
print fnames

#Separate out the directory names(which are the sub packages):
os.chdir("../mypackage") #so abspath() below can construct full paths
package_dirs = []

for fname in fnames:
abs_path = os.path.abspath(fname)  #need full path for isdir()
print abs_path,

if os.path.isdir(abs_path):
print 'dir'
package_dirs.append(fname)
else:
print 'file'

print package_dirs

sys.path.append("../") #directs python to search the specified
   #dir for any modules that are imported

#Import the sub packages:
for dir in package_dirs:
modname = "%s.%s.%s" % ("mypackage", dir, "myfuncs")
modname_minus_toplevel_packname = "%s.%s" % (dir, "myfuncs")

mod = __import__(modname, globals(), locals(),
[modname_minus_toplevel_packname])
mod.f()



--output:--
['__init__.py', '__init__.pyc', 'system1', 'system2']
/Users/me/2testing/mypackage/__init__.py file
/Users/me/2testing/mypackage/__init__.pyc file
/Users/me/2testing/mypackage/system1 dir
/Users/me/2testing/mypackage/system2 dir
['system1', 'system2']
system1 here
system2 here



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


Re: XML Parsing

2008-04-01 Thread 7stud
On Apr 1, 1:42 pm, Alok Kothari <[EMAIL PROTECTED]> wrote:
> Hello,
>           I am new to XML parsing.Could you kindly tell me whats the
> problem with the following code:
>
> import xml.dom.minidom
> import xml.parsers.expat
> document = """Lettermanis token>betterthan token>JayLeno"""
>
> # 3 handler functions
> def start_element(name, attrs):
>     print 'Start element:', name, attrs
> def end_element(name):
>     print 'End element:', name
> def char_data(data):
>     print 'Character data:', repr(data)
>
> p = xml.parsers.expat.ParserCreate()
>
> p.StartElementHandler = start_element
> p.EndElementHandler = end_element
> p.CharacterDataHandler = char_data
> p.Parse(document, 1)
>
> OUTPUT:
>
> Start element: token {u'pos': u'nn'}
> Character data: u'Letterman'
> End element: token
>
> Traceback (most recent call last):
>   File "C:/Python25/Programs/eg.py", line 20, in 
>     p.Parse(document, 1)
> ExpatError: junk after document element: line 1, column 33


I don't know if you are aware of the BeautifulSoup module:


import BeautifulSoup as bs

xml = """LettermanisbetterthanJayLeno"""

doc = bs.BeautifulStoneSoup(xml)

tokens = doc.findAll("token")
for token in tokens:
for attr in token.attrs:
print "%s : %s" % attr


print token.string

--output:--
pos : nn
Letterman
pos : bez
is
pos : jjr
better
pos : cs
than
pos : np
Jay
pos : np
Leno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BeautiflSoup -- getting all the attributes of a tag?

2008-04-01 Thread 7stud
On Apr 1, 5:25 pm, 7stud <[EMAIL PROTECTED]> wrote:
> You can treat a tag like a dictionary to obtain a specific attribute:
>
> import BeautifulSoup as bs
>
> html = "hello"
>
> doc = bs.BeautifulSoup(html)
> div = doc.find("div")
> print div
> print div["x"]
>
> --output:--
> a
>
> But you can't iterate over a tag to get all the attributes:
>
> import BeautifulSoup as bs
>
> html = "hello"
>
> doc = bs.BeautifulSoup(html)
> div = doc.find("div")
>
> for key in div:
>     print key, div[key]
>
> --output:--
> hello
> Traceback (most recent call last):
>   File "test1.py", line 9, in ?
>     print key, div[key]
>   File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
> python2.4/site-packages/BeautifulSoup.py", line 430, in __getitem__
>     return self._getAttrMap()[key]
> KeyError: u'hello'
>
> How can you get all the attributes when you don't know the attribute
> names ahead of time?

I figured it out:


import BeautifulSoup as bs

html = "hello"

doc = bs.BeautifulSoup(html)
div = doc.find("div")

for attr, val in div.attrs:
print "%s:%s" % (attr, val)

--output:--
x:a
y:b
z:c
-- 
http://mail.python.org/mailman/listinfo/python-list


BeautiflSoup -- getting all the attributes of a tag?

2008-04-01 Thread 7stud
You can treat a tag like a dictionary to obtain a specific attribute:

import BeautifulSoup as bs

html = "hello"

doc = bs.BeautifulSoup(html)
div = doc.find("div")
print div
print div["x"]

--output:--
a

But you can't iterate over a tag to get all the attributes:

import BeautifulSoup as bs

html = "hello"

doc = bs.BeautifulSoup(html)
div = doc.find("div")

for key in div:
print key, div[key]

--output:--
hello
Traceback (most recent call last):
  File "test1.py", line 9, in ?
print key, div[key]
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/site-packages/BeautifulSoup.py", line 430, in __getitem__
return self._getAttrMap()[key]
KeyError: u'hello'

How can you get all the attributes when you don't know the attribute
names ahead of time?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for indent advice howto in emacs python-mode

2008-03-31 Thread 7stud
On Mar 31, 10:32 am, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
> Here's what I want to do:
>
> if ( ( v == 1 )
>    or ( v == 2 )
>    or ( v == 3 ) ):
>      pass
>

python indenting = 4 spaces
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python persistence

2008-03-31 Thread 7stud
On Mar 31, 5:31 pm, [EMAIL PROTECTED] wrote:
> Can you have a Python object stored entirely on disk?

import cPickle as cp

class Dog(object):
def __init__(self, name):
self.name = name

d = Dog("Spot")

f = open("data.txt", "w")
cp.dump(d, f)
f.close()

f = open("data.txt")
stored_obj = cp.load(f)
print stored_obj.name

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


Re: problem with CGIHTTPServer

2008-03-28 Thread 7stud
On Mar 28, 10:12 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Fri, 28 Mar 2008 12:38:45 -0300, 7stud <[EMAIL PROTECTED]>  
> escribió:
>
> > After I start the server script, load the html page in my browser, and
> > click on the link, I get the desired output in my browser, but the
> > server script outputs the following in my terminal:
>
> > localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/
> > 1.1" 200 -
> > localhost - - [28/Mar/2008 08:51:22] code 404, message File not found
> > localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 -
>
> > What are the error messages on lines two and three?
>
> Line 3 is your browser (IE, I presume?) asking for an icon for the site.
> Seehttp://en.wikipedia.org/wiki/Favicon
>

Safari.


> I don't know about line 2, maybe it's just a diagnostic message related to  
> line 3. Try refreshing the page, or using an inexistent url to see if it  
> still appears. Or put any icon as /favicon.ico to make your browser happy.
>

I searched for a .ico file on my computer, then copied it into the
same directory as the server program, and renamed the .ico file:

favcion.ico

Then I loaded my html file in Safari and clicked on the link, and this
was the output:

localhost - - [28/Mar/2008 19:30:31] "GET /my_cgi_scripts/test.py HTTP/
1.1" 200 -
localhost - - [28/Mar/2008 19:30:31] "GET /favicon.ico HTTP/1.1" 200 -

So, it looks like Safari automatically requests a .ico file from a
server.  Thanks.

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


problem with CGIHTTPServer

2008-03-28 Thread 7stud

1) I have this simple cgi server:


import CGIHTTPServer
import BaseHTTPServer

class MyRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ['/my_cgi_scripts']

server = BaseHTTPServer.HTTPServer(
('', 8111),
MyRequestHandler
)


server.serve_forever()


2) I have this simple python script:

test.py

#!/usr/bin/env python

import cgitb; cgitb.enable()
import cgi


print "Content-type: text/html"
print
print "hello"


3) I have this simple html page with a link that calls test.py:








http://localhost:8111/my_cgi_scripts/test.py";>click me






My directory structure looks like this:

../dir1
---myserver.py
---/my_cgi_scripts
test.py

After I start the server script, load the html page in my browser, and
click on the link, I get the desired output in my browser, but the
server script outputs the following in my terminal:

localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/
1.1" 200 -
localhost - - [28/Mar/2008 08:51:22] code 404, message File not found
localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 -


What are the error messages on lines two and three?

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


Re: Do any of you recommend Python as a first programming language?

2008-03-22 Thread 7stud
On Mar 22, 3:34 pm, bsoist <[EMAIL PROTECTED]> wrote:
> On Mar 22, 12:40 pm, jmDesktop <[EMAIL PROTECTED]> wrote:
>
> > For students 9th - 12th grade, with at least Algebra I.  Do you think
> > Python is a good first programming language for someone with zero
> > programming experience?  Using Linux and Python for first exposure to
> > programming languages and principles.
>
> > Thank you.
>
> Absolutely. I love using Python in "the real world" but it is
> fantastic for beginning programmers.
>
> Python enforces good habits and presents many opportunities to discuss
> programming from an academic perspective. Why does Python not have a
> switch or until statement? Why are very common objects (stack, queue,
> linked list) not builtin? etc.
>

Beginning programmers in grades 9-12 are not going to understand
issues like that, and it would be a mistake to try and introduce
them.  Beginning programmers should be concentrating their efforts on
learning the syntax of a language and basic constructs like for-loops
and if statements.  They will begin by writing simple "hello world"
style programs, and as their basic skills improve, the programs will
get a little more complex and require some more thought and some math
to solve the problems presented to them.  String formatting should
probably be introduced to help with formatting the output.  That is
about as far as things are going to go.

Terms like "Touring machines" and "lambda-calculus" are not going to
be mentioned anywhere in the course of study.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0]

2008-03-20 Thread 7stud
On Mar 20, 8:42 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message
>
> news:[EMAIL PROTECTED]
> | "Daniel Fetchinson" <[EMAIL PROTECTED]> writes:
> | > Is it just me or others also think that it would be a major loss to
> | > remove tkinter from the python core?
> |
> | That would be terrible.  Every time I've tried to use one of the other
> | packages it has led to installation hell.  Tkinter isn't great, but
> | it's extremely useful to have a gui module that's present
> | automatically in every compete Python installation and that is
> | reasonably cross platform.  I can write a Python/Tkinter app under
> | Linux and send it to Windows users and they can run it after a single,
> | very simple Python installation from the Windows .msi.  I have no
> | Windows development tools whatsoever and very limited access to
> | Windows boxes, so any Python code I deploy on Windows can't rely on
> | any non-Python code outside of the stdlib.
> |
> | Also, because of tkinter's inherent limitations, I have the impression
> | that upgrading it to the latest and greatest tcl/tk release wouldn't
> | improve it much over the useful but low-rent module that it already is.
> | Therefore, that supposed "benefit" of splitting it out to an external
> | package is not much of a benefit.
> |
> | One of Python's traditionally best attractions has been the depth of
> | its standard libraries, and backing away from that would be plain
> | self-destructive.  Python needs more stuff in its stdlib, not less.
> | If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard
> | distro.  If that happens (i.e. some new toolkit is brought in and
> | declared to be the standard) then it might be ok to drop Tkinter but
> | it certainly shouldn't be dropped without a replacement.
>
> I think this nicely summarizes the case against dropping tkinter (and
> indeed, the case against shrinking the stdlib), like some devs (who mostly
> une *nix) want to do.  Perhaps someone can forward it to the lib-sig and/or
> the Py3-devel lists.
>
> tjr

I think one of the advantages that python has over ruby is that python
comes with tkinter.  For me, tkinter worked from the get go after I
installed python.  I don't know if that's because my os already had
the necessary tcl/tk framework set up or not, but not having to go
through installation hell to get it working was nice.

On the other hand, Ruby doesn't come with a gui framework.  And trying
to get Ruby tk working is a nightmare that I suspect many new
programmers will never accomplish, and therefore gui programming will
largely be inaccessible to them.

Since the adherents to the various languages like to list the reasons
why their language is better, removing tkinter from python will only
will make python's list shorter.


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


Re: if __name__ == '__main__':

2008-03-20 Thread 7stud
On Mar 20, 10:21 am, "Simon Brunning" <[EMAIL PROTECTED]>
wrote:
> On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde <[EMAIL PROTECTED]> wrote:
> > Hi,
> > I am new to the python and not getting meaning of following line,
>
> > if __name__ == '__main__':
> >       main()
>

The if statement is used to skip the code after the if statement in
certain situations.  If that if statement is in a file named test1.py,
and you issue this command:

$ python test1.py

then the code after the if statement will execute.  That's because
python assigns the string '__main__' to the variable __name__ when the
program starts

However, if you do this:

---
#test1.py
def my_func(num):
print num * 2


if __name__ == "__main__":
print "Testing my func:", my_func(10)



#test2.py
import test1

test1.my_func(5)

---

...and you issue the command:

$python test2.py

Then the code after the if statement in test1.py will not execute.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is hash map data structure available in Python?

2008-03-19 Thread 7stud
On Mar 19, 2:40 am, grbgooglefan <[EMAIL PROTECTED]> wrote:
> Hi,
> I have a situation that I need to search a name in a big list of names
> in my Python embedded interpreter. I am planning to use hash map for
> quicker search.
> How do I create hash map in Python?
> Can you please guide me to some documentation or tutorial which
> provides information on creating, editing, searching through hash map
> in Python?
> Thanks.

#creating:
my_dict = {'a':1, 'b':2, 'c':3}

#editing:
my_dict['a'] = 10

#searching:
result = my_dict.get('a', None)
print result  //10

result = my_dict.get('f', None)
print result  //None
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help Starting Out

2008-03-18 Thread 7stud
On Mar 18, 10:10 am, jmDesktop <[EMAIL PROTECTED]> wrote:
> Hi, I would like to start using Python, but am unsure where to begin.
> I know how to look up a tutorial and learn the language, but not what
> all technologies to use.  

I think you are getting ahead of yourself.  Get the book Learning
Python(3rd edition), which just came out, and start at the beginning.
I think the proper order is to learn the basics first, then learn an
application of the language that you are interested in, i.e. web
programming.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ord function problem from newbie

2008-03-17 Thread 7stud
[EMAIL PROTECTED] wrote:
>  I convert all to lowercase,
>
> import string
>
>   small = string.lower(name)
>   print "Here is the calculated value:"
>
> print small
>   for ch in small:
>   v = ord(ch)-96
> print v
>

I don't know if you are using an out of date book or what, but
generally you are not going to be importing string.  For example,

my_str = "HELLO"
small = my_str.lower()
print small

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


Re: Why does my compiler say invalid syntax then highlight...?

2008-03-10 Thread 7stud
On Mar 10, 9:44 pm, Nathan Pinno <[EMAIL PROTECTED]> wrote:
> Why does my compiler say invalid syntax and then highlight the
> quotation marks in the following code:
>
> # This program is to find primes.
> primes = []
> import math
> import gmpy
> while 1:
>     run = int(raw_input("Do you want to calculate primes? 1 = yes and
> 2 = no. "))
>     if run == 1:
>         y = int(raw_input("What number do you want to use as the final
> number to calculate with? "))
>         x = int(raw_input("What number do you want to start
> calculating primes from? "))
>         while x < 2:
>             print "Number must be at least 2 for math reasons."
>         else:
>             while x < y:
>                 prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x)
>                 if prime < 0:
>                     primes.append(x)
>                 else:
>                     print x " is not prime. " # highlights the final "
> here
>                 x = x + 1
>             print primes
>     elif run == 2:
>         break
>     else:
>         print "Sorry, not a choice. Please enter your choice again."
> print "Goodbye."
>
> How do I fix such an invalid syntax?
>
> TIA,
> Nathan Pinno

Rather, try running this:

print 10 "Hello world."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does my compiler say invalid syntax then highlight...?

2008-03-10 Thread 7stud
On Mar 10, 9:44 pm, Nathan Pinno <[EMAIL PROTECTED]> wrote:
> Why does my compiler say invalid syntax and then highlight the
> quotation marks in the following code:
>
> # This program is to find primes.
> primes = []
> import math
> import gmpy
> while 1:
>     run = int(raw_input("Do you want to calculate primes? 1 = yes and
> 2 = no. "))
>     if run == 1:
>         y = int(raw_input("What number do you want to use as the final
> number to calculate with? "))
>         x = int(raw_input("What number do you want to start
> calculating primes from? "))
>         while x < 2:
>             print "Number must be at least 2 for math reasons."
>         else:
>             while x < y:
>                 prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x)
>                 if prime < 0:
>                     primes.append(x)
>                 else:
>                     print x " is not prime. " # highlights the final "
> here
>                 x = x + 1
>             print primes
>     elif run == 2:
>         break
>     else:
>         print "Sorry, not a choice. Please enter your choice again."
> print "Goodbye."
>
> How do I fix such an invalid syntax?
>
> TIA,
> Nathan Pinno

Try running this:

input = raw_input("Hello
world.")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tcp

2008-03-02 Thread 7stud
On Mar 2, 6:09 am, Gif <[EMAIL PROTECTED]> wrote:
> i have this small script which after some router configurations works.
>
> ##
>
> #! /usr/bin/python
> import socket
>
> HOST = ''
> PORT = 1515
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind((HOST, PORT))
> s.listen(1)
> conn, addr = s.accept()
> conn.send('HTTP/1.1 200 OK\r\n')
> conn.send('Content-Type: text/html\r\n')
> conn.send('Server: test/1.0\r\n\r\n')
> conn.send('test')
> s.close()
>
> ##
>
> as you see it listens to 1515 until a connection is established and
> then it accepts it...
> the problem is that when it accepts the connection it sends those
> strings and exits, but then it exits the program. i want it to listen
> to 1515 then accept a connection, send.. and then listen to the port
> again and again until new connections are found.
>
> i've been struggling with try..except,while and all kinds of loops but
> always new erros pop up, or it overflows.

while True:
  conn, addr = s.accept()
  ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: more pythonic

2008-02-28 Thread 7stud
On Feb 28, 4:48 am, 7stud <[EMAIL PROTECTED]> wrote:
>
> It's my understanding that the way you insert arguments into queries
> has to be done in a db specific way.  
>

Rather:

It's my understanding that the way you insert arguments into queries
*should* be done in a db specific way.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: more pythonic

2008-02-28 Thread 7stud
On Feb 28, 4:40 am, Temoto <[EMAIL PROTECTED]> wrote:
> Hello.
>
> There is a Django application, i need to place all its data into
> Access mdb file and send it to user.
> It seems to me that params filling for statement could be expressed in
> a more beautiful way.
> Since i'm very new to Python, i don't feel that, though.
>
> Could you tell your opinion on that snippet?
>
> 
>     sql = """insert into salesmanager
>         (employeeid, name, officelocation, departmentname, salary)
>         values (?, ?, ?, ?, ?);"""
>     params = []
>     for manager in Manager.objects.all():
>         params.append( (manager.id, manager.name, manager.office,
> manager.department, manager.salary) )
>     curs.executemany(sql, params)
> 

It's my understanding that the way you insert arguments into queries
has to be done in a db specific way.  If done in that way, your
queries will be protected against sql injection attacks, AND the query
strings will be constructed in a more efficient manner.

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


Re: threading/Queue: join() and task_done() not working? (deadlock)

2008-02-28 Thread 7stud
On Feb 28, 1:47 am, Gal Aviel <[EMAIL PROTECTED]> wrote:
> 7stud  yahoo.com> writes:
>
> > What is task_done()?  The python docs don't list any such function.
>
> I'm using Python 2.5 and it's in the docs ...

According to the docs, join() unblocks only after you call task_done()
for every item that was entered into the Queue.  However, just because
the Queue size is 1 doesn't mean there aren't other items waiting to
be added to the Queue.  With one item in the Queue, presumably the
task-count is 1.  But, if you get() an item out of the Queue and
another item is waiting to be added to the Queue, then it seems likely
that the task_count will jump to 2 immediately after calling get().
Thereafter, a call to task_done() will decrement the task_count to 1,
which means join() will continue blocking.

Please recognize that it is very difficult to debug imaginary code.
If you want some help that is more relevant, then post a short example
that demonstrates your problem.  Do not post some lengthy program with
cryptic variable names.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call by reference howto????

2008-02-27 Thread 7stud
On Feb 27, 5:02 pm, Tamer Higazi <[EMAIL PROTECTED]> wrote:
> Hi!
> Can somebody of you make me a sample how to define a function based on
> "call by reference" ???
>
> I am a python newbie and I am not getting smart how to define functions,
> that should modify the variable I passed by reference.
>
> thanks in advance
>
> Tamer

def my_func(x):
x[0] = 4


my_list = [3]
print my_list

my_func(my_list)
print my_list

--output:--
[3]
[4]



class MyData(object):
pass

def another_func(obj):
obj.val += 10


md = MyData()
md.val = 20
another_func(md)
print md.val

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


Re: threading/Queue: join() and task_done() not working? (deadlock)

2008-02-27 Thread 7stud

Gal Aviel wrote:
> Hello All,
>
> I'm seeing strange behavior where one thread waits on a queue using join() and
> the later (or so I think, according to order of the printing in STDOUT) 
> another
> thread calls task_done() on the very same queue,

What is task_done()?  The python docs don't list any such function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BaseHTTPServer and do_POST method

2008-02-27 Thread 7stud
On Feb 27, 5:33 am, rocksportrocker <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I am trying to implement a local server for storing and retrieving
> numerical data.
> So I use BaseHTTPServer as follows:
>
> -
>     from BaseHTTPServer import *
>
>     class Handler(BaseHTTPRequestHandler):
>
>         def do_POST(self):
>
>             print "POST"
>             self.send_response(200)
>
>     httpd = HTTPServer(("",8000), Handler)
>     httpd.serve_forever()
> -
>
> For testing I use:
>
> -
>
>     import httplib
>
>     data = "123456789o" * 100
>
>     conn = httplib.HTTPConnection("localhost:8000")
>     print conn.request("POST", "/", data)
>
> ---
>
> Executing this client, the server says:
>
>     error(10053, 'Software caused connection abort')
>
> If I add "conn.getresponse()" at the end of the test script, the
> message disapears, but the server hangs.
>
> Where is my mistake ?
>
> Greetings, Uwe.

I don't get that error.  On the server, I get the output:

POST
localhost - - [27/Feb/2008 06:49:13] "POST / HTTP/1.1" 200 -

and on the client I get:

None

I don't know what's causing the second line of output on the server.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to measure memory usage on Mac OSX ?

2008-02-26 Thread 7stud
On Feb 26, 3:43 am, "masayuki.takagi" <[EMAIL PROTECTED]> wrote:
> hi all,
>
> i want to measure memory usage of my python process on Mac OSX.
>
> i tired resource module, but it doesn't work on OSX.
>
> how can i get it ?
>
> thnx.
>
> -- masayuki takagi

#mac osx 10.4.7
import resource

print resource.getrusage(resource.RUSAGE_SELF)

--output:--
(0.009417, 0.020122, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,
0, 0)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: network programming: how does s.accept() work?

2008-02-26 Thread 7stud
On Feb 25, 10:00 pm, Roy Smith <[EMAIL PROTECTED]> wrote:
> In article
> <[EMAIL PROTECTED]>,
>
>  7stud <[EMAIL PROTECTED]> wrote:
> > But your claim that the server doesn't change its port flies in the
> > face of every description I've read about TCP connections and
> > accept().  The articles and books I've read all claim that the server
> > port 5053 is a 'listening' port only.  Thereafter, when a client sends
> > a request for a connection to the listening port, the accept() call on
> > the server creates a new socket for communication between the client
> > and server, and then the server goes back to listening on the original
> > socket.
>
> You're confusing "port" and "socket".
>
> A port is an external thing.  It exists in the minds and hearts of packets
> on the network, and in the RFCs which define the TCP protocol (UDP too, but
> let's keep this simple).
>
> A socket is an internal thing.  It is a programming abstraction.  Sockets
> can exist that aren't bound to ports, and several different sockets can be
> bound to the same port.  Just like there can be multiple file descriptors
> which are connected to a given file on disk.
>
> The TCP protocol defines a state machine which determines what packets
> should be sent in response when certain kinds of packets get received.  The
> protocol doesn't say how this state machine should be implemented (or even
> demands that it be implemented at all).  It only requires that a TCP host
> behave in a way which the state machine defines.
>
> In reality, whatever operating system you're running on almost certainly
> implements in the kernel a state machine as described by TCP.  That state
> machine has two sides.  On the outside is the network interface, which
> receives and transmits packets.  On the inside is the socket interface to
> user-mode applications.  The socket is just the API by which a user program
> interacts with the kernel to get it to do the desired things on the network
> interface(s).
>
> Now, what the articles and books say is that there is a listening SOCKET.  
> And when you accept a connection on that socket (i.e. a TCP three-way
> handshake is consummated on the network), the way the socket API deals with
> that is to generate a NEW socket (via the accept system call).  There
> really isn't any physical object that either socket represents.  They're
> both just programming abstractions.
>
> Does that help?

If two sockets are bound to the same host and port on the server, how
does data sent by the client get routed?  Can both sockets recv() the
data?

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


Re: network programming: how does s.accept() work?

2008-02-26 Thread 7stud
On Feb 25, 10:08 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> There can be many TCP connections to a server all using the same
> endpoint. Take a look at the traffic coming out of any busy web server:
> everything that comes out of the same server comes from port 80. That
> doesn't stop it listening for more connections on port 80.
>

---
When you surf the Web, say to http://www.google.com, your Web browser
is a client. The program you contact at Google is a server. When a
server is run, it sets up business at a certain port, say 80 in the
Web case. It then waits for clients to contact it. When a client does
so, the server will usually assign a new port, say 56399, specifically
for communication with that client, and then resume watching port 80
for new requests.
---
http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: network programming: how does s.accept() work?

2008-02-25 Thread 7stud
On Feb 25, 10:56 am, Thomas Bellman <[EMAIL PROTECTED]> wrote:
> 7stud <[EMAIL PROTECTED]> wrote:
> > The question I'm really trying to answer is: if a client connects to a
> > host at a specific port, but the server changes the port when it
> > creates a new socket with accept(), how does data sent by the client
> > arrive at the correct port?  Won't the client be sending data to the
> > original port e.g. port 5052 in the client code above?
>
> The answer is that the server *doesn't* change its port.  As you
> could see in the output of your server, the socket that accept()
> returned also had local port 5052.  Each *client* will however
> get a unique local port at *its* end.
>
> A TCP connection is identified by a four-tuple:
>
>     ( localaddr, localport, remoteaddr, remoteport )
>
> Note that what is local and what is remote is relative to which
> process you are looking from.  If the four-tuple for a specific
> TCP connection is ( 127.0.0.1, 5052, 127.0.0.1, 50816 ) in your
> server, it will be ( 127.0.0.1, 50816, 127.0.0.1, 5052 ) in the
> client for the very same TCP connection.
>
> Since your client hasn't bound its socket to a specific port, the
> kernel will chose a local port for you when you do a connect().
> The chosen port will be more or less random, but it will make
> sure that the four-tuple identifying the TCP connection will be
> unique.
>

You seem to be describing what I see:

server output-
original socket: ('0.0.0.0', 5053)
new socket, self: ('127.0.0.1', 5053)
new socket, peer: ('127.0.0.1', 49302)

original socket: ('0.0.0.0', 5053)
new socket, self: ('127.0.0.1', 5053)
new socket, peer: ('127.0.0.1', 49303)

---client1 output-
('0.0.0.0', 0)
('127.0.0.1', 49302)

---client2 output-
('0.0.0.0', 0)
('127.0.0.1', 49303)


But your claim that the server doesn't change its port flies in the
face of every description I've read about TCP connections and
accept().  The articles and books I've read all claim that the server
port 5053 is a 'listening' port only.  Thereafter, when a client sends
a request for a connection to the listening port, the accept() call on
the server creates a new socket for communication between the client
and server, and then the server goes back to listening on the original
socket.  Here are two sources for that claim:

Socket Programming How To:
http://www.amk.ca/python/howto/sockets/

Tutorial on Network Programming with Python:
http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf

In either case, there are still some things about the output that
don't make sense to me.  Why does the server initially report that its
ip address is 0.0.0.0:

original socket: ('0.0.0.0', 5053)

I would expect the reported ip address to be '127.0.0.1'.  Also, since
a socket is uniquely identified by an ip address and port number, then
the ('0.0.0.0', 5053) socket is not the same as this socket:

new socket, self: ('127.0.0.1', 5053)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any method to urlretrieve to a file the html source from a url with "Transfer-encoding": chunked

2008-02-25 Thread 7stud
On Feb 25, 8:25 am, Aldo Ceccarelli <[EMAIL PROTECTED]> wrote:
> Thank you All for your suggestions:
>
> I could finally assess that
>
> besides partial read from chunked url - by-passed thanks to a socket
> approach:
>
> f.i. this was good for 
> me:http://python.about.com/od/networkingwithpython/ss/beg_web_client_9.htm
>
> I have still two kind of problems that quit this post's aims (original
> url is redirected and has password protections too, I will go for
> these now)
>
> Again SUPER thanks to You All:-) Aldo

Don't use that code--it's merely a bare bones example.  Post the url
that is giving you problems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: network programming: how does s.accept() work?

2008-02-25 Thread 7stud
On Feb 25, 5:17 am, 7stud <[EMAIL PROTECTED]> wrote:
> On Feb 25, 4:08 am, 7stud <[EMAIL PROTECTED]> wrote:
>
>
>
> > The question I'm really trying to answer is: if a client connects to a
> > host at a specific port, but the server changes the port when it
> > creates a new socket with accept(), how does data sent by the client
> > arrive at the correct port?  Won't the client be sending data to the
> > original port e.g. port 5052 in the client code above?
>
> If I change the clients to this:
>
> import socket
> import time
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> host = 'localhost'
> port = 5052  #server port
>
> print s.getsockname()  #<NEW LINE
> s.connect((host, port))
> print s.getsockname()
>
> response = []
> while 1:
>     piece = s.recv(1024)
>     if piece == '':
>         break
>
>     response.append(piece)
>
> Then I get output from the clients like this:
>
> ('0.0.0.0', 0)
> ('127.0.0.1', 51439)
>
> ('0.0.0.0', 0)
> ('127.0.0.1', 51440)
>
> The server port 5052(i.e. the one used in connect()) is not listed
> there. That output indicates that the client socket is initially
> created with some place holder values, i.e. 0.0.0.0, 0.  Then accept()
> apparently sends a message back to the client that in effect says,
> "Hey, in the future send me data on port 51439."  Then the client
> fills in that port along with the ip address in its socket object.
> Thereafter, any data sent using that socket is sent to that port and
> that ip address.

Implicit in that description is that the client must get assigned a
port number before the call to connect(), or maybe the call to
connect() assigns a port number to the client.  In any case, the
server has to receive both the client's ip address and port number as
part of the client's request for a connection in order for the server
to know where to send the response.  The server then uses that ip
address and port number to send back a message to the client that
tells the client what port number future communications need to be
sent to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: network programming: how does s.accept() work?

2008-02-25 Thread 7stud
On Feb 25, 4:08 am, 7stud <[EMAIL PROTECTED]> wrote:
>
> The question I'm really trying to answer is: if a client connects to a
> host at a specific port, but the server changes the port when it
> creates a new socket with accept(), how does data sent by the client
> arrive at the correct port?  Won't the client be sending data to the
> original port e.g. port 5052 in the client code above?
>

If I change the clients to this:


import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = 'localhost'
port = 5052  #server port

print s.getsockname()  #<NEW LINE
s.connect((host, port))
print s.getsockname()

response = []
while 1:
piece = s.recv(1024)
if piece == '':
break

response.append(piece)


Then I get output from the clients like this:

('0.0.0.0', 0)
('127.0.0.1', 51439)

('0.0.0.0', 0)
('127.0.0.1', 51440)


The server port 5052(i.e. the one used in connect()) is not listed
there. That output indicates that the client socket is initially
created with some place holder values, i.e. 0.0.0.0, 0.  Then accept()
apparently sends a message back to the client that in effect says,
"Hey, in the future send me data on port 51439."  Then the client
fills in that port along with the ip address in its socket object.
Thereafter, any data sent using that socket is sent to that port and
that ip address.





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


Re: network programming: how does s.accept() work?

2008-02-25 Thread 7stud
On Feb 25, 2:43 am, [EMAIL PROTECTED] wrote:
>
> by reusing the same variables without storing the previous values.
> This could make the Python
> garbage collector to attempt freeing the socket object created with
> the first connection, therefore
> closing the connection.
>
> If I'm right, your program should work as you expect if you for
> instance collect in a list the sockets
> returned by accept.
>

Yes, you are right about that.  This code prevents the first client
from disconnecting:

newsocks = []
client_addys = []

while 1:
newsock, client_addr = s.accept()
newsocks.append(newsock)
client_addys.append(client_addr)

print "original socket:", s.getsockname()

print "new socket, self:", newsock.getsockname()
print "new socket, peer:", newsock.getpeername()
print
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: network programming: how does s.accept() work?

2008-02-25 Thread 7stud
On Feb 25, 2:43 am, [EMAIL PROTECTED] wrote:
> On 25 Feb, 09:51, 7stud <[EMAIL PROTECTED]> wrote:
>
>
>
> > I have the following two identical clients
>
> > #test1.py:---
> > import socket
>
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> > host = 'localhost'
> > port = 5052  #server port
>
> > s.connect((host, port))
> > print s.getsockname()
>
> > response = []
> > while 1:
> >     piece = s.recv(1024)
> >     if piece == '':
> >         break
>
> >     response.append(piece)
>
> > #test3.py:
> > import socket
>
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> > host = 'localhost'
> > port = 5052  #server port
>
> > s.connect((host, port))
> > print s.getsockname()
>
> > response = []
> > while 1:
> >     piece = s.recv(1024)
> >     if piece == '':
> >         break
>
> >     response.append(piece)
>
> > and this basic server:
>
> > #test2.py:--
> > import socket
>
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> > host = ''
> > port = 5052
>
> > s.bind((host, port))
> > s.listen(5)
>
> > while 1:
> >     newsock, client_addr = s.accept()
> >     print "orignal socket:", s.getsockname()
>
> >     print "new socket:", newsock.getsockname()
> >     print "new socket:", newsock.getpeername()
> >     print
>
> > I started the server, and then I started the clients one by one.  I
> > expected both clients to hang since they don't get notified that the
> > server is done sending data, and I expected the server output to show
> > that accept() created two new sockets.  But this is the output I got
> > from the server:
>
> > original socket: ('0.0.0.0', 5052)
> > new socket, self: ('127.0.0.1', 5052)
> > new socket, peer: ('127.0.0.1', 50816)
>
> > original socket: ('0.0.0.0', 5052)
> > new socket, self: ('127.0.0.1', 5052)
> > new socket, peer: ('127.0.0.1', 50818)
>
> > The first client I started generated this output:
>
> > ('127.0.0.1', 50816)
>
> > And when I ran the second client, the first client disconnected, and
> > the second client produced this output:
>
> > ('127.0.0.1', 50818)
>
> > and then the second client hung.  I expected the server output to be
> > something like this:
>
> > original socket: ('127.0.0.1', 5052)
> > new socket, self: ('127.0.0.1', 5053)
> > new socket, peer: ('127.0.0.1', 50816)
>
> > original socket: ('0.0.0.0', 5052)
> > new socket, self: ('127.0.0.1', 5054)
> > new socket, peer: ('127.0.0.1', 50818)
>
> > And I expected both clients to hang.  Can someone explain how accept()
> > works?
>
> I guess (but I did not try it) that the problem is not accept(), that
> should work as you expect,
> but the fact that at the second connection your code actually throws
> away the first connection
> by reusing the same variables without storing the previous values.
> This could make the Python
> garbage collector to attempt freeing the socket object created with
> the first connection, therefore
> closing the connection.
>
> If I'm right, your program should work as you expect if you for
> instance collect in a list the sockets
> returned by accept.
>
> Ciao
> 
> FB

The question I'm really trying to answer is: if a client connects to a
host at a specific port, but the server changes the port when it
creates a new socket with accept(), how does data sent by the client
arrive at the correct port?  Won't the client be sending data to the
original port e.g. port 5052 in the client code above?
-- 
http://mail.python.org/mailman/listinfo/python-list


network programming: how does s.accept() work?

2008-02-25 Thread 7stud
I have the following two identical clients

#test1.py:---
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = 'localhost'
port = 5052  #server port

s.connect((host, port))
print s.getsockname()

response = []
while 1:
piece = s.recv(1024)
if piece == '':
break

response.append(piece)


#test3.py:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = 'localhost'
port = 5052  #server port

s.connect((host, port))
print s.getsockname()

response = []
while 1:
piece = s.recv(1024)
if piece == '':
break

response.append(piece)


and this basic server:

#test2.py:--
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ''
port = 5052

s.bind((host, port))
s.listen(5)


while 1:
newsock, client_addr = s.accept()
print "orignal socket:", s.getsockname()

print "new socket:", newsock.getsockname()
print "new socket:", newsock.getpeername()
print


I started the server, and then I started the clients one by one.  I
expected both clients to hang since they don't get notified that the
server is done sending data, and I expected the server output to show
that accept() created two new sockets.  But this is the output I got
from the server:

original socket: ('0.0.0.0', 5052)
new socket, self: ('127.0.0.1', 5052)
new socket, peer: ('127.0.0.1', 50816)

original socket: ('0.0.0.0', 5052)
new socket, self: ('127.0.0.1', 5052)
new socket, peer: ('127.0.0.1', 50818)

The first client I started generated this output:

('127.0.0.1', 50816)

And when I ran the second client, the first client disconnected, and
the second client produced this output:

('127.0.0.1', 50818)

and then the second client hung.  I expected the server output to be
something like this:

original socket: ('127.0.0.1', 5052)
new socket, self: ('127.0.0.1', 5053)
new socket, peer: ('127.0.0.1', 50816)

original socket: ('0.0.0.0', 5052)
new socket, self: ('127.0.0.1', 5054)
new socket, peer: ('127.0.0.1', 50818)

And I expected both clients to hang.  Can someone explain how accept()
works?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create multiple directories

2008-02-24 Thread 7stud
On Feb 24, 6:27 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Paul Lemelle wrote:
> > I am somewhat new to Python and I am trying to create a program that
> > automatically creates directories from a range of numbers. I
> > researched the os.mkdir & os.makedirs methods, but they do not seem to
> > (I don't know) how to include an argumnet to step through my list.
>
> > I woudl like to do the follwoing:
> > 1) Ask the user how many folders to create
> > 2) take raw_input and then translate it into a while loop that steps
> > through the os.mkdir process.
>
> Maybe something like this?
>
> import os
>
> def mkdirs(n):
>      for i in range(n):
>          os.mkdir("%d" % i)
>
> if __name__ == '__main__':
>      mkdirs(int(raw_input("How many folders should I create? ")))

Maybe something like this:

import os

num_str = raw_input("Enter number of dirs to create: ")
num = int(num_str)

for i in range(num):
dir_name = "new_dir%s" % i  #same result as "new_dir" + str(i)
os.mkdir(dir_name)  #creates dirs in current directory
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b with urllib2: How to make it handle cookie automatically?

2008-02-24 Thread 7stud
On Feb 24, 4:41 am, est <[EMAIL PROTECTED]> wrote:
> On Feb 23, 2:42 am, Rob Wolfe <[EMAIL PROTECTED]> wrote:
>
>
>
> > est <[EMAIL PROTECTED]> writes:
> > > Hi all,
>
> > > I need urllib2 do perform series of HTTP requests with cookie from
> > > PREVIOUS request(like our browsers usually do ). Many people suggest I
> > > use some library(e.g. pycURL) instead but I guess it's good practise
> > > for a python beginner to DIY something rather than use existing tools.
>
> > > So my problem is how to expand the urllib2 class
>
> > > from cookielib import CookieJar
> > > class SmartRequest():
> > >     cj=CookieJar()
> > >     def __init__(self, strUrl, strContent=None):
> > >         self.Request    =   urllib2.Request(strUrl, strContent)
> > >         self.cj.add_cookie_header(self.Request)
> > >         self.Response   =   urllib2.urlopen(Request)
> > >         self.cj.extract_cookies(self.Response, self.Request)
> > >     def url
> > >     def read(self, intCount):
> > >         return self.Response.read(intCount)
> > >     def headers(self, strHeaderName):
> > >         return self.Response.headers[strHeaderName]
>
> > > The code does not work because each time SmartRequest is initiated,
> > > object 'cj' is cleared. How to avoid that?
> > > The only stupid solution I figured out is use a global CookieJar
> > > object. Is there anyway that could handle all this INSIDE the class?
>
> > > I am totally new to OOP & python programming, so could anyone give me
> > > some suggestions? Thanks in advance
>
> > Google for urllib2.HTTPCookieProcessor.
>
> > HTH,
> > Rob- Hide quoted text -
>
> > - Show quoted text -
>
> Wow, thank you Rob Wolfe! Your reply is shortest yet most helpful! I
> solved this problem by the following code.
>
> class HTTPRefererProcessor(urllib2.BaseHandler):
>     """Add Referer header to requests.
>
>     This only makes sense if you use each RefererProcessor for a
> single
>     chain of requests only (so, for example, if you use a single
>     HTTPRefererProcessor to fetch a series of URLs extracted from a
> single
>     page, this will break).
>
>     There's a proper implementation of this in module mechanize.
>
>     """
>     def __init__(self):
>         self.referer = None
>
>     def http_request(self, request):
>         if ((self.referer is not None) and
>             not request.has_header("Referer")):
>             request.add_unredirected_header("Referer", self.referer)
>         return request
>
>     def http_response(self, request, response):
>         self.referer = response.geturl()
>         return response
>
>     https_request = http_request
>     https_response = http_response
>
> def main():
>     cj = CookieJar()
>     opener = urllib2.build_opener(
>         urllib2.HTTPCookieProcessor(cj),
>         HTTPRefererProcessor(),
>     )
>     urllib2.install_opener(opener)
>
>     urllib2.urlopen(url1)
>     urllib2.urlopen(url2)
>
> if "__main__" == __name__:
>     main()
>
> And it's working great!
>
> Once again, thanks everyone!

How does the class HTTPReferrerProcessor do anything useful for you?
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   >