problems with shelve(), collections.defaultdict, self
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: problems with shelve(), collections.defaultdict, self
On Feb 10, 7:48 pm, 7stud <[email protected]> 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
Re: problems with shelve(), collections.defaultdict, self
On Feb 10, 7:52 pm, 7stud <[email protected]> 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
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
interesting take on python OO
http://www.evolt.org/article/OO_programming_the_Python_way/18/449/ - The last article gives you the absolute basics of using Python. This time, we'll do the OO side of Python. Yes, Python: a true object- oriented language with classes, inheritance and all. Ok, my OO background comes from the usual suspects of OO language, C+ +, Java and Object Pascal (Delphi). So I have this preconceived idea about what Python OO should be. When I discover how OO is implemented in Python, my first reaction was: "What the is this s#~! ?" My idealism about OO is offended by what Python does with object and classes. It offers a new perspective on what can be done with classes and object. Over time Python has grown on me, and now I can really appreciate what it can do. So if you have the same reaction as mine, keep reading. It will grow on you as well. lol -- http://mail.python.org/mailman/listinfo/python-list
Re: implementing callback function
Ron Provost wrote: > class X( object ): >fn = None >@staticmethod >def callX( n ): > return X.fn( n ) > Now, the following global stuff represents my higher-level routines: > def fn_impl( n ): # my callback >return n + 1 > X.fn = fn_impl # register my callback > Now I can do something which forces my callback (fn_impl) to get called > print X.callX( 3 ) > I think I would get '4' printed but instead get the above error. What > am I doing wrong? callX is a static method, so it does not require an instance as the first argument. However, that's not true for fn_impl. This line of code: > X.fn = fn_impl makes fn_impl an attribute of the class. If you call a function that is a class attribute, python creates a method out of the function. A method requires that the first argument be an instance. If you call the method through an instance, python automatically sends the instance as the first argument to the method. If you call the method using the class, then you have to supply the instance argument yourself. In this line: return X.fn( n ) You are calling a function that is a class attribute and you are calling it through the class, so you have to supply an instance as the first argument yourself. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to control the creation of an instance?
On Jun 2, 10:31 pm, lialie <[EMAIL PROTECTED]> wrote: > Hi, > > suppose i have a free_object list[Sample1, Smaple2]. when create a > new object sample(*args, **kwds), if free_object_list isn't empty, just > pop one from free_object_list instead of creating a new instance. > > any way to do this? > > I do some work as follows: > > class Sample(object): > used_object = [] > free_object = [] > > def __init__(self, *args, **kwds): > pass > > def __new__(self, *args, **kwds): > if Sample.free_object: > obj = Sample.free_object.pop(0) > else: > obj = object.__new__(Sample, *args, **kwds) > Sample.used_object.append(obj) > return obj > > still get a new instance :( > > def Release(self): > Sample.used_object.remove(self) > Sample.free_object.append(self) > return True Try something like this: class A(object): pass def getObj(alist): if alist: return alist.pop() else: return A() x = [A(), A()] print x newlist = [] for i in range(0,3): newlist.append(getObj(x) ) print newlist --output:-- [<__main__.A object at 0x55bf0>, <__main__.A object at 0x55b50>] [<__main__.A object at 0x55b50>, <__main__.A object at 0x55bf0>, <__main__.A object at 0x55d30>] Examine the addresses, i.e. the set of numbers in each <> -- http://mail.python.org/mailman/listinfo/python-list
Re: How to control the creation of an instance?
I just noticed that in your code you used pop(0). It's not efficient to pop an element off the front of a list because after doing so, every other element in the list has to be moved over to the left one position. If you pop() an element off the end of the list, then the first element in the list remains the first element, and the 2nd element remains the 2nd element, etc., so no shifting of the remaining elements is required. If you need to pop elements of the front of a list, then it's more efficient to use a deque, which can be found in the collections module. Here is an example: import collections class A(object): pass def getObj(a_deque): if a_deque: return a_deque.popleft() else: return A() x = collections.deque([A(), A()]) print x newlist = [] for i in range(0,3): newlist.append(getObj(x) ) print newlist --output:-- deque([<__main__.A object at 0x55d90>, <__main__.A object at 0x55db0>]) [<__main__.A object at 0x55d90>, <__main__.A object at 0x55db0>, <__main__.A object at 0x55e30>] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to control the creation of an instance?
On Jun 2, 10:31 pm, lialie <[EMAIL PROTECTED]> wrote:
> Hi,
>
> suppose i have a free_object list[Sample1, Smaple2]. when create a
> new object sample(*args, **kwds), if free_object_list isn't empty, just
> pop one from free_object_list instead of creating a new instance.
>
> any way to do this?
>
> I do some work as follows:
>
> class Sample(object):
> used_object = []
> free_object = []
>
> def __init__(self, *args, **kwds):
> pass
>
> def __new__(self, *args, **kwds):
> if Sample.free_object:
> obj = Sample.free_object.pop(0)
> else:
> obj = object.__new__(Sample, *args, **kwds)
> Sample.used_object.append(obj)
> return obj
>
> still get a new instance :(
>
> def Release(self):
> Sample.used_object.remove(self)
> Sample.free_object.append(self)
> return True
This seems to work for me:
import collections
class Sample(object):
free_objects = collections.deque()
used_objects = []
def __new__(cls, *args, **kwds):
if not Sample.free_objects:
temp = object.__new__(Sample, args, kwds)
Sample.used_objects.append(temp)
return temp
else:
return Sample.free_objects.popleft()
def __init__(self, *args, **kwds):
self.args = args
self.kwds = kwds
def release(self):
Sample.used_objects.remove(self)
Sample.free_objects.append(self)
s1 = Sample(10, name="Bob")
print s1
print s1.args
print s1.kwds
s2 = Sample("red", name="Bill")
print s2
print s2.args
print s2.kwds
s1.release()
s3 = Sample("blue", name="Tim")
print s3
print s3.args
print s3.kwds
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to control the creation of an instance?
On Jun 3, 12:17 am, 7stud <[EMAIL PROTECTED]> wrote:
> On Jun 2, 10:31 pm, lialie <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > suppose i have a free_object list[Sample1, Smaple2]. when create a
> > new object sample(*args, **kwds), if free_object_list isn't empty, just
> > pop one from free_object_list instead of creating a new instance.
>
> > any way to do this?
>
> > I do some work as follows:
>
> > class Sample(object):
> > used_object = []
> > free_object = []
>
> > def __init__(self, *args, **kwds):
> > pass
>
> > def __new__(self, *args, **kwds):
> > if Sample.free_object:
> > obj = Sample.free_object.pop(0)
> > else:
> > obj = object.__new__(Sample, *args, **kwds)
> > Sample.used_object.append(obj)
> > return obj
>
> > still get a new instance :(
>
> > def Release(self):
> > Sample.used_object.remove(self)
> > Sample.free_object.append(self)
> > return True
>
> This seems to work for me:
>
> import collections
>
> class Sample(object):
>
> free_objects = collections.deque()
> used_objects = []
>
> def __new__(cls, *args, **kwds):
> if not Sample.free_objects:
> temp = object.__new__(Sample, args, kwds)
> Sample.used_objects.append(temp)
> return temp
> else:
> return Sample.free_objects.popleft()
>
> def __init__(self, *args, **kwds):
> self.args = args
> self.kwds = kwds
>
> def release(self):
> Sample.used_objects.remove(self)
> Sample.free_objects.append(self)
>
> s1 = Sample(10, name="Bob")
> print s1
> print s1.args
> print s1.kwds
>
> s2 = Sample("red", name="Bill")
> print s2
> print s2.args
> print s2.kwds
>
> s1.release()
> s3 = Sample("blue", name="Tim")
> print s3
> print s3.args
> print s3.kwds
Oops. This line:
> temp = object.__new__(Sample, args, kwds)
should be:
temp = object.__new__(cls, args, kwds)
although it would seem that cls is always going to be Sample, so I'm
not sure what practical difference that makes.
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to control the creation of an instance?
On Jun 3, 12:50 am, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sat, 02 Jun 2007 23:25:49 -0700, 7stud wrote: > > Oops. This line: > > >> temp = object.__new__(Sample, args, kwds) > > > should be: > > > temp = object.__new__(cls, args, kwds) > > > although it would seem that cls is always going to be Sample, so I'm > > not sure what practical difference that makes. > > What if you are calling it from a sub-class? > > -- > Steven. cls it is! -- http://mail.python.org/mailman/listinfo/python-list
Re: Select one of 2 functions with the same name ?
On Jun 10, 10:37 am, Stef Mientki <[EMAIL PROTECTED]> wrote: > hello, > > For a simulation at different levels, > I need different functions with the same name. > Is that possible ? > > I can realize it with a simple switch within each function, > but that makes the code much less readable: > > def Some_Function(): >if simulation_level == 1: > ... do things in a way >elif simulation_level == 2: > ... do things in another way >elif simulation_level == 3: > ... do things in yet another way > > thanks, > Stef Mientki Try something like this: class Simulation1(object): def greet(self): print "hello" class Simulation2(object): def greet(self): print "hello" class Simulation3(object): def greet(self): print "hello" def someFunc(simObj): simObj.greet() s1 = Simulation1() s2 = Simulation2() s3 = Simulation3() someFunc(s1) someFunc(s2) someFunc(s3) -- http://mail.python.org/mailman/listinfo/python-list
Re: Select one of 2 functions with the same name ?
On Jun 10, 11:11 am, 7stud <[EMAIL PROTECTED]> wrote: > On Jun 10, 10:37 am, Stef Mientki <[EMAIL PROTECTED]> > wrote: > > > > > hello, > > > For a simulation at different levels, > > I need different functions with the same name. > > Is that possible ? > > > I can realize it with a simple switch within each function, > > but that makes the code much less readable: > > > def Some_Function(): > >if simulation_level == 1: > > ... do things in a way > >elif simulation_level == 2: > > ... do things in another way > >elif simulation_level == 3: > > ... do things in yet another way > > > thanks, > > Stef Mientki > > Try something like this: > > class Simulation1(object): > def greet(self): > print "hello" > > class Simulation2(object): > def greet(self): > print "hello" > > class Simulation3(object): > def greet(self): > print "hello" > > def someFunc(simObj): > simObj.greet() > > s1 = Simulation1() > s2 = Simulation2() > s3 = Simulation3() > > someFunc(s1) > someFunc(s2) > someFunc(s3) Horrible example. Look at this instead: class Simulation1(object): def greet(self): print "hello from sim1" class Simulation2(object): def greet(self): print "Hi. I'm sim2" class Simulation3(object): def greet(self): print "sim3 is #1! Hello there." def someFunc(simObj): simObj.greet() s1 = Simulation1() s2 = Simulation2() s3 = Simulation3() someFunc(s1) someFunc(s2) someFunc(s3) ---output:--- hello from sim1 Hi. I'm sim2 sim3 is #1! Hello there. As the output shows, you can call the same function, but the function can do different things. -- http://mail.python.org/mailman/listinfo/python-list
Re: Select one of 2 functions with the same name ?
On Jun 10, 2:03 pm, Stef Mientki <[EMAIL PROTECTED]> wrote: > thanks Francesco and "7stud", > > The solution with objects is too difficult, > because I want to stay very close to the orginal language, > Why would you want to duplicate poorly written code? -- http://mail.python.org/mailman/listinfo/python-list
Re: Dive into Python 5.5
On Jun 13, 2:40 am, james_027 <[EMAIL PROTECTED]> wrote:
> Hi,
>
> class UserDict:
> def __init__(self, dict=None):
> self.data = {}
> if dict is not None: self.update(dict)
>
> I just don't understant this code, as it is not also mention in the
> book. the update is a method of a dict right? in my understanding the
> last statement should be self.data.update(dict).
>
> someone please explain to me what happen where?
>
> Thanks
> james
This is what "Dive" says:
---
To explore this further, let's look at the UserDict
class in the UserDict module...In particular, it's stored in the lib
directory in your Python installation.
---
So you can actually locate the file UserDict.py on your computer and
look at the code. If you don't want to do that, then the following is
an explanation of what's going on with that code.
Suppose you have a class like this:
class Dog(object):
def __init__(self):
self.update()
When __init__ executes, the only line in __init__ says go look in self
for the method update() and execute it. That means the Dog class
probably has at least one additional method:
class Dog(object):
def __init__(self):
self.update()
def update(self):
print "hello"
So if you wrote:
d = Dog()
the output would be:
hello
Ok, now suppose you add a line to __init__:
class Dog(object):
def __init__(self):
self.data = {}
self.update()
def update(self):
print "hello"
Does the new line in __init__ affect the line self.update() in any
way? Is there necessarily any connection between self.data and
update()? No.
However, if you look at the actual code for UserDict, you can see that
inside the method update(), items are added to self.data, so there is
a connection.
Then the question is: why didn't the person who wrote the class just
do the following in __init__:
self.data.update(dict)
Well, as it turns out, adding items to self.data is not that straight
forward. self.data is a dict type and dict types have an update()
method that requires another dict as an argument. But the 'dict'
parameter variable in __init__ could be sent a dict type or it could
be sent another instance of UserDict. So, the code to add items to
self.data got complicated enough that the writer of the class decided
to move the code into its own method. Note that just because the
parameter variable is named 'dict' does not mean the argument sent to
the function is a dict type. For instance, you could write this:
dict = "hello world"
As you can see, the variable named 'dict' does not refer to a dict
type. Using a python type as a variable name is a horrible and
confusing thing to do, so don't do it in your code.
In addition, the writer of the class wanted to provide an update()
method for the UserDict class, which could be called at any time, so
instead of having to write the same code in two places: once in
__init__ to initialize an instance with a given dict and a second time
inside the update() method, the programmer wrote the code once in its
own method and then called the method from __init__.
--
http://mail.python.org/mailman/listinfo/python-list
Re: OS X install confusion
On Jun 14, 11:21 am, [EMAIL PROTECTED] (John Fisher) wrote: > Hi Groupies, > > I have an Intel Macbook running OS X 10.4. > > It came installed with Python 2.3.5. I have since installed MacPython > with version 2.4.4, cool. > > When I open a bash terminal session and type python, it brings up > version 2.3.5. If I type IDLE it brings up version 2.4.4. > > My question: what do I have to do to get it to bring up 2.4.4 with the > "python" command? > > Thanks for bringing light to my ignorance. > > JF Strange. I installed macpython 2.4.4 on an imac this year, and when I type python on the command line of a bash shell, python 2.4.4 starts up: $ python Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> I looked in: /System/Library/Frameworks/Python.framework/Versions/Current/bin/ and inside that directory are the programs: idle pydoc python python2.3 So I tried typing python2.3 on the command line, and lo and behold python 2.3.5 started up: $ python2.3 Python 2.3.5 (#1, Jul 25 2006, 00:38:48) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> So it looks like the macpython install changed the name of the pre- installed python program from python to python2.3. What do you see in that directory? -- http://mail.python.org/mailman/listinfo/python-list
Re: OS X install confusion
On Jun 14, 6:25 pm, Paul McNett <[EMAIL PROTECTED]> wrote:
> John Fisher wrote:
> > Ted <[EMAIL PROTECTED]> wrote:
>
> >> On Jun 14, 1:31 pm, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> >>> John Fisher wrote:
> Hi Groupies,
> I have an Intel Macbook running OS X 10.4.
> It came installed with Python 2.3.5. I have since installed MacPython
> with version 2.4.4, cool.
> When I open a bash terminal session and type python, it brings up
> version 2.3.5. If I type IDLE it brings up version 2.4.4.
> My question: what do I have to do to get it to bring up 2.4.4 with the
> "python" command?
> Thanks for bringing light to my ignorance.
> JF
> >>> Sounds like a path problem. Apple's system Python is installed in
> >>> /usr/bin. Your installation is probably in /usr/local/bin. Edit your
> >>> profile or use the full path.
>
> >>> --
> >>> Kevin Walzer
> >>> Code by Kevinhttp://www.codebykevin.com
> >> The default python on tiger (2.3.5) is sym-linked to /usr/bin/python
> >> and /usr/bin/pythonw.
>
> >> I found it easier to relink to the new installation path. This also
> >> leaves /usr/bin/python23 and /usr/bin/pythonw23 still linked to the
> >> original version if you want to quickly check something.
>
> >> Cheers,
> >> Ted
>
> > OK, please give a little more information how I can accomplish this
> > "re-link".
>
> Your Python 2.5 is likely installed here:
>
> /Library/Frameworks/Python.framework/Versions/Current/bin
>
> But OS X comes with a "system Python", version 2.3.5, likely installed here:
>
> /usr/bin
>
> If you look at /usr/bin, you'll see:
>
> lrwxr-xr-x 1 root wheel 9 Jan 31 17:24 python -> python2.3
> lrwxr-xr-x 1 root wheel 72 Jan 31 17:24 python2.3 ->
> ../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python
> lrwxr-xr-x 1 root wheel 10 Jan 31 17:24 pythonw -> pythonw2.3
> -rwxr-xr-x 1 root wheel 29704 Aug 19 2006 pythonw2.3
>
> So, python is linked to python2.3, and python2.3 is in turn linked to
> /System/Library/Frameworks/Python.framework/Versions/2.3/bin/python
>
> You need to (warning: watch for line wrap):
>
> sudo -s
>
> cd /usr/bin
> ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/python
> python_current
> ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/pythonw
> pythonw_current
> rm python
> rm pythonw
> ln -s python python_current
> ln -s pythonw pythonw_current
>
> However, that isn't what I did. I like the system being able to find and
> use the system-installed python, but I like my scripts to use the python
> version I installed (2.5). To get that, skip the above symlinking and
> instead edit your .bash_profile file (hidden file inside your home
> directory) and put these lines at the top:
>
> PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH}
> export PATH
>
> --
> pkm ~http://paulmcnett.com
When I installed macpython 2.4.4, I think the install automatically
changed the file: Users/me/.bash_profile. Here is what is says at the
bottom of .bash_profile:
# Setting PATH for MacPython 2.5 (these lines added by install)
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:$
{PATH}"
export PATH
(Note I installed macpython 2.4.4 but the comment says something about
python 2.5.)
Ahh, I think I know what happened to the op's install. I don't think
imacs come with the file: Users/me/.bash_profile. I had previously
created the .bash_profile file in order to alter the bash prompt, so
when I installed macpython 2.4.4, the install modified the pre-
existing .bash_profile file and added the lines listed above. I bet
the op didn't have a .bash_profile file on his system, so the install
didn't make the path changes for him/her.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Want to learn Python
On Jun 15, 11:59 am, "Evan Klitzke" <[EMAIL PROTECTED]> wrote: > On 6/15/07, Amol <[EMAIL PROTECTED]> wrote: > > > Hi, I want to learn Python in less than a month which resources should > > I use. I prefer to read books . Please give me a list of *recognized* > > resources. Thank You all > > The Apress "Beginning Python" book is the one that I recommend to > people who want to learn the language. I started off with the O'Reilly > book, and that book went too slow and didn't cover as many topic as > the Apress book. If you are an experienced programmer and use the > Apress book, you'll get a pretty good grasp of the language within a > week or so. > > -- > Evan Klitzke <[EMAIL PROTECTED]> I am of the opposite opinion: I recommend that people get any book but "Beginning Python: Novice to Professional". In my opinion, that book is horribly written, the examples are terrible, some subjects are only covered in passing so the info is too parse to be of any use, and there are no problems at the end of the chapters to work on. I think a beginner might be fooled into thinking Beginning Python is a good book because they won't know how many holes their knowledge of python is riddled with, and since there are no problems to work on, they may not even realize how little they learned. I think an experienced programmer would spot all the blunders in the book straight away. As a result, I often use "Learning Python" as a reference to fill in all the missing material in Beginning Python, and I wish I had purchased it initially. It also has problems to work on at the end of each section. One problem with Learning Python is that it needs a new edition to catch up with the changes that have occurred in the language, but it still seems like a much, much better book than Beginning Python. The reference book "Python in a Nutshell" is excellent, however its index is so bad I hesitate to recommend it. A reference book should have a thorough index--you shouldn't have to hunt through the chapters trying to find the particular topic you are interested in. -- http://mail.python.org/mailman/listinfo/python-list
Re: Want to learn Python
> I'm curious, have you tried _Python for Dummies_? No, I haven't. Unfortunately, I don't ever consider Dummies books. That type of marketing appeals to certain people and not others. I'm one of the others. I'll definitely take a look at it the next time I'm in the bookstore. >We didn't wait for Wiley to offer, we simply insisted on providing a >list of index terms. It's nice to hear about an author who cares enough about the end product that bears their name to insist on quality. I'm so tired of hearing authors whine that the publisher screwed up the book. -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 bug??
On Jun 17, 7:16 am, mark carter <[EMAIL PROTECTED]> wrote: > David Wahler wrote: > > On 6/17/07, mark carter <[EMAIL PROTECTED]> wrote: > >> Anyone else getting these problems? > > > Seehttp://www.python.org/dev/peps/pep-0249/(emphasis mine): > > >.commit() > > OK, I tried that, and I appear to be cooking. The funny thing is, I > could have sworn that I tried that a few days ago, and it didn't work. > Weird. Appears to be working now, though, so I guess I must have been > doing something kooky. > > Should I also explicitly close the cursor and connection, or is that > taken care of "automagically"? > > I'm seriously thinking about reporting the commit() thing as a doc bug > in python, as this isn't mentioned > athttp://docs.python.org/lib/module-sqlite3.html > and I think it's exactly the kind of thing that should be mentioned in > the examples. Please report the whole docs as a bug. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the size of an object
On Jun 18, 10:07 am, "filox" <[EMAIL PROTECTED]> wrote: > is there a way to find out the size of an object in Python? e.g., how could > i get the size of a list or a tuple? > > -- > You're never too young to have a Vietnam flashback You can use the struct module to find the size in bytes: import struct mylist = [10, 3.7, "hello"] int_count = 0 float_count = 0 char_count = 0 for elmt in mylist: if type(elmt) == int: int_count += 1 elif type(elmt) == float: float_count += 1 elif type(elmt) == str: char_count += len(elmt) format_string = "%di%dd%dc" % (int_count, float_count, char_count) list_size_in_bytes = struct.calcsize(format_string) print list_size_in_bytes --output:-- 17 -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding method to a class on the fly
On Jun 22, 2:24 pm, askel <[EMAIL PROTECTED]> wrote:
> class Dummy:
> def method(self, arg):
> print arg
>
> def method2(self, arg):
> self.method(arg)
>
> Dummy.method2 = method2
> Dummy.method2('Hello, world!')
Traceback (most recent call last):
File "test1.py", line 8, in ?
Dummy.method2('Hello, world!')
TypeError: unbound method method2() must be called with Dummy instance
as first argument (got str instance
instead)
>I like that to be the same as:
>
>class Dummy:
>def __init__(self):
>return
>
>def method_dynamic(self):
>return self.method_static("it's me")
>
>def method_static(self, text):
>print text
> return
>
>
>so that I can do:
>
>dum=Dummy.method_dynamic()
>
>and see "it's me" printed.
When are you able to see that?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Adding method to a class on the fly
On Jun 22, 3:23 pm, askel <[EMAIL PROTECTED]> wrote:
> sorry, of course last line should be:
> Dummy().method2('Hello, world!')
..which doesn't meet the op's requirements.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Collections of non-arbitrary objects ?
On Jun 23, 11:45 am, walterbyrd <[EMAIL PROTECTED]> wrote: > On Jun 22, 11:43 pm, Ben Finney <[EMAIL PROTECTED]> > wrote: > > > Can you help us understand, by showing a use case that would in your > > estimation be improved by the feature you're describing? > > Suppose you are sequentially processing a list with a routine that > expects every item to be of a certain type. Something in the list that > doesn't conform to the type could give you unexpected results, maybe > crash your application. > if hasattr(elmt, some_func): elmt.some_func() -- http://mail.python.org/mailman/listinfo/python-list
Re: pydoc with METH_VARGS
On Jun 23, 2:13 pm, Stuart <[EMAIL PROTECTED]> wrote: > With my Python extension module all the function definitions are with > METH_VARGS. The result being that pydoc, just puts "(...)" for the > argument list. Can I hand edit this to put the specific variable names > I want? With optional arguments in brackets or something? > > Thanks. Are you asking whether you can change a text file that pydoc produces? -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing variable from a function within a function
On Jun 24, 11:55 am, "Nathan Harmston" <[EMAIL PROTECTED]> wrote: > Hi, > > I m playing around with extended euclids algorithm from Knuth. I m > trying to build a function with a function inside it. > > def exteuclid(m,n): > a,a1,b,b1,c,d = 0,1,1,0,m,n > def euclid(c,d): > q = c /d > r = c % d > if r == 0: > print a,b > return d > else: > print a1,a,b1,b,c,d,q,r > t = b1 > b = t - q * b > a = t - q * a > c,d,a1,b1 = d,r,a,b > return euclid(c,d) > return euclid(c,d) > > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? > > Many Thanks in advance, > > Nathan ef outer(): a = 10 def inner(): print a return inner f = outer() f() --output:-- 10 -- http://mail.python.org/mailman/listinfo/python-list
can't start Apache on Mac OS X--no listening sockets available?
I'm trying to get Apache set up on my system so I can use mod_python. I installed Apache 2.2.4 according to the following instructions: http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-os-x/#comment-30704 and everything seemed to install correctly, but I can't start Apache. I typed in the following command: $ sudo /Library/Apache2/bin/apachectl start Password: and I got this error message: httpd: Could not reliably determine the server's fully qualified domain name, using tms-computer.local for ServerName (48)Address already in use: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: can't start Apache on Mac OS X--no listening sockets available?
> On Jun 25, 7:23 pm, 7stud <[EMAIL PROTECTED]> wrote: > > > > > I'm trying to get Apache set up on my system so I can use mod_python. > > I installed Apache 2.2.4 according to the following instructions: > > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > > and everything seemed to install correctly, but I can't start Apache. > > I typed in the following command: > > > $ sudo /Library/Apache2/bin/apachectl start > > Password: > > > and I got this error message: > > > httpd: Could not reliably determine the server's fully qualified > > domain name, using tms-computer.local for ServerName > > (48)Address already in use: make_sock: could not bind to address > > 0.0.0.0:80 > > no listening sockets available, shutting down > > Unable to open logs > > > Any ideas? > > Do you have "Web Sharing" in the prefs on as well? I checked and to my surprise Personal Web Sharing was turned on. I was messing around with it yesterday because I thought that might have something to do with my problems, but I couldn't get Personal Web Sharing to start--it just said "Web Sharing starting up...", and it never did. Anyway, I turned Personal Web Sharing off, and then the error message changed to this: $ sudo /Library/Apache2/bin/apachectl start Password: httpd: Could not reliably determine the server's fully qualified domain name, using tms-computer.local for ServerName However, I checked the All Processes page in the Activity Monitor, and it said httpd was running. So I tested my apache installation by typing http:/localhost in Safari's address bar, and a page displayed saying "It works!". But I wondered if that page was being served up by the pre-installed version of Apache or my new installation. So, I went into my new installation's directory and looked at the file: /Library/Apache2/htdocs/index.html and changed the text from "It works!" to "Apache 2.2.4", but when I retyped http:/localhost in Safari's address bar, I still got a page saying "It works!", so that page is not being served by my new installation. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't start Apache on Mac OS X--no listening sockets available?
Ok. If I try to start Personal Web Sharing while Apache is running, it says "Web Sharing starting up...", but it never does. Then if I close the window and restart my imac, my imac boots up with Personal Web Sharing turned on. I still can't figure out where the page that says "It works!" is located. It must be in the pre installed apache directory, but I have no idea where it is on my imac. And, I don't understand why the page isn't being served up by my new installation since I started the new Apache using the command: $sudo /Library/Apache2/bin/apachectl start I didn't start the pre-installed Apache. Also, when I look at the Activity monitor, there is an httpd root process with pid 285, and then there are 6 daemon http processes with pids 286, 287, 288, 289, 290, 291. What is that all about? -- http://mail.python.org/mailman/listinfo/python-list
Re: can't start Apache on Mac OS X--no listening sockets available?
On Jun 26, 12:52 am, kaens <[EMAIL PROTECTED]> wrote: > If apache2 works on macs how it does on linux (it should, right?) > there should be Apache2/sites-enabled and Apache2/sites-available > directories - the "default" files in these will tell you what pages > are being served, I believe. > There are no such directories in my new installation directory / Library/Apache2 > Also, I think the processes are normal, but I'm not sure. Apache is a > pretty heavyweight server. Ok. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't start Apache on Mac OS X--no listening sockets available?
Well, I'm able to put html pages in /Library/Apache2/htdocs/ and access them in Safari as I would expect: http://localhost/test.htm and I can access the index.html page in that directory: http://localhost/index.html and it displays: It works! Apache 2.2.4 But, if I just use the address http://localhost/ in Safari, this is displayed: It works! Where is that coming from? Is the original index.html page(before I changed it and added "Apache 2.2.4") cached by Safari somehow? That doesn't make any sense to me because when I explicitly request index.html, I get the changed output. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't start Apache on Mac OS X--no listening sockets available?
On Jun 26, 1:34 am, 7stud <[EMAIL PROTECTED]> wrote: > Where is that coming from? Is the original index.html page(before I > changed it and added "Apache 2.2.4") cached by Safari somehow? That > doesn't make any sense to me because when I explicitly request > index.html, I get the changed output. I looked around in Safari for a bit, and I found Empty Cache under the Safari menu item. So I emptied the cache and now when I use the address http://localhost, I get the changed index.html page. So Safari was caching the original page. I guess Safari associate the address http://localhost with the original index.html page, and Safari would not display the updated index.html page when I used that address again. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't start Apache on Mac OS X--no listening sockets available?
> Console and the system logs are an invaluable debugging tool on Macs. > Bet you have some errors there saying why apache couldnt stop/start. > What/where is Console and how do I look at the system logs? -- http://mail.python.org/mailman/listinfo/python-list
subprocess.Popen() problem
I have this program:
mytest.py
--
myinput = raw_input("Enter input: ")
if myinput == "hello":
print "goodbye"
--
and I want to execute it using subprocess.Popen(). I tried the
following but it just hangs:
---
import subprocess
f = open("/Users/me/2testing/dir1/aaa.txt", "w")
my_path = "/Users/me/2testing/"
my_file = "mytest.py"
p = subprocess.Popen(["python", "mytest.py"], stdin=subprocess.PIPE,
stdout = f,
stderr = f,
cwd = my_path
)
f.close()
p.stdin.write("hello")
p.wait()
f.open("/Users/me/2testing/dir1/aaa.txt")
print f.read()
--
http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen() problem
On Jun 26, 3:00 pm, "Jerry Hill" <[EMAIL PROTECTED]> wrote:
> On 6/26/07, 7stud <[EMAIL PROTECTED]> wrote:
>
> > p.stdin.write("hello")
>
> You need to add the linefeed, otherwise your mytest.py process is
> still waiting for you to finish typing. So, use this instead:
>
> p.stdin.write("hello\n")
>
Arggh. Of course! Thanks
>Never tried this, but I think you need to use the communicate method
>detailed here:
Yes, communicate() will work too, but communicate reads stdout into a
string(i.e. into memory), and I don't want to do that. Thanks.
--
http://mail.python.org/mailman/listinfo/python-list
unicode
Based on this example and the error:
-
u_str = u"abc\u"
print u_str
UnicodeEncodeError: 'ascii' codec can't encode character u'\u' in
position 3: ordinal not in range(128)
--
it looks like when I try to display the string, the ascii decoder
parses each character in the string and fails when it can't convert a
numerical code that is higher than 127 to a character, i.e. the
character \u.
In the following example, I use encode() to convert a unicode string
to a regular string:
-
u_str = u"abc\u"
reg_str = u_str.encode("utf-8")
print repr(reg_str)
-
and the output is:
'abc\xe9\xa6\x99'
1) Why aren't the characters 'a', 'b', and 'c' in hex notation? It
looks like python must be using the ascii decoder to parse the
characters in the string again--with the result being python converts
only the 1 byte numerical codes to characters. 2) Why didn't that
cause an error like above for the 3 byte character?
Then if I try this:
---
u_str = u"abc\u"
reg_str = u_str.encode("utf-8")
print reg_str
---
I get the output:
abc
Here it looks like python isn't using the ascii decoder anymore. 2)
What determines which decoder python uses?
--
http://mail.python.org/mailman/listinfo/python-list
os.path.isfile()
Here is a program to print out the files in a directory:
---
import os
myfiles = os.listdir("../")
print myfiles
for afile in myfiles:
print afile
if os.path.isfile(afile):
print afile, "___file"
if os.path.isdir(afile):
print afile, "___dir"
print
Here is what's in the directory:
--
$ ls -al ../
total 2576
drwxr-xr-x8 nnn nnn 272 Jul 1 03:03 .
drwxr-xr-x 25 nnn nnn 850 Jul 1 01:34 ..
-rw-r--r--1 nnn nnn 6148 Jul 1 03:02 .DS_Store
-rw-r--r--1 nnn nnn 130 Jun 27 14:02 aaa.txt
drwxr-xr-x 55 nnn nnn 1870 Jul 1 03:09 dir1
-rwxrwxrwx1 nnn nnn 263 Jun 27 22:40 mytest.py
-rw-r--r--1 nnn nnn0 Mar 4 16:15 scratch.txt
-rw-r--r--1 nnn nnn 275 Apr 11 03:40 xmlFile.xml
Here is the output from my program:
--
$ python 1test.py
['.DS_Store', 'aaa.txt', 'dir1', 'mytest.py', 'scratch.txt',
'xmlFile.xml']
.DS_Store
.DS_Store ___file
aaa.txt
aaa.txt ___file
dir1
mytest.py
scratch.txt
xmlFile.xml
$
--
I expected the output:
---
DS_Store
.DS_Store ___file
aaa.txt
aaa.txt ___file
dir1
dir1 ___dir
mytest.py
mytest.py ___file
scratch.txt
scratch.txt ___file
xmlFile.xml
xmlFile.xml ___file
--
http://mail.python.org/mailman/listinfo/python-list
Re: os.path.isfile()
On Jul 1, 3:36 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> 7stud <[EMAIL PROTECTED]> wrote:
> > Here is a program to print out the files in a directory:
>
> > ---
> > import os
>
> > myfiles = os.listdir("../")
> > print myfiles
>
> > for afile in myfiles:
> > print afile
> > if os.path.isfile(afile):
> > print afile, "___file"
> > if os.path.isdir(afile):
> > print afile, "___dir"
> > print
> >
>
> > Here is what's in the directory:
>
> > --
> > $ ls -al ../
>
> > total 2576
> > drwxr-xr-x8 nnn nnn 272 Jul 1 03:03 .
> > drwxr-xr-x 25 nnn nnn 850 Jul 1 01:34 ..
> > -rw-r--r--1 nnn nnn 6148 Jul 1 03:02 .DS_Store
> > -rw-r--r--1 nnn nnn 130 Jun 27 14:02 aaa.txt
> > drwxr-xr-x 55 nnn nnn 1870 Jul 1 03:09 dir1
> > -rwxrwxrwx1 nnn nnn 263 Jun 27 22:40 mytest.py
> > -rw-r--r--1 nnn nnn0 Mar 4 16:15 scratch.txt
> > -rw-r--r--1 nnn nnn 275 Apr 11 03:40 xmlFile.xml
> >
>
> Yes, but what does 'ls -al .' show you? You didn't put any kind of path in
> your calls to isfile/isdir, so you are checking for the existence of
> files/directories called '.DS_Store' etc. in the *current* directory, not
> the one above. From your output I'd guess you have .DS_Store and aaa.txt
> files but the other names are not duplicated.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: unicode
Erik Max Francis wrote:
> 7stud wrote:
>
> > Based on this example and the error:
> >
> > -
> > u_str = u"abc\u"
> > print u_str
> >
> > UnicodeEncodeError: 'ascii' codec can't encode character u'\u' in
> > position 3: ordinal not in range(128)
> > --
> >
> > it looks like when I try to display the string, the ascii decoder
> > parses each character in the string and fails when it can't convert a
> > numerical code that is higher than 127 to a character, i.e. the
> > character \u.
>
> If you try to print a Unicode string, then Python will attempt to first
> encode it using the default encoding for that file. Here, it's apparent
> the default encoding is 'ascii', so it attempts to encode it into ASCII,
> which it can't do, hence the exception. The error is no different from
> this:
>
> >>> u_str = u'abc\u'
> >>> u_str.encode('ascii')
> Traceback (most recent call last):
>File "", line 1, in ?
> UnicodeEncodeError: 'ascii' codec can't encode character u'\u' in
> position 3: ordinal not in range(128)
>
> > In the following example, I use encode() to convert a unicode string
> > to a regular string:
> >
> > -
> > u_str = u"abc\u"
> > reg_str = u_str.encode("utf-8")
> > print repr(reg_str)
> > -
> >
> > and the output is:
> >
> > 'abc\xe9\xa6\x99'
> >
> > 1) Why aren't the characters 'a', 'b', and 'c' in hex notation? It
> > looks like python must be using the ascii decoder to parse the
> > characters in the string again--with the result being python converts
> > only the 1 byte numerical codes to characters. 2) Why didn't that
> > cause an error like above for the 3 byte character?
>
> Since you've already encoded the Unicode object as a normal string,
> Python isn't trying to do any implicit encoding. As for why 'abc'
> appears in plain text, that's just the way repr works:
>
> >>> s = 'a'
> >>> print repr(s)
> 'a'
> >>> t = '\x99'
> >>> print repr(t)
> '\x99'
>
> repr is attempting to show the string in the most readable fashion. If
> the character is printable, then it just shows it as itself. If it's
> unprintable, then it shows it in hex string escape notation.
>
> > Then if I try this:
> >
> > ---
> > u_str = u"abc\u"
> > reg_str = u_str.encode("utf-8")
> > print reg_str
> > ---
> >
> > I get the output:
> >
> > abc
> >
> > Here it looks like python isn't using the ascii decoder anymore. 2)
> > What determines which decoder python uses?
>
> Again, that's because by already encoding it as a string, Python isn't
> doing any implicit encoding. So it prints the raw string, which happens
> to be UTF-8, and which your terminal obviously supports, so you see the
> proper character.
>
> --
> Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
> San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
>Let us not seek the Republican answer or the Democratic answer but
> the right answer. -- John F. Kennedy
So let me see if I have this right:
Here is some code:
-
print "print unicode string:"
#print u"abc\u" #error
print repr(u'abc\u')
print
print "print regular string containing chars in unicode syntax:"
print 'abc\u'
print repr('abc\u')
print
print "print regular string containing chars in utf-8 syntax:"
#encode() converts unicode strings to regular strings
print u'abc\u'.encode("utf-8")
print repr(u'abc\u'.encode("utf-8") )
-
Here is the output:
---
print unicode string:
u'abc\u'
print regular string containing chars in unicode syntax:
abc\u
'abc\\u'
print regular string containing chars in utf-8 syntax:
abc
'abc\xe9\xa6\x99'
--
1) If you print a unicode string:
*print implicitly calls str()*
a) str() calls encode(), and encode() tries to convert the unicode
string to a regular string. encode() uses the default encoding, which
is ascii. If encode() can't convert a character, then encode() raises
an exception.
b) repr() calls encode(), but if encode() raises an exception for a
character, repr() catches the exception and skips over the character
leaving the character unchanged.
2) If you print a regular string containing characters in unicode
syntax:
a) str() calls encode(), but if encode() raises an exception for a
character, str() catches the exception and skips over the character
leaving the character unchanged. Same as 1b.
b) repr() similar to a), but repr() then escapes the escapes in the
string.
3) If you print a regular string containing characters in utf-8
syntax:
a) str() outputs the string to your terminal, and if your terminal can
convert the utf-8 numerical codes to characters it does so.
b) repr() blocks your terminal from interpreting the characters by
escaping the escapes in your string. Why don't I see two slashes like
in the output for 2b?
--
http://mail.python.org/mailman/listinfo/python-list
Re: unicode
Hi, Thanks for the detailed response. On Jul 1, 2:14 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > > 1) If you print a unicode string: > > > > a) str() calls encode(), and encode() tries to convert the unicode > > string to a regular string. encode() uses the default encoding, which > > is ascii. If encode() can't convert a character, then encode() raises > > an exception. > > Yes and no. This is what str() does, but str() isn't called. Instead, > print inspects sys.stdout.encoding, and uses that encoding to encode > the string. That, in turn, may raise an exception (in particular if > sys.stdout.encoding is "ascii" or not set). > Is that the same as print calling encode(u_str, sys.stdout.encoding) -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode
On Jul 1, 9:51 pm, 7stud <[EMAIL PROTECTED]> wrote: > Hi, > > Thanks for the detailed response. > > On Jul 1, 2:14 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > > > > 1) If you print a unicode string: > > > > a) str() calls encode(), and encode() tries to convert the unicode > > > string to a regular string. encode() uses the default encoding, which > > > is ascii. If encode() can't convert a character, then encode() raises > > > an exception. > > > Yes and no. This is what str() does, but str() isn't called. Instead, > > print inspects sys.stdout.encoding, and uses that encoding to encode > > the string. That, in turn, may raise an exception (in particular if > > sys.stdout.encoding is "ascii" or not set). > > Is that the same as print calling encode(u_str, sys.stdout.encoding) ooops. I mean is that the same as print calling u_str.encode(sys.stdout.encoding)? -- http://mail.python.org/mailman/listinfo/python-list
subprocess -- broken pipe error
Hi,
Can someone explain what a broken pipe is? The following produces a
broken pipe error:
--
import subprocess as sub
p = sub.Popen(["ls", "-al", "../"], stdin=sub.PIPE, stdout=sub.PIPE)
print p.stdout.read()
#outputs the files correctly
p.stdin.write("ls\n")
#IOError: [Errno 32] Broken pipe
---
--
http://mail.python.org/mailman/listinfo/python-list
Re: subprocess -- broken pipe error
On Jul 2, 11:32 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Jul 2, 1:12 pm, 7stud <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > Can someone explain what a broken pipe is? The following produces a
> > broken pipe error:
>
> > --
> > import subprocess as sub
>
> > p = sub.Popen(["ls", "-al", "../"], stdin=sub.PIPE, stdout=sub.PIPE)
>
> > print p.stdout.read()
> > #outputs the files correctly
>
> > p.stdin.write("ls\n")
> > #IOError: [Errno 32] Broken pipe
> > ---
>
> You are seeing this error because sub.Popen closes both stdin and
> stdout once the subprocess terminates (which it must have done for
> p.stdout.read() to return a result).
>
> Consequently you are trying to write to a pipeline whose reader has
> already closed it, hence the error message.
>
> regards
> Steve
Hi,
Thanks for the response. So are you saying that the only way you can
get data out of a pipe is when the subprocess has terminated?
--
http://mail.python.org/mailman/listinfo/python-list
Re: subprocess -- broken pipe error
Why doesn't the following program write to the file?
driver.py
---
import subprocess as sub
p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE,
stdout=sub.PIPE)
p.stdin.write("text3")
while True:
pass
---
test1.py:
-
import sys
data = sys.stdin.read()
f = open("aaa.txt", "w")
f.write(data + "\n")
f.close()
---
After I hit Ctrl+C to end the program and look in the file, the text
wasn't written to the file. But, if I change driver.py to the
following it works:
driver.py:
--
import subprocess as sub
p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE,
stdout=sub.PIPE)
p.stdin.write("text3")
---
Ok. So that looks like the data is caught in a buffer--even though the
pipes should be unbuffered by default. But this doesn't work:
driver.py
--
import subprocess as sub
p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE,
stdout=sub.PIPE)
p.stdin.write("text4")
p.stdin.flush()
while True:
pass
---
It just hangs, and then when I hit Ctrl+C and look in the file, the
data isn't in there.
--
http://mail.python.org/mailman/listinfo/python-list
Re: subprocess -- broken pipe error
On Jul 2, 1:58 pm, Bjoern Schliessmann wrote: > 7stud wrote: > > Thanks for the response. So are you saying that the only way you > > can get data out of a pipe is when the subprocess has terminated? > > No, not only because Pipes aren't related to processes in any > special way. > > He said that you can't write to a pipe whose reader has already > terminated. > What he said was: >...once the subprocess terminates (which it must have done for >p.stdout.read() to return a result) And based on the results of the examples I posted in my last post, it seems to confirm that no data travels through a pipe until a program on one side of the pipe has terminated. -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess -- broken pipe error
On Jul 2, 2:03 pm, Bjoern Schliessmann wrote: > 7stud wrote: > > Why doesn't the following program write to the file? > > [...] > > It just hangs, and then when I hit Ctrl+C and look in the file, > > the data isn't in there. > > Also, the pipe may be unbuffered by > default; file access isn't. > f.close() flushes the buffer to a file. -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess -- broken pipe error
On Jul 2, 2:12 pm, Steve Holden <[EMAIL PROTECTED]> wrote: > a) Who told you pipes should be unbuffered by default, and b) what difference > does that make anyway? > a) The docs. b) If the pipes were buffered then writing a small amount of data like "text3" to the pipe would cause the other side to hang forever thereby providing a possible explanation for the results. > > > It just hangs, and then when I hit Ctrl+C and look in the file, the > > data isn't in there. > > Of course it does, for the reasons mentioned above. file.read() only > returns when it has consumed *all* the data from the file (which means > the write must close the file for the reader to be able to return). > That doesn't seem like a very good explanation, since the only thing written to the file(i.e. stdin) was "text3", and the write() was unbuffered, so the read() could consume all the data without the write() closing the file--there was no more data. -- http://mail.python.org/mailman/listinfo/python-list
Re: list.append not working?
Hardy wrote:
> I experience a problem with append(). This is a part of my code:
>
> for entity in temp:
> md['module']= entity.addr.get('module')
> md['id']=entity.addr.get('id')
> md['type']=entity.addr.get('type')
> #print md
> mbusentities.append(md)
> #print mbusentities
>
> I want something like: [{'module': 'home', 'id': 123, 'type': 'core'},
> {'module': 'work', 'id': 456, 'type': 'core'}]
> md is always correct, BUT:mbusentities is wrong. Length of
> mbusentities is same of temp, so it appended everything. BUT:
> mbusentities only shows the values of the last append: [{'module':
> 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456,
> 'type': 'core'}]
>
> What's wrong?
Inside your loop, you assign md["module"], md["id"], and md["type"]
the same values over and over again.
--
http://mail.python.org/mailman/listinfo/python-list
Installing mod_python on mac os 10.4.7
The mod_python manual says this under section 2.1 Prerequisites: -- In order to compile mod_python you will need to have the include files for both Apache and Python, as well as the Python library installed on your system. If you installed Python and Apache from source, then you already have everything needed. However, if you are using prepackaged software (e.g. Red Hat Linux RPM, Debian, or Solaris packages from sunsite, etc) then chances are, you have just the binaries and not the sources on your system. Often, the Apache and Python include files and libraries necessary to compile mod_python are part of separate ``development'' package. If you are not sure whether you have all the necessary files, either compile and install Python and Apache from source, or refer to the documentation for your system on how to get the development packages. - I installed Apache from source using these instructions: http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-os-x/ but I used a package to install python 2.4. The package was from here: http://www.pythonmac.org/packages/ and it's a "Universal binary version of Python that runs natively on PPC and Intel systems." But my mac came with Python 2.3.5 pre-installed, so I wonder if I already have the necessary "include files for both Apache and Python, as well as the Python library" already installed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to POST to web page with cookies?
On Jul 19, 7:43 pm, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> Hello
>
> I need to write a script to automate fetching data from a web site:
> 1. using the POST method, log on, with login/password saved as cookies
> 2. download page and extract relevent information using regexes
> 3. log off
> 4. wait for a random number of minutes, and GOTO 1
>
> I'm a bit confused with how to get POST and cookies in the same
> script:
> - urllib vs urllib2 vs httplib?
> - "ClientCookie.urlopen("www") behaves identically to urllib2.urlopen,
> except that it deals with cookies automatically"
>
> Has anyone some working code that I could borrow (er... steal) to do
> this?
>
> Thank you.
Also, see here:
http://www.voidspace.org.uk/python/articles/cookielib.shtml
--
http://mail.python.org/mailman/listinfo/python-list
Re: Open HTML file in IE
On Jul 19, 11:09 pm, gravey <[EMAIL PROTECTED]> wrote: > The URL looks like this: > > file:///C|/Temp/Google%20Maps/linktothis.htm?lat=45.0&lng=-20.0&zoom=4&type =k > > The Javascript gets the URL from the Javascript location object and > parses it. I'm assuming that the location object has some kind of > Windows equivalent that might be set using win32com.client. Can anyone > shed any light on this? > > Thanks The location object is just your url. So, if the url of the page you open in IE is parsed by javascript, then you need to use a url with the proper information in it. -- http://mail.python.org/mailman/listinfo/python-list
Re: What makes an iterator an iterator?
On Apr 18, 8:50 am, [EMAIL PROTECTED] (Alex Martelli) wrote: > The special methods need to be on the type -- having attributes of those > names on the instance doesn't help (applies to all special methods in > the normal, aka newstyle, object model; legacy, aka classic, classes, > work by slightly different and not entirely self-consistent semantics). > > Alex Can you explain some of the details of why this code fails: --- class Parrot(object): def __iter__(self): return self def __init__(self): self.next = self.next().next def next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word P = Parrot() for word in P: print word -- It causes an infinite loop that just prints out the iterator object returned when you call the generator function. If I try this: - class Parrot(object): def __iter__(self): return self def __init__(self): print self.next() print self.next().next #self.next = self.next().next def next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word P = Parrot() ''' for word in P: print word ''' -- the output is: Based on that output, self.next() is the iterator object that wraps the generator function, and it has a next() method. If 'i' is the iterator object, then the statement: self.next = self.next().next is equivalent to: self.next = i.next and therefor calling P.next() is equivalent to i.next(), which appears to be exactly what you want. As I understand it, this is how the for loop works: 1) The for loop causes the built in, global iter() function to be called with P as an argument: iter(P). That calls P's __iter__() method, which just returns P. 2) The for loop repeatedly calls next() on whatever object is returned by 1), so that results in calls to P.next(). 3) P.next() is equivalent to i.next() I don't understand at which step does the code fail. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: import
On Apr 18, 10:34 am, [EMAIL PROTECTED] wrote:
> I thought import used relative paths from either the python executable
> or the script being executed. I have a script pulling in code from an
> arbitrary directory. How is this happening?
>
> It's a RHEL 4 environment by the way. I couldn't find any relevant
> environment variables.
>
> Thanks from a newbie for any insight.
>From the online python tutorial here:
http://docs.python.org/tut/
There is this:
--
6.1.1 The Module Search Path
When a module named spam is imported, the interpreter searches for a
file named spam.py in the current directory, and then in the list of
directories specified by the environment variable PYTHONPATH. This has
the same syntax as the shell variable PATH, that is, a list of
directory names. When PYTHONPATH is not set, or when the file is not
found there, the search continues in an installation-dependent default
path; on Unix, this is usually .:/usr/local/lib/python.
Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory containing
the input script (or the current directory), PYTHONPATH and the
installation-dependent default. This allows Python programs that know
what they're doing to modify or replace the module search path. Note
that because the directory containing the script being run is on the
search path, it is important that the script not have the same name as
a standard module, or Python will attempt to load the script as a
module when that module is imported. This will generally be an error.
See section 6.2, ``Standard Modules,'' for more information.
--
You can use the following trick to import one of your own modules when
your module
isn't in the current directory(and doesn't happen to be in PYTHONPATH
or the default path):
import sys
sys.path.append("relative path or absolute path to dir with the
module") # temporarily changes sys.path
import mymodule
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: import
Here's an example where you are trying to import a function in one of
your .py files--when that .py file is not in the current directory:
import sys
sys.path.append("/Users/me/2testing/dir1/")
#directory that contains the file
import test1 #name of file without .py extension
test1.greet()
--
http://mail.python.org/mailman/listinfo/python-list
Re: What makes an iterator an iterator?
Hi, Thanks for the responses. > 7stud <[EMAIL PROTECTED]> wrote: > > Can you explain some of the details of why this code fails: > --- > class Parrot(object): > def __iter__(self): > return self > def __init__(self): > self.next = self.next().next > def next(self): > for word in "Norwegian Blue's have beautiful > plumage!".split(): > yield word > > P = Parrot() > for word in P: > print word > -- On Apr 18, 8:45 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: > > ...a loop like "for x in y:" binds an unnamed temporary > variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to > be pedantic type(_t).next(t)] until that raises StopIteration. A. Isn't this the crux: > repeatedly calls[type(_t).next(t)] As far as I can tell, if the call was actually _t.next(), the code I asked about would work. However, the name look up for 'next' when you call: P.next() is entirely different from the name look up for 'next' when you call: type(P).next(). In the first lookup, the instance attribute "next" hides the class attribute "next". In the second lookup, the "next" attribute of the class is returned, i.e. the next() method. Yet, a generator-function- call returns an iterator object that wraps the generator function, so when the for loop makes repeated calls to type(P).next(), an iterator object is repeatedly returned--what you want is i.next() to be returned. I suspected next() might be called through the class, but after carefully parsing the section on iterators (Python in a Nutshell, p. 65) where it says iter() returns an object i, and then the for loop repeatedly calls i.next(), I dismissed that idea. I have to admit I'm still a little confused by why you only parenthetically noted that information and called it pedantic. On Apr 18, 8:38 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > > One very good way to get an iterator from an iterable is for .__iter__ to > be a generator function. Ahhh. That eliminates having to deal with next().next constructs. Nice. > snip all examples of bad code that violate the iterator rule > by improperly writing .next as a generator function What iterator rule states that .next can't be a generator function? My book says an iterator is any object with a .next method that is callable without arguments (Python in a Nutshell(p.65) says the same thing). Also, my boos says an iterable is any object with an __iter__ method.As a result, next() and __iter__() don't have to be in the same object: lass MyIterator(object): def __init__(self, obj): self.toIterateOver = obj def next(self): for x in range(self.toIterateOver.age): print x raise StopIteration class Dog(object): def __init__(self, age): self.age = age def __iter__(self): return MyIterator(self) d = Dog(5) for year in d: print year I've read recommendations that an iterator should additionally contain an __iter__() method, but I'm not sure why that is. In particular PEP 234 says: -- Classes can define how they are iterated over by defining an __iter__() method; this should take no additional arguments and return a valid iterator object. A class that wants to be an iterator should implement two methods: a next() method that behaves as described above, and an __iter__() method that returns self. The two methods correspond to two distinct protocols: 1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). Container-like objects usually support protocol 1. Iterators are currently required to support both protocols. The semantics of iteration come only from protocol 2; protocol 1 is present to make iterators behave like sequences; in particular so that code receiving an iterator can use a for-loop over the iterator. Classes can define how they are iterated over by defining an __iter__() method; this should take no additional arguments and return a valid iterator object. A class that wants to be an iterator should implement two methods: a next() method that behaves as described above, and an __iter__() method that returns self. The two methods correspond to two distinct protocols: 1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). Container-like objects usually support protocol 1. Iterators are currently required to support both protocols. The semantics of iteration come only from protocol 2; protocol
Re: Text Suffix to Prefix Conversion
On Apr 18, 11:08 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: > EMC ROY wrote: > > Original Sentence: An apple for you. > > Present: An apple for you .<.> > > Desire:An apple for you <.>. > >>> text = 'An apple for you .<.>' > >>> import re > >>> re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) > > 'An apple for you <.>.' If you end up calling re.sub() repeatedly, e.g. for each line in your file, then you should "compile" the regular expression so that python doesn't have to recompile it for every call: import re text = 'An apple for you .<.>' myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') re.sub(myR, r'\2\1\3', text) Unfortunately, I must be doing something wrong because I can't get that code to work. When I run it, I get the error: Traceback (most recent call last): File "2pythontest.py", line 3, in ? myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre.py", line 180, in compile return _compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre.py", line 225, in _compile p = sre_compile.compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_compile.py", line 496, in compile p = sre_parse.parse(p, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_parse.py", line 668, in parse p = _parse_sub(source, pattern, 0) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_parse.py", line 308, in _parse_sub itemsappend(_parse(source, state)) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_parse.py", line 396, in _parse if state.flags & SRE_FLAG_VERBOSE: TypeError: unsupported operand type(s) for &: 'str' and 'int' Yet, these two examples work without error: -- import re text = 'An apple for you .<.>' #myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') print re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) myR = re.compile(r'(hello)') text = "hello world" print re.sub(myR, r"\1XXX", text) -output: An apple for you <.>. helloXXX world Can anyone help? -- http://mail.python.org/mailman/listinfo/python-list
Re: What makes an iterator an iterator?
On Apr 19, 5:37 am, Steve Holden <[EMAIL PROTECTED]> wrote: > > It's nothing to do with the name lookup. Alex mentioned that to remind > us that the magic "double-under" names are looked up on the type rather > than the instance... P.next() vs. type(P).next() Where is the "double-under" name? -- http://mail.python.org/mailman/listinfo/python-list
Re: What makes an iterator an iterator?
On Apr 19, 3:12 pm, 7stud <[EMAIL PROTECTED]> wrote: > On Apr 19, 5:37 am, Steve Holden <[EMAIL PROTECTED]> wrote: > > > > > It's nothing to do with the name lookup. Alex mentioned that to remind > > us that the magic "double-under" names are looked up on the type rather > > than the instance... > > P.next() > > vs. > > type(P).next() > > Where is the "double-under" name? The following example looks up next() in the instance not the class: class Parrot(object): def __init__(self): self.next = lambda: "hello" def __iter__(self): return self def next(self): yield "goodbye" raise StopIteration p = Parrot() _t = iter(p) print _t.next() -output: hello -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and how to return text entry to main program?
On Apr 19, 1:38 pm, Tyler <[EMAIL PROTECTED]> wrote: > Hello All: > > I am currently working on a project to create an FEM model for school. > I was thinking about using wxPython to gather the 12 input variables > from the user, then, after pressing the "Run" button, the GUI would > close, and the 12 input variables would then be available for the rest > of the program. > > So far, what I have been able to do is mostly a reverse engineering > job to get the frame to look right and return the text variable to a > dialog box. > > I have read about a "redirect" that could be used to send the values > to a file. But, then I would have to open the file and read in the > data from there. This seems crude and lacking elegance. > > Any help on how to get the program to output the data back to the main > python program and close when I press submit? My apologies if this is > something of a simple question, but I have only started in on wxPython > about a week ago, and Python this term. > > The codes I am using are below. > > Any help (or suggested reading material) is greatly appreciated. > > Cheers, > > t. > > MY MAIN PROGRAM > > #!/usr/bin/env python > import femGUI > app = femGUI.MyApp(False) > dlg = femGUI.FemInput() > dlg.Destroy() > app.MainLoop() > > # Then do something with inputs here > > THE FEMINPUT GUI CLASS > > import wx > > class FemInput(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, -1, "Options Input Interface") > panel = wx.Panel(self) > > # First create the controls > > # Title > topLbl = wx.StaticText(panel, -1, "FEM 2D Basket Put Option > ",size=(420,-1)) > topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) > > # S1 lower and upper bounds for grid > s1label = wx.StaticText(panel, -1, "S1 Low , S2 Low: ", > size=(220,-1)) > self.s1lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S2 lower and upper bounds for grid > s2label = wx.StaticText(panel, -1, "S1 High, S2 High: ", > size=(220,-1)) > self.s1upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S1 and S2 volatility > vlabel = wx.StaticText(panel, -1, "S1 Volatility, S2 > Volatility: ", size=(220,-1)) > self.v1vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.v2vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Risk free rate and correlation > prlabel = wx.StaticText(panel, -1, "Interest Rate, > Correlation: ", size=(220,-1)) > self.risk= wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.corr= wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Strike and Exercise Date > kTlabel = wx.StaticText(panel, -1, "Srike Price, Exercise > Date: ", size=(220,-1)) > self.strike= wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.finalT= wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # deltaT and deltaX > dTXlabel = wx.StaticText(panel, -1, "delta T, delta X: ", > size=(220,-1)) > self.deltaT= wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.deltaX= wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Execute program > runBtn = wx.Button(panel, -1, "Run") > self.Bind(wx.EVT_BUTTON, self.OnSubmit, runBtn) > > # Now do the layout. > > # mainSizer is the top-level one that manages everything > mainSizer = wx.BoxSizer(wx.VERTICAL) > mainSizer.Add(topLbl, 0, wx.ALL, 5) > mainSizer.Add(wx.StaticLine(panel), 0, > wx.EXPAND|wx.TOP|wx.BOTTOM, 5) > > # femSizer is a grid that holds all of the address info > femSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) > femSizer.AddGrowableCol(1) > > # S1 and S2 LOWER label > femSizer.Add(s1label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s1Sizer = wx.BoxSizer(wx.HORIZONTAL) > s1Sizer.Add(self.s1lower, 1) > s1Sizer.Add((10,10)) # some empty space > s1Sizer.Add(self.s2lower, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s1Sizer, 1, wx.EXPAND) > > # S1 and S2 HIGH label > femSizer.Add(s2label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s2Sizer = wx.BoxSizer(wx.HORIZONTAL) > s2Sizer.Add(self.s1upper, 1) > s2Sizer.Add((10,10)) # some empty space > s2Sizer.Add(self.s2upper, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s2Sizer, 1, wx.EXPAND) > > # Volatility label > femSizer.Add(vlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > volSizer =
Re: List of Objects
[EMAIL PROTECTED] wrote: > > However, Python doesn't support pointers As I understand it, every name in Python is a pointer. class Gazelle(object): def __init__(self): self.x = 0 g_list =[] for x in range(10): g_list.append(Gazelle()) for g in g_list: g.x = 10 print g_list[2].x -- http://mail.python.org/mailman/listinfo/python-list
Re: List of Objects
On Apr 19, 9:18 pm, Paddy <[EMAIL PROTECTED]> wrote: > > # create a list of instances > gazelles= [ Gazelle() for x in range(5)] > Nice. I knew there had to be a way to use a list comprehension, but I couldn't figure it out. -- http://mail.python.org/mailman/listinfo/python-list
Re: wx.TextCtrl.SetDefaultStyle not working?
On Apr 20, 8:38 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I'm running Python2.5 with wxPython v2.8.3.0 under WinXP and I cannot
> get the SetDefaultStyle method to work.
>
> I'm trying:
>
> self.output.SetDefaultStyle(wx.TextAttr(wx.RED))
> self.output.AppendText(text)
> self.output.SetDefaultStyle(wx.TextAttr())
>
> where "self.output" is a TextCtrl window. The text appears, but it's
> always black. If I print the output of
> self.output.GetDefaultStyle().GetTextColour() before resetting it back
> to default, I see "(255, 0, 0, 255)". After reset, it's "(-1, -1, -1,
> 255)".
>
> The font in that window is the system default.
>
> Am I doing something wrong?
>
> -- Brian
You didn't show the code that creates the TextCtrl. Is it something
like this:
self.output = wx.TextCtrl(myFrame, -1, style=wx.TE_MULTILINE |
wx.TE_RICH2)
On my platform, styling the text doesn't work for single line
TextCtrl's(which seems kind of stupid), and on Windows I think you are
required to specify wx.TE_RICH2 to style the text. This following
code colors the entered text red for me:
import wx
myApp = wx.App(False)
myFrame = wx.Frame(None, -1, title="Test")
panel = wx.Panel(myFrame, -1)
my_tc = wx.TextCtrl(myFrame, -1, style=wx.TE_MULTILINE | wx.TE_RICH2)
my_tc.SetDefaultStyle(wx.TextAttr("red") )#wx.RED works too
myFrame.Show()
myApp.MainLoop()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Returning a date as string
On Apr 21, 2:59 pm, Björn Keil <[EMAIL PROTECTED]> wrote: > Hello pythons, > > I have little problem with understanding conversions in python. I've > written a little class - nothing much, just to try out Python a little > - containing the following method: > > def __repr__(self): > """Serializes the note. > > Currently the format of notes isn't decided upon. XML output > is > projected.""" > return "Due: " + str(self.dateDue) + \ >"\nDate: " + str(self.dateCreated) + \ >"\nSubject: " + self.subject + \ >"\n" + self.content > > The fields "dateDue" and "dateCreated" contain datetime.date objects. > Now when I try to serialize the whole thing: > > >>> myNote > > Traceback (most recent call last): > File "", line 1, in ? > File "notes.py", line 81, in __repr__ > return "Due: " + str(self.dateDue) + \ > TypeError: cannot concatenate 'str' and 'datetime.date' objects > > I tryed different variant before I wrapped "self.dateDue" in a str() > constructor: > I tried to put it in brackets, or call its .isoformat() method. > Nothing works. It still complains that I was trying to concatenate a > string with a date, but I really wanna concatenate a string with a > string! > > Could anyone please tell me what I am doing wrong? > > Greetings, > Björn This works for me: import datetime class MyDate(object): def __init__(self, date): self.d = date def __repr__(self): return str(self.d) md = MyDate(datetime.date.today()) print "the result is: " + repr(md) ##output:the result is: 2007-04-21 -- http://mail.python.org/mailman/listinfo/python-list
Re: serializable object references
Martin Drautzburg wrote:
> Is it possible to convert an object into a string that identifies the
> object in a way, so it can later be looked up by this string.
> Technically this should be possible, because things like
>
> <__main__.Foo instance at 0xb7cfb6ac>
>
> say everything about an object. But how can I look up the real object,
> when I only have this string?
>
> I know such a thing can be achieved with a dictionary that holds
> reference-object pairs. Is there another way?
How about:
class Dog(object):
def __init__(self, name):
self.name = name
d = Dog("Spot")
print globals()["d"].name
--
http://mail.python.org/mailman/listinfo/python-list
Re: serializable object references
On Apr 22, 5:07 am, Martin Drautzburg <[EMAIL PROTECTED]> wrote: > > <__main__.Foo instance at 0xb7cfb6ac> > > But how can I look up the real object, > when I only have this string? > You can't because that identifies the instance with an address, and pointers are not part of the python language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Javascript equivalence
On Apr 22, 7:00 pm, "Sam the Cat" <[EMAIL PROTECTED]> wrote:
> Hey All,
>
> I am writing some COM code in Python to control photoshop. Several
> functions of PS require an "Array" argument. In the examples of VBscript or
> javascript the Array type is used. I have tried what would appear to be the
> equivalent in Python -- Lists and Tuples -- but to no avail. Anyone have
> any insight on what via the COM interface is equivalent to an Array in
> javascript ?
>
> Cheers
> Sam
See if the python array type works:
import array
y = array.array("i", [2,3,4])
print y
--
http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - First Project
On Apr 23, 12:26 pm, [EMAIL PROTECTED] wrote: > I am assuming you are using Tkinter for your front-end GUI. You might > also take a gander at wxPython. It has an excellent demo you could > download and it might give you some additional ideas for > implementation:www.wxpython.org. > > Mike Hi, I've heard about that excellent demo, but I downloaded wxPython, and I don't even know where to look for it. Any pointers? -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - First Project
On Apr 23, 4:25 pm, 7stud <[EMAIL PROTECTED]> wrote: > On Apr 23, 12:26 pm, [EMAIL PROTECTED] wrote: > > > I am assuming you are using Tkinter for your front-end GUI. You might > > also take a gander at wxPython. It has an excellent demo you could > > download and it might give you some additional ideas for > > implementation:www.wxpython.org. > > > Mike > > Hi, > > I've heard about that excellent demo, but I downloaded wxPython, and I > don't even know where to look for it. Any pointers? Never mind. Got it: $ python /Developer/Examples/wxWidgets/wxPython/demo/demo.py -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - First Project
Uhhmm...how are you supposed to close a ShapedWindow(under Miscellaneous)? -- http://mail.python.org/mailman/listinfo/python-list
Re: wx.TextCtrl.SetDefaultStyle not working?
On Apr 23, 11:05 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > On my platform, styling the text doesn't work for single line > > TextCtrl's(which seems kind of stupid), and on Windows I think you are > > required to specify wx.TE_RICH2 to style the text. This following > > code colors the entered text red for me: > > That's it! I didn't have the TE_RICH2 option set. It works now. > > The docs say it's Windows only. Does the GTK version work without > this flag? > > -- Brian I'm not sure what GTK is, but on a Mac that style is ignored if it is set. Naturally, you can also style the text without that style being set. So, if you want your program to work cross platform, I assume you should set that style. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - First Project
On Apr 23, 5:04 pm, Kevin Haynes <[EMAIL PROTECTED]> wrote: > Hello > > I was a python newbie just a month ago and found the following books a great > help. > > Beginning Python: From Novice to Professional (Beginning: From Novice to > Professional) by Magnus L. Hetland (Paperback - 29 Sep > 2005)http://www.amazon.co.uk/Beginning-Python-Novice-Professional/dp/15905... > > WxPython in Action by Noel Rappin and Robin Dunn (Paperback - 30 Mar > 2006)http://www.amazon.co.uk/WxPython-Action-Noel-Rappin/dp/1932394621/ref... > > Kevin > > On Monday 23 April 2007, 7stud wrote: > > > Uhhmm...how are you supposed to close a ShapedWindow(under > > Miscellaneous)? I am reading both now, and I would not recommend either one. If you just skim over the examples and don't play with them, you might mistakenly believe you know what's going on, but if you actually try the examples and alter them here and there to figure out how things really work, you will discover all the mistakes and gaps in both books. -- http://mail.python.org/mailman/listinfo/python-list
Re: My python annoyances so far
[EMAIL PROTECTED] wrote: > Annoyances: > Every language has annoyances. Python is no exception. Post away. Anyone that is offended can go drink a Guinness. > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). > I thought those were pretty ugly myself. Now, I am used to them. > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? I know what you mean. I always write: someStringVar.len and then I backspace and retype: len(someString). But then again, I can never remember whether length is a member or a method in other languages. -- http://mail.python.org/mailman/listinfo/python-list
Re: My python annoyances so far
On Apr 26, 9:08 am, Michael Hoffman <[EMAIL PROTECTED]> wrote: > 7stud wrote: > > [EMAIL PROTECTED] wrote: > >> Annoyances: > > > Every language has annoyances. Python is no exception. Post away. > > Anyone that is offended can go drink a Guinness. > > I find Guinness annoying. > -- > Michael Hoffman lol. -- http://mail.python.org/mailman/listinfo/python-list
Re: python function in pipe
On Apr 28, 7:37 am, Bart <[EMAIL PROTECTED]> wrote: > Hi everyone! > > Im using module that gives errors to stderr/stdout (generated by SWIG) > Problem is that I need to parse this errors/information from module. > > os.popen3 looks nice but this executes command not function. > > Is there any solution? > > Best regards > Bart. Maybe something like this: moduleA.py: --- def someFunc(): print "hello" raise ValueError someFunc() -- import subprocess print "Main executing" try: p = subprocess.Popen(["python", "6test.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = p.wait() if result == 0: print "output:", p.stdout.read() else: print "output before error:", p.stdout.read() print "error:", p.stderr.read() except (OSError, TypeError, ValueError), e: print "subprocess was never started" print e -- http://mail.python.org/mailman/listinfo/python-list
Re: python function in pipe
> p = subprocess.Popen(["python", "6test.py"], > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) The file name is wrong there; it should be: p = subprocess.Popen(["python", "moduleA.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I put an Exception as the key of a hash table
[EMAIL PROTECTED] wrote:
> I want to keep track of the number of different exception happens in
> my python program:
>
> ErrorHash = {}
>
> try:
>
> # come code ...
>
> except Exception, e:
> print e
> errcode = e
>
> if (ErrorHash.has_key(errcode)):
> ErrorFailNo = ErrorHash[errcode]
>
> ErrorHash[errcode] = ErrorFailNo + 1
>
> else:
> ErrorHash[errcode] = 1
>
>
> But when i print out the ErrorHash like this:
>
> print ErrorHash
>
> i get an empty string. Can you please tell me how can I put an
> Exception as the key of a hash table ? Or how can i dump out all the
> content of the hashtable.
>
> Thank you.
Apparently, the Exception class's __str__() method doesn't print
anything about the exception. That doesn't mean the exception is an
empty string though:
ErrorHash = {}
try:
raise ValueError
except Exception, e:
print "the exception is:", e, "<"
if (ErrorHash.has_key(e)):
ErrorFailNo = ErrorHash[e]
ErrorHash[e] = ErrorFailNo + 1
else:
ErrorHash[e] = 1
print ErrorHash
--
http://mail.python.org/mailman/listinfo/python-list
Re: howto check is object a func, lambda-func or something else?
On Apr 29, 11:19 am, dmitrey <[EMAIL PROTECTED]> wrote: > > callable(lambda-func) returnes False > I'm not seeing that. Try this: f = lambda x: x print callable(f) ---output:-- True -- http://mail.python.org/mailman/listinfo/python-list
Re: Restricting the alphabet of a string
On Apr 30, 5:53 am, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I ve being thinking about playing around with bit strings but use in
> some encoding problems I m considering and was trying to decide how to
> implement a bit string class. Is there a library out there for doing
> basic things with bit strings already is my first question?
>
> I know that I can extend string to bit string, but is there anyway I
> can force the alphabet to be restricted to 1's and 0's (or even 1, 0
> and -1, as an extension to from trinary strings).
>
> class Binary_String(String):
> pass
>
> Many Thanks
>
> Nathan
You could do something like this:
class Binary_String(str):
def __init__(self, val):
i = 0
for char in val:
if char not in "-101":
raise ValueError("illegal character at index " +
str(i)+ "\nOnly -1,0,1 allowed.")
i+=1
self.val = val
b = Binary_String("1a0101")
--output:--
Traceback (most recent call last):
File "test1.py", line 13, in ?
b = Binary_String("1a100")
File "test1.py", line 6, in __init__
raise ValueError("illegal character at index " + str(i)
ValueError: illegal character at index 1
Only -1,0,1 allowed.
--
http://mail.python.org/mailman/listinfo/python-list
sqlite for mac?
Does sqlite come in a mac version? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Store variable name in another variable
On May 1, 6:43 am, loial <[EMAIL PROTECTED]> wrote:
> OK, I have it working with dictionaries.
>
> However I have another scenerio :
>
> I am reading a file containing records like the following :
>
>
>
>
> ..
> ..
>
> I need to substitute MYVARIABLE with the current value of MYVARIABLE
> in my python script and write the file out again.
>
> The file may contain many more lines and many substitution values on
> any line
>
> Assuming that MYVARIABLE is currently set to JOHN then the output
> would be
>
>
>
>
>
> Can this be done in Python?
s = "hello world, goodbye world"
result = s.replace("world", "moon")
print result
--
http://mail.python.org/mailman/listinfo/python-list
Re: Why are functions atomic?
On May 1, 5:06 am, Michael <[EMAIL PROTECTED]> wrote: > Why are functions atomic? (I.e. they are not copied.) > > For example, I would like to make a copy of a function so I can change > the default values: > > >>> from copy import copy > >>> f = lambda x: x > >>> f.func_defaults = (1,) > >>> g = copy(f) > >>> g.func_defaults = (2,) > >>> f(),g() > > (2, 2) > > I would like the following behaviour: > > >>> f(),g() > > (1,2) > > I know I could use a 'functor' defining __call__ and using member > variables, but this is more complicated and quite a bit slower. (I > also know that I can use new.function to create a new copy, but I > would like to know the rational behind the decision to make functions > atomic before I shoot myself in the foot;-) > > Thanks, > Michael. Does deepcopy work? -- http://mail.python.org/mailman/listinfo/python-list
Re: Having problems accepting parameters to a function
On May 1, 10:38 am, rh0dium <[EMAIL PROTECTED]> wrote:
> Hi Experts!!
>
> I am trying to get the following little snippet to push my data to the
> function func(). What I would expect to happen is it to print out the
> contents of a and loglevel. But it's not working. Can someone please
> help me out.
>
> ---
> #!/usr/bin/env python
>
> import random
>
> def func(*args, **kwargs):
>print kwargs.get('a', "NOPE")
>print kwargs.get('loglevel', "NO WAY")
>
> def main():
>b = []
>for x in range(5):
> b.append({'a':random.random(), "loglevel":10})
>
>for y in b:
> apply(func,y)
>
> # First attempt - didn't work
> # for y in b:
> # func(y)
>
> if __name__ == '__main__':
>main()
1) apply() is deprecated
2) You need to unpack the dictionary using ** before sending it to
func(), whereupon it will be repacked into a dictionary.
import random
def func(*args, **kwargs):
print kwargs.get('a', "NOPE")
print kwargs.get('loglevel', "NO WAY")
def main():
b = []
for x in range(5):
b.append({'a':random.random(), "loglevel":10})
for y in b:
func(**y)
if __name__ == '__main__':
main()
You might consider redefining func() so that you don't have to do the
unpack--repack:
--
http://mail.python.org/mailman/listinfo/python-list
Re: sqlite for mac?
On May 1, 4:08 am, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote: > > Does sqlite come in a mac version? > > The interface (pysqlite) is part of the python 2.5 standard library > but you need to install sqlite itself separately (as far as I > remember) fromwww.sqlite.org > > Daniel I'm using python 2.4.4 because the download said there were more mac modules available for 2.4.4. than 2.5, and I can't seem to locate a place to download sqlite for mac. -- http://mail.python.org/mailman/listinfo/python-list
Re: Having problems accepting parameters to a function
On May 1, 11:06 am, 7stud <[EMAIL PROTECTED]> wrote: > > You might consider redefining func() so that you don't have to do the > unpack--repack... When you define a function like this: def func(**keywordargs): print keywordargs the function expects to receive arguments in the form: func(a="hello", b="world") not: func(adict) -- http://mail.python.org/mailman/listinfo/python-list
Re: Having problems accepting parameters to a function
kwargs is not a built in name--it's a made up name used in the docs.Would you expect this function to work: def somefunc(x=10, y=20): print a The best way to figure out a feature of a programming language that you don't understand is not in the middle of some complex program. Instead, you should begin a new program, or if you are smart you will already have several blank programs already created waiting in the wings for testing purposes. In the new program, you can play around with functions, default values and catch all parameters like *a and **b to figure out how they work. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join
On May 1, 7:36 pm, Elliot Peele <[EMAIL PROTECTED]> wrote:
> Why does os.path.join('/foo', '/bar') return '/bar' rather than
> '/foo/bar'? That just seems rather counter intuitive.
>
> Elliot
join( path1[, path2[, ...]])
Join one or more path components intelligently. If any component is an
absolute path, all previous components (on Windows, including the
previous drive letter, if there was one) are thrown away...
--
http://mail.python.org/mailman/listinfo/python-list
Re: Writing a nice formatted csv file
On May 2, 8:14 am, redcic <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I use the csv module of Python to write a file. My code is of the
> form :
>
> cw = csv.writer(open("out.txt", "wb"))
> cw.writerow([1,2,3])
> cw.writerow([10,20,30])
>
> And i get an out.txt file looking like:
> 1,2,3
> 10,20,30
>
> Whereas what I'd like to get is:
> 1,2,3,
> 10, 20, 30
>
> which is more readable.
>
> Can anybody help me to do so ?
>
> Thanks,
>
> Cédric
cvs files are constructed for efficient processing not formatting so
that you can read them easier. If you want a formatted file, then
construct one.
--
http://mail.python.org/mailman/listinfo/python-list
Re: sqlite for mac?
On May 1, 6:09 am, Ben Secrest <[EMAIL PROTECTED]> wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > On 2007-05-01, Daniel Nogradi <[EMAIL PROTECTED]> wrote: > > >> Does sqlite come in a mac version? > > > The interface (pysqlite) is part of the python 2.5 standard library > > but you need to install sqlite itself separately (as far as I > > remember) fromwww.sqlite.org > > http://developer.apple.com/documentation/MacOSX/Conceptual/OSX_Techno... > > - -- > Ben Secrest <[EMAIL PROTECTED]> > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.7 (NetBSD) > > iD8DBQFGNy4DeLi5NDZQ3o0RAtVOAJ9AglHEPH/9HUKIsLLWIkaNwoZC8QCaAy7T > MC8VhXY2MyOyp2DaJAPOb0I= > =UGAL > -END PGP SIGNATURE- I downloaded pysqlite, ran the setup script, and tested the installation and everything worked fine. However, if I try to import either sqlite, sqlite2, or sqlite3 into a python program, I get an error saying there's no such module. I assume that means pysqlite cannot see the installation of SQlite that came preinstalled on my mac. My python book says to download the SQlite source where automatic code generation has already been performed. I did that. Then my book says says to follow the instructions in the README file. However, the download only has two files: sqlite3.c and sqlite3.h. As a result, I don't know what to do. Any advice? -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite for mac?
> Did you install Xcode on your Mac? Yes, Xcode 2.4. -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite for mac?
Per the pysqlite installation instructions, this is the test I ran to
confirm that pysqlite installed correctly
>from pysqlite2 import test
>test.test()
and I got output similar to what the docs say should happen:
>ran 101 tests in 0.182s
My python book, "Beginning Python: From Novice to Professional"(2005),
after giving some brief installation instructions for SQLite and
pysqlite, says:
"Once you have pysqlite installed, you can import it as a module,
under the name sqlite."
and then the author provides this example:
>>>import sqlite
>>>conn = sqlite.connect('somedatabase.db')
>>>curs = conn.cursor()
This cursor can then be used to make SQL queries...
>>>conn.commit()
>>>conn.close()
So that is what I tried. Then I changed "sqlite" to "sqlite2" and
"sqlite3" as well.
--
http://mail.python.org/mailman/listinfo/python-list
Re: sqlite for mac?
On May 3, 8:37 am, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote: > > If all tests ran fine then pysqlite can see your sqlite installation. > How are you importing sqlite? It's usually something like "from > pysqlite2 import dbapi2 as sqlite" not simply "import sqlite". > I just checked the errata for the book, and it says to use the import statement you suggested: > from pysqlite2 import dbapi2 as sqlite -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
On May 3, 7:21 pm, Andy Terrel <[EMAIL PROTECTED]> wrote:
> Okay does anyone know how to decorate class member functions?
>
> The following code gives me an error:
>
> Traceback (most recent call last):
> File "decorators2.py", line 33, in
> s.update()
> File "decorators2.py", line 13, in __call__
> retval = self.fn.__call__(*args,**kws)
> TypeError: update() takes exactly 1 argument (0 given)
>
> --
>
> #! /usr/bin/env python
>
> class Bugger (object):
> def __init__ (self, module, fn):
> self.module = module
> self.fn = fn
>
> def __call__ (self,*args, **kws):
> ret_val = self.fn(*args,**kws)
> return ret_val
>
> def instrument (module_name):
> ret_val = lambda x: Bugger(module_name, x)
> return ret_val
>
> class Stupid:
> def __init__(self):
> self.val = 1
>
> @instrument("xpd.spam")
> def update(self):
> self.val += 1
>
> s = Stupid()
> s.update()
As far as I can tell, the problem is that the decorator executes when
the class is parsed, and at that time there is no self(the instance
object). The decorator produces a callable Bugger object, but the
callable object has no way to get self when s.update() is called.
Normally when you call a class function, like s.update(), the
__get__() method in the 'update' function object is called (all
function objects have a __get__() method and therefore are
descriptors). Then __get__() creates a method object out of the
function object(update), and python automatically passes the instance
object to the method object. However, the Bugger object does not have
a __get__() method, so no method object is created when the Bugger
object is called, and therefore self is not automatically passed to
the Bugger object.
The following solution adds a __get__() method to the Bugger object.
Python automatically passes the instance object to the __get__()
method, and the solution stores the instance in the Bugger object.
Then __call__ is defined to send the instance object to update().
class Bugger (object):
def __init__ (self, module, fn):
self.module = module
self.fn = fn
def __call__ (self,*args, **kws):
ret_val = self.fn(self.obj, *args,**kws)
return ret_val
def __get__(descr, inst, instCls=None):
descr.obj = inst
return descr
def instrument (module_name):
ret_val = lambda func: Bugger(module_name, func)
return ret_val
class Stupid(object):
def __init__(self):
self.val = 1
@instrument("xpd.spam")
def update(self):
self.val += 1
s = Stupid()
s.update()
s.update()
s.update()
print s.val
--output:--
4
--
http://mail.python.org/mailman/listinfo/python-list
Re: behavior difference for mutable and immutable variable in function definition
On May 4, 3:30 pm, [EMAIL PROTECTED] wrote: > Hi, > > Can anyone explain the following: > > Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> def > foo(): > > ... x = 2 > ...>>> foo() > >>> def bar(): > > ... x[2] = 2 > ... > > >>> bar() > > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in bar > NameError: global name 'x' is not defined > > Thanks, > Jianbing The first function is completely irrelevant unless you expect this to work: x = 2 x[2] = 2 Traceback (most recent call last): File "test1.py", line 2, in ? x[2] = 2 TypeError: object does not support item assignment So that leaves you with: > >>> def bar(): > > ... x[2] = 2 > ... > > >>> bar() Would you expect this to work: x[2] = 2 print x -- http://mail.python.org/mailman/listinfo/python-list
Re: Further adventures in array slicing.
> A second question is: When can you use += vs .append(). > Are the two always the same? They are never the same unless you only add one item to the list. append() will only increase the length of a list by 1. la = [1,2] lb = [3, 4, 5] la += lb print la lc = [1,2] lc.append(lb) print lc --output:-- [1, 2, 3, 4, 5] [1, 2, [3, 4, 5]] print la[2] print lc[2] --output:-- 3 [3, 4, 5] -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more pythonic/faster append or +=[]
On May 8, 11:05 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: > alf <[EMAIL PROTECTED]> wrote: > > two ways of achieving the same effect > > > l+=[n] > > > or > > > l.append(n) > > > so which is more pythonic/faster? > > .append - easy to measure, too: > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > 100 loops, best of 3: 1.31 usec per loop > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' > 100 loops, best of 3: 1.52 usec per loop > > Alex Why is it necessary to copy L? -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more pythonic/faster append or +=[]
On May 8, 11:05 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: > alf <[EMAIL PROTECTED]> wrote: > > two ways of achieving the same effect > > > l+=[n] > > > or > > > l.append(n) > > > so which is more pythonic/faster? > > .append - easy to measure, too: > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > 100 loops, best of 3: 1.31 usec per loop > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' > 100 loops, best of 3: 1.52 usec per loop > > Alex Ah, I see. The list would grow too large with all that appending, so you begin again with the original list for every loop. Is there any documentation for the syntax you are used with timeit? I checked 'man python', and I also read the example in the python docs, but you seem to be using a hybrid syntax. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more pythonic/faster append or +=[]
> Is there any documentation for the syntax you used with timeit? This is the syntax the docs describe: --- Python Reference Library 10.10.1: When called as a program from the command line, the following form is used: python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] --- Then in the examples in section 10.10.2, the docs use a different syntax: % timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' 10 loops, best of 3: 15.7 usec per loop % timeit.py 'if hasattr(str, "__nonzero__"): pass' 10 loops, best of 3: 4.26 usec per loop % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' 100 loops, best of 3: 1.43 usec per loop % timeit.py 'if hasattr(int, "__nonzero__"): pass' 10 loops, best of 3: 2.23 usec per loop --- and then there is Alex Martelli's syntax: >>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more pythonic/faster append or +=[]
On May 10, 2:39 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: > 7studwrote: > >> Is there any documentation for the syntax you used with timeit? > > > This is the syntax the docs describe: > [snip > > python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] > [snip] > > Then in the examples in section 10.10.2 > [snip] > > timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' > [snip] > > and then there is Alex Martelli's syntax: > [snip] > > python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > > The following three things are equivalent: > python /path/to/.py > /path/to/.py # assuming the OS knows how to exec it > python -m# assuming is on sys.path > > So that just leaves the differences between: > [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] > 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' > 'L=range(3); n=23' 'x=L[:]; x.append(n)' > > Those look pretty similar to me (aside from the fact that they're > testing different things). Each argument in single quotes is a line of > the code you want timed. > Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: removing spaces between 2 names
On May 15, 12:14 am, Steven Howe <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi,
> > Suppose i have a string stored in variable,how do i remove the
> > space between them,like if i have the name:
> > "USDT request" in a variable.i need "USDTrequest",without any space .
> > Thanks
>
> from string import replace
> st = 'abcd acdfgxtit'
> st.replace(' ','')
> 'abcdacdfgxtit'
>
> sph
>
> --
> HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
The methods in the string module are deprecated. Skip the import and
use a string's built in replace() method instead:
s = "hello world"
result = s.replace(" ", "")
print result
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Newbie Suggestions
Not "Learning Python: From Novice to Professional". I've looked at "Learning Python 2nd Ed." to use as a reference for all the blunders in the first book I mentioned, and it's a lot better--plus it has exercises at the end of each chapter. -- http://mail.python.org/mailman/listinfo/python-list
