Re: Printing n elements per line in a list
unexpected wrote:
> If have a list from 1 to 100, what's the easiest, most elegant way to
> print them out, so that there are only n elements per line.
>
> So if n=5, the printed list would look like:
>
> 1 2 3 4 5
> 6 7 8 9 10
> 11 12 13 14 15
> etc.
>
> My search through the previous posts yields methods to print all the
> values of the list on a single line, but that's not what I want. I feel
> like there is an easy, pretty way to do this. I think it's possible to
> hack it up using while loops and some ugly slicing, but hopefully I'm
> missing something
I suppose 'elegance' is in the eye of the beholder. I agree with the
previous posts, a readable for loop is probably the best way to go.
I've instead chosen to use the functional paradigm. I thought someone
might appreciate this:
p = sys.stdout.write
map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,101)])
--
http://mail.python.org/mailman/listinfo/python-list
Re: Printing n elements per line in a list
John Machin wrote:
> Matimus wrote:
> > unexpected wrote:
> > > If have a list from 1 to 100, what's the easiest, most elegant way to
> > > print them out, so that there are only n elements per line.
> > >
> > > So if n=5, the printed list would look like:
> > >
> > > 1 2 3 4 5
> > > 6 7 8 9 10
> > > 11 12 13 14 15
> > > etc.
> > >
> > > My search through the previous posts yields methods to print all the
> > > values of the list on a single line, but that's not what I want. I feel
> > > like there is an easy, pretty way to do this. I think it's possible to
> > > hack it up using while loops and some ugly slicing, but hopefully I'm
> > > missing something
> >
> > I suppose 'elegance' is in the eye of the beholder. I agree with the
> > previous posts, a readable for loop is probably the best way to go.
> > I've instead chosen to use the functional paradigm. I thought someone
> > might appreciate this:
> >
> > p = sys.stdout.write
> > map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,101)])
>
> At least three strikes:
>
> 1. The functional paradigm AFAIK abjures side effects.
>
> |>>> n = 3
> |>>> map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,11)])
> 1 2 3
> 4 5 6
> 7 8 9
> 10 [None, None, None, None, None, None, None, None, None, None]
>
> If you want functional, instead of
> map(sys.stdout.write, strings)
> do this:
> sys.stdout.write(''.join(strings))
>
> 2. This little gem
> ("\n"+" "*(n-1))[i%n]
> is better written
> " \n"[i%n==0]
>
> 3. Like some other attempts, it's missing the trailing \n when len(seq)
> % n != 0
>
> 4. It needs elaboration so that it works with any sequence, not just
> range(1, size+1)
>
> Yer out!
>
> Cheers,
> John
Well, I have another at bat, so I will try to redeem myself... using
recursion:
def printTable(l,c):
print(("%d "*len(l[:c]))%tuple(l[:c]))
if( len(l[:c]) > 0 ):
printTable(l[c:],c)
printTable(range(1,101),5)
--
http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
You could do something like this:
>>> class MyDict(dict):
... pass
>>> bananna = MyDict({"foo":"bar"}) #dict constructor still works
>>> bananna.name = "bananna"
>>> bananna.name
'bananna'
>>> bananna
{'foo': 'bar'}
Or, you could also just do this:
>>> bananna = {"name":"bananna"}
Depending on what you actually want to use it for the best solution is
to use the id instead of a name though.
-Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: How do I read Excel file in Python?
> the date( 8/9/2006 ) in Excel file, i am getting the value as 38938.0, > which I get when I convert date values to general format in Excel. I > want the actual date value. How do get that? 38938 appears to be the date in days since 1/1/1900. I'm sure someone can help you figure out how to convert that to a more useful value. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
> is it possible in python (with/without matplotlib, numpy etc) to store > a whole class with its data into a file, instead it to reconstruct > every time again? So is there an analogous to the matlab functions > load/save available? look up the pickle module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception Handling in TCPServer (was; Problem exiting application in Windows Console.)
> This seems a really nasty hack though - any ideas for a cleaner way to > do it? You could overload handle_request instead. I think that makes more sense anyway because you don't want to handle a SystemExit exception as an error, you want to exit. Of course this only deals with catching the exception, there may be a better method of shutting down and exiting the server (other than sys.exit that is). class HelpServer(HTTPServer): def handle_request(self): try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): try: self.process_request(request, client_address) except SystemExit: raise SystemExit except: self.handle_error(request, client_address) self.close_request(request) -- http://mail.python.org/mailman/listinfo/python-list
Re: Will GPL Java eat into Python marketshare?
John Bokma wrote: > Intelligent people don't suffer from fanboy sentiments. They just pick a > language that works best for them. Adding to that, they pick the language that works best for them and the situation. Python has a significant advantage in many applications because it is dynamic and can be used for rapid development. IMHO, usually more rapid than Java. Hopefully Java being GPL'd will make it easier to deploy applications, especially on Linux. There are many applications where Java has a significant advantage. I plan to make use of both. -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Boris wrote: > Hi, is there any alternative software for Matlab? Although Matlab is > powerful & popular among mathematical & engineering guys, it still > costs too much & not publicly open. So I wonder if there's similar > software/lang that is open & with comparable functionality, at least > for numerical aspect. Thanks! There is also Scilab. I've only used it a tiny bit but for the task it worked well. I do know that it has a somewhat restrictive license. It is open source, but you aren't allowed to modify and redistribute the source. I get the feeling that some people avoid Scilab but I'm not sure why. If anybody knows the reason I'd be happy to hear it. Scilab website: http://www.scilab.org -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: How to let a loop run for a while before checking for break condition?
Claudio Grondi wrote:
> Sometimes it is known in advance, that the time spent in a loop will be
> in order of minutes or even hours, so it makes sense to optimize each
> element in the loop to make it run faster.
> One of instructions which can sure be optimized away is the check for
> the break condition, at least within the time where it is known that the
> loop will not reach it.
>
> Any idea how to write such a loop?
>
> e.g.
>
> counter = 2*64
>
> while counter(BUT DON'T CHECK IT THE FIRST ONE HOUR LONG):
>... do something ... # and decrease the counter
>
> Thanks for any hint, but in particular if related to timers on the
> Windows 2000/XP system I am mainly working with.
>
> What do you think about this idea? Does it make sense?
>
> Claudio Grondi
Would simple loop unrolling help? I've never experimented with loop
unrolling in python, but perhaps something like this would help. Also,
it sort of depends upon the condition. Do you know how many times 'do
something' will be performed before hand?
do_something = compile("print 'do_something'","loop.tmp","single")
loop_list = [do_something]*(loop_count)
for x in loop_list: exec(x)
Note that this offloads some work upfront but depending on what is
being done it might still be quicker. It will take up more memory, but
the list will only be full of references. I'm pretty sure that the for
loop, in this case, will not be doing a check each iteration since it
is operating on a list, but I'm not positive.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Data sticking around too long
taskName and scanList are defined at the class level making them class attributes. Each instance of the ScannerCommand class will share its class attributes. What you want are instance attributes which can be initialized whithin the constructor like so: >>> class ScannerCommand: ... def __init__(self): ... self.taskName = '' ... self.scanList = [] ... print "Creating a ScannerCommand object; list has " + \ ... str(len(self.scanList)) + " objects." [EMAIL PROTECTED] wrote: > Greetings! > > Here's my script: > > start of script > class ScannerCommand: > taskName = '' > scanList = [] > > def __init__(self): > print "Creating a ScannerCommand object; list has " + \ > str(len(self.scanList)) + " objects." > > class Scanner: > def Read(self, data): > command = ScannerCommand() > command.scanList.append(data) > return command > > class Handler: > def Process(self, dataList): > print "Processing data" > for data in dataList: > print " " + data > print "Finished processing data." > > if __name__ == '__main__': > s = Scanner() > count = 0 > for data in ["Zero", "One", "Two", "Three"]: > command = s.Read(data) > handler = Handler() > handler.Process(command.scanList) > ## End of script > > Here's the result: > > ## Start of result > Processing data >Zero > Finished processing data. > Creating a ScannerCommand object; list has 1 objects. > Processing data >Zero >One > Finished processing data. > Creating a ScannerCommand object; list has 2 objects. > Processing data >Zero >One >Two > Finished processing data. > Creating a ScannerCommand object; list has 3 objects. > Processing data >Zero >One >Two >Three > Finished processing data. > End of result > > I had expected to get "Zero" by itself, then "One" by itself, and so > on. > > Why is the ScannerCommand object being created with a scanList that > contains the data that was in the previously created ScannerCommand > object? And what do I have to do to ensure that the code that is run > when I call ScannerCommand() gives me an object with an empty scanList? > > I am a C++ developer in a shop that uses some Python as well, and I > just ran across this behavior for the first time. I believe it is due > to the difference between binding a variable to an object, as Python > does, and actually creating the variable, as a similar C++ application > would do. > > Thank you very much. > > Rob Richardson > RAD-CON, Inc. > Bay Village, OH -- http://mail.python.org/mailman/listinfo/python-list
Re: Data sticking around too long
Someone correct me if I'm wrong (sometimes I get the terms mixed up)
but I believe that what you are seeing is due to 'number' being an
immutable type. This means that its value cannot be changed and thus
each assignment is effectively creating a new instance if int. I
believe lists are considered immutable also but since it is a container
type it behaves somewhat differently. I read a thread earlier that
addressed a similar issue but I can't find it now. I will post again if
I come accross it. Anyway, as a demonstration try this using python's
command line prompt:
>>> i = int()
>>> j = i
>>> j is i
True
### j and i are attributes that point to the same instance
>>> i = 1
>>> j is i
False
### assignment to I made a new instance and j and i are no longer the
same instance
>>> a = [0,1,2]
>>> b = a
>>> b is a
True
### the same is true for lists
>>> b = [0,1,3]
>>> b is a
False
>>> b = a
>>> b is a
True
### but since 'a' is a container its contents can be modified without
creating a new instance
>>> b[1] = 3
>>> b is a
True
>>> a
[0,3,2]
>>> b
[0,3,2]
>>> a.append(4)
>>> a
[0,3,2,4]
>>> b
[0,3,2,4]
>>> b is a
True
I hope this helps.
-Matt
[EMAIL PROTECTED] wrote:
> Greetings again!
>
> There's something more to determining whether a class member is a class
> variable or an instance variable. Here's a slightly expanded version
> of my last script:
>
> class ScannerCommand:
> taskName = ''
> scanList = []
> number = 0
>
> def __init__(self, data):
> pass
> #self.scanList = []
> #self.scanList.append(data)
>
> if __name__ == '__main__':
> c1 = ScannerCommand("c1")
> c2 = ScannerCommand("c2")
> c1.number = 1
> c2.number = 2
> c1.scanList.append("One")
> c2.scanList.append("Two")
> print "C1: " + str(c1.number)
> for data in c1.scanList:
> print " " + data
> print "C2: " + str(c2.number)
> for data in c2.scanList:
> print " " + data
>
> And here's the output:
> C1: 1
>One
>Two
> C2: 2
>One
>Two
>
> Here, the two instances share the scanList list, as expected from
> previous discussions, but they have their own copies of the number
> variable. Why is scanList a class variable but number an instance
> variable here?
>
> Good night, all!
>
> Rob Richardson
> RAD-CON, Inc.
> Bay Village, OH
--
http://mail.python.org/mailman/listinfo/python-list
Re: I wish I could add docstrings to vars.
It seems that you are getting some complex answers with confusing examples. So, here is hopefully a less confusing example: class MyDict(dict): """MyDict doc-string!""" #then to use it d = MyDict() d['something'] = whatever you want This solution leaves it open to do whatever you want with the class, but it's better than nothing. Matthew Wilson wrote: > I build a lot of elaborate dictionaries in my interpreter, and then I > forget exactly how they work. It would be really nice to be able to add > notes to the dictionary. > > Is there some way to do this now? > > Matt > > > -- > A better way of running series of SAS programs: > http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles -- http://mail.python.org/mailman/listinfo/python-list
Re: Help
I have yet to find a language/community with better online documentation. I taught myself with the Python tutorial found at http://docs.python.org/tut/tut.html. I would look there first. If you are new to programming altogether I think Python may still be a good choice, but that may not be the _best_ reference. Rrajal wrote: > Hi there, I am new in this subject so could you please tell me from > where I can get help (or good e-book) of python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to run an external program
Brant Sears wrote:
> Hi. I'm new to Python and I am trying to use the latest release (2.5)
> on Windows XP.
>
> What I want to do is execute a program and have the results of the
> execution assigned to a variable. According to the documentation the
> way to do this is as follows:
>
> import commands
> x = commands.getstatusoutput('dir')
>
> This should assign "x" to be the output of the command "dir".
> However, when I run this (or any other command), x ends up being:
>
> (1, "'{' is not recognized as an internal or external command,
> \noperable program or batch file.")
>
> From looking through the documentation, I'm believing that the
> implementation of commands.getstatusoutput is actually some multi-
> step thing that starts with issuing the bracket character that is
> being choked on. This leads me to believe that Python or perhaps just
> the commands module is not setup correctly on my computer.
>
> I installed Python using the Python2-5.msi link that I found at:
> http://www.python.org/download/releases/2.5/
>
> I left everything the default during installation, so Python was
> installed to C:\Python25. The only other thing I did was add this
> PATH variable on my computer.
>
> Any ideas on what I might do to troubleshoot this?
>
> Thanks!
>
> Brant Sears
commands is a Unix module, hence it will not work in Windows XP. If you
don't need the return code try this:
import os
pipe = os.popen('dir')
x = pipe.read()
# do something with x
-Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: generator with subfunction calling yield
The issue is that nn() does not return an iterable object. _nn() returns an iterable object but nothing is done with it. Either of the following should work though: def nn(): def _nn(): print 'inside' yield 1 print 'before' for i in _nn(): yield i print 'after' Or you could just return the iterable object that was returned by _nn(): def nn(): def _nn(): print 'inside' yield 1 print 'before' retval = _nn(): print 'after' return retval For clarification, using yeild creates a generator. That generator returns an iterable object. Nesting generators does not somehow magically throw the values up the stack. I made the same mistake when I first started messing with generators too. -Matt [EMAIL PROTECTED] wrote: > Hi, > > I might understand why this does not work, but I am not convinced it > should not - following: > > def nnn(): > print 'inside' > yield 1 > > def nn(): > def _nn(): > print 'inside' > yield 1 > > print 'before' > _nn() > print 'after' > > > for i in nnn(): > print i > > for i in nn(): > print i > > > > gives results: > > $ python f.py > inside > 1 > before > after > Traceback (most recent call last): > File "f.py", line 18, in ? > for i in nn(): > TypeError: iteration over non-sequence > > while I would expect: > $ python f.py > inside > 1 > before > inside > 1 > after > > Any insight? > > andy -- http://mail.python.org/mailman/listinfo/python-list
Re: remove a list from a list
> The solution so far is: > > for i in xrange(len(dirs), 0, -1): >if dirs[i-1].lower() in dirs_exclude: > del dirs[i-1] This won't affect much, but uses better style I think. Change: for i in xrange(len(dirs),0,-1): To: for i in reversed(xrange(len(dirs))): and then just use 'i' instead of 'i-1' -- http://mail.python.org/mailman/listinfo/python-list
Re: String formatters with variable argument length
> Could it be as I fear, that it is impossible? p'shaw, you underestimate the power of the Python... I think this is a poor solution (I would go with the solution in John Machin's second post) but here it is anyway since it does essentially what you asked for: [code] def print_data(fmtstr): data = (10,11,12,13) for i in xrange(len(data)): try: print fmtstr %data[:i+1] break except: pass [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: Mirror imaging binary numbers
Craig wrote: > I'm trying to switch binary numbers around so that the MSB becomes the > LSB etc. What do you mean 'binary numbers'? They are all binary. If you mean the int type, they are 32 bits long and there are 16 bits between the MSB and LSB (Most/Least Significant _Byte_). Do you want to swap the most significant word with the least significant word? Swap the most significant nibble with the least significant nibble in a Byte? Or do you want to completely reverse the bit order? To swap nibbles in a byte: reverseVal = (val & 0xf) << 4 | (val & 0xf0) >> 4 Basicly you are going to need to use the bit operators (|,&, << and >>) to get what you need. If you could be more specific perhaps I could be of more help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Multidimesional array(newbie)
Tartifola wrote: > Hi, > how can I sort an array like > > array([[5, 2], >[1, 3]]) > > along the first column to obtain > > array([[1, 3], >[5, 2]]) > i.e. keeping track of the ordered couples? > > Thanks, > A use a sort key: >>>from operators import getitem >>>a = [[5,2],[1,3]] >>>a [[5, 2], [1, 3]] >>>a.sort(key=lambda x:getitem(x,0)) >>>a [[1, 3], [5, 2]] -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: unbound method must be called with class instance 1st argument
> Can someone please explain why I get the following error: The following line: threading.Thread.__init__() Should be written as: threading.Thread.__init__(self) -- http://mail.python.org/mailman/listinfo/python-list
Re: list1.append(list2) returns None
Pyenos wrote: > def enlargetable(table,col): > table.append(col) # the code won't return sorted lists :-o > return_the_fucking_table_bitch=table # assign it to a new variable to > return it > return return_the_fucking_table_bitch # :-| Maybe you were just trying to be funny, but assiging the table to another variable before returning is not only unnecessary, it accomplishes nothing. The following will do exactly the same thing as the above: [code] def enlargetable(table,col): table.append(col) return table [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: A stupid question
[EMAIL PROTECTED] wrote: > Any other ideas? Well, you could always try downloading and installing python: http://www.python.org. It is completely free. It won't run anything in the task bar or add itself to the startup menu and it doesn't have ads... it just sits there waiting for you to use it. I would start with version 2.4, and if that doesn't work I would go to 2.3 then 2.5 then 2.2. Uninstall the last version before moving on to another. I do worry a little though because python dlls are named as Python.dll, so the dll in that error message could actually be from some third party. Anyway, there is no harm in installing Python. If it doesn't work it will uninstall cleanly. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use execfile with argument under windows
>
> error output
> IOError: [Errno 2] No such file or directory:"filename.exe -type png
> -source sourcearg -file filename.png"
Use 'os.system' not 'execfile'. 'execfile' is for executing other
python scripts, not arbitrary command line.
Try this:
import os
...
...
os.system("filename.exe -type png -source sourcearg -file
filename.png")
> try
> execfile("d:\pathto\filename.exe -type png -source sourcearg -file
> filename.png")
>
> error output
> IOError: [Errno 2] No such file or directory:"d:\pathto\filename.exe
> filename.exe -type png -source sourcearg -file filename.png"
be careful with your '\'s they tend to get interpreted as escape
characters. You can prefix the string with an 'r', double them up or
use forward slashes.
One of the following should work:
r"d:\pathto\filename.exe -type png -source sourcearg -file
filename.png"
"d:\\pathto\\filename.exe -type png -source sourcearg -file
filename.png"
"d:/pathto/filename.exe -type png -source sourcearg -file filename.png"
--
http://mail.python.org/mailman/listinfo/python-list
Re: C/C++, Perl, etc. to Python converter
I don't know of a converter, one may exist. I have seen similar requests though and will give you a similar response to what I have seen. A converter, if it exists, may be able to produce working code but _not_ readable code. Python is a language whose strength comes from, among other things, its readability and conventions. Learning python is best done by using the online documentation (http://docs.python.org/tut/tut.html) and reading existing code (take a look at the built in modules). My biggest fear of teaching someone to program by using a program to convert perl to python is that they will end up writing python that still looks like perl. I don't know if it helps, but I know others will give you similar advice. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: code optimization (calc PI)
Using the '+' operator for string concatonation can be slow, especially
when done many times in a loop.
>pi = pi + str("%04d" % int(e + d/a)) ## this should be fast?! I dont
The accepted solution would be to make pi an array and append to the
end...
pi = [] #create the array (empty)
...
...
pi.append(str("%04d"%int(e+d/a))) # append to it
And when it is time to print the results do the following:
print "".join(pi)
It may look strange, but it is a common Python idiom. You might also
look into an optimizer such as psycho: http://psyco.sourceforge.net/.
--
http://mail.python.org/mailman/listinfo/python-list
Re: code optimization (calc PI)
> If someone is really interested in speed optimization, I can publish my > PI-calc code. I wouldn't mind seeing it. Chances are you will get much better help if you post your code anyway. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine an object is a subclass of another
First you need to subclass the classes so that Dog actually is a subclass of Animal which is a subclass of thing... class Thing: pass class Animal(Thing): pass class Dog(Animal): pass class Weapon(Thing): pass class Gun(Weapon): pass Then you can use 'isinstance' >>>d = Dog() >>>isinstance(d,Thing) True >>>isinstance(d,Animal) True >>>isinstance(d,Weapon) False >>>isinstance(d,Gun) False -- http://mail.python.org/mailman/listinfo/python-list
Re: Get ClassID of different versions of program with same ProgID
Bummer you can't look into the registry. By convention the ProgID is named ... Also, usually there is a version independent ProgID that goes .. The version independent ProgID usually points to the newest version. It looks like that is what you are using. Many programs get away with not using those conventions, but I'm willing to bet that there is an 'AutoCAD.Application.14' and an 'AutoCAD.Application.??'. I don't know what will be there for 2004. Chances are that it is not '2004', but '15' (or something similar). So, you should be able to use those instead of the version independent one. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you htmlentities in Python
On Jun 4, 6:31 am, "js " <[EMAIL PROTECTED]> wrote:
> Hi list.
>
> If I'm not mistaken, in python, there's no standard library to convert
> html entities, like & or > into their applicable characters.
>
> htmlentitydefs provides maps that helps this conversion,
> but it's not a function so you have to write your own function
> make use of htmlentitydefs, probably using regex or something.
>
> To me this seemed odd because python is known as
> 'Batteries Included' language.
>
> So my questions are
> 1. Why doesn't python have/need entity encoding/decoding?
> 2. Is there any idiom to do entity encode/decode in python?
>
> Thank you in advance.
I think this is the standard idiom:
>>> import xml.sax.saxutils as saxutils
>>> saxutils.escape("&")
'&'
>>> saxutils.unescape(">")
'>'
>>> saxutils.unescape("A bunch of text with entities: & > <")
'A bunch of text with entities: & > <'
Notice there is an optional parameter (a dict) that can be used to
define additional entities as well.
Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: Sending cookies with python. When download with python
On Jun 5, 9:14 am, [EMAIL PROTECTED] wrote: > I need to download files off a password protected website. So if I try > to download files off the site with python I will be blocked. Is there > anyway to send cookies with python. So I will be authenticated. Yes. I haven't done it but I know you should be looking at urllib2 and cookielib. I'm sure you can find some examples online. Dive Into Python (google it) has some examples that may help you get started with more general purpose use of urllib2. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: which "GUI module" you suggest me to use?
> I know that WxPython work only under Windows Hmm, there seems to be some disparity between what you know and the truth... WxPython works everywhere (Windows, Linux, MacOS), and it works well. Also, it has web widgets that come standard (wx.html.HtmlWindow). Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Boost.Python participate in cyclic gc?
> The solution was to recognize when we where finished with it to set > self.over_there to None. To my knowledge python does not handle all cyclic gc anyway. Here is some information from the gc documentation: [doc] garbage A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). By default, this list contains only objects with __del__() methods.3.1Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesn't collect such cycles automatically because, in general, it isn't possible for Python to guess a safe order in which to run the __del__() methods. If you know a safe order, you can force the issue by examining the garbage list, and explicitly breaking cycles due to your objects within the list. Note that these objects are kept alive even so by virtue of being in the garbage list, so they should be removed from garbage too. For example, after breaking cycles, do del gc.garbage[:] to empty the list. It's generally better to avoid the issue by not creating cycles containing objects with __del__() methods, and garbage can be examined in that case to verify that no such cycles are being created. [/doc] So, do BoostFieldClass and Foo both implement __del__? Is there some way you can eliminate one of them? I can reproduce something similar with the code below, and I'm not using Boost.Python. [code] class Bar: def set_callback(self,cb): self.cb = cb def __del__(self): pass class Foo: def __init__(self): self.over_there = Bar() self.over_there.set_callback(self.boost_callback) def boost_callback(self): print "Boost callback" def __del__(self): pass if __name__ == "__main__": import gc f = Foo() del(f) gc.collect() print dir() print gc.garbage [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: copying generatrors
Why not just do this: >>> def foo(): ... yield 1 ... yield 2 ... yield 3 ... >>> f = foo() >>> g = foo() >>> f.next() 1 >>> f.next() 2 >>> f.next() 3 >>> g.next() 1 >>> g.next() 2 >>> g.next() 3 -- http://mail.python.org/mailman/listinfo/python-list
Re: running a random function
How are you making the list of functions? Something like this: [code] fs = [] for k,f in globals(): if callable(f): fs.append(f) [/code] Then to call a random one (assuming they all take no parameters): [code] import random random.choice(fs)() [/code] Or maybe you only have the name of the function, this should work: [code] globals()[name]() [/code] Does this help? I'm not really clear on what you are asking for. -- http://mail.python.org/mailman/listinfo/python-list
Re: Method much slower than function?
> The first time you read the file, it has to read it from disk. > The second time, it's probably just reading from the buffer > cache in RAM. I can verify this type of behavior when reading large files. Opening the file doesn't take long, but the first read will take a while (multiple seconds depending on the size of the file). When the file is opened a second time, the initial read takes significantly less time. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Making static dicts?
On Jun 18, 1:46 pm, Ognjen Bezanov <[EMAIL PROTECTED]> wrote:
> Hello!
>
> Just to ask, is it possible to make a static dictionary in python. So
> that the keys in the dictionary cannot be removed, changed or new ones
> added, but the value pairs can.
>
> Is this possible with python?
>
> thanks,
>
> Ognjen.
How much functionality do you need? Something like this might work
(though it could use better error messages.
[code]
class StaticDict:
def __init__(self,srcdict):
self._srcdict = srcdict
def __getitem__(self,idx):
return self._srcdict[idx]
[/code]
Use it like this:
>>> sd = StaticDict({'a':'b'})
>>> sd['a']
'b'
>>> sd['b']
Traceback (most recent call last):
File "", line 1, in ?
File "", line 5, in __getitem__
KeyError: 'b'
>>> sd['a'] = "hello"
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: StaticDict instance has no attribute '__setitem__'
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: need help with re module
On Jun 20, 9:58 am, linuxprog <[EMAIL PROTECTED]> wrote:
> hello
>
> i have that string "helloworldok" and i want to
> extract all the text , without html tags , the result should be some
> thing like that : helloworldok
>
> i have tried that :
>
> from re import findall
>
> chaine = """helloworldok"""
>
> print findall('[a-zA-z][^(<.*>)].+?[a-zA-Z]',chaine)
>
>>>> ['html', 'hell', 'worl', 'anyt', 'ag>o']
>
> the result is not correct ! what would be the correct regex to use ?
This: [^(<.*>)] is a set that contains everything but the characters
"(","<",".","*",">" and ")". It most certainly doesn't do what you
want it to. Is it absolutely necessary that you use a regular
expression? There are a few HTML parsing libraries out there. The
easiest approach using re might be to do a search and replace on all
tags. Just replace the tags with nothing.
Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: need help with re module
Here is an example:
>>> s = "Helloworldok"
>>> matchtags = re.compile(r"<[^>]+>")
>>> matchtags.findall(s)
['', '', '']
>>> matchtags.sub('',s)
'Helloworldok'
I probably shouldn't have shown you that. It may not work for all
HTML, and you should probably be looking at something like
BeautifulSoup.
Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: try/except with multiple files
It depends, what are you going to do if there is an exception? If you are just going to exit the program, then that works fine. If you are going to just skip that file, then the above wont work. If you are going to return to some other state in your program, but abort the file opening, you might want to close any files that were opened. The closing can be taken care if in the except block, but you will have to know which ones opened successfully. In general I would do something like this for multiple files: [code] filenames = ["fname1","fname2","fname3"] for fn in filenames: try: f = open(fn) except IOError: # handle exception #do something with f [/code] But, that might not work for you if the files aren't homogeneous (each have similar contents). If the files have distinctly different purposes, I would just wrap them each in their own try/except block. I rambled a bit there, but I hope it helps. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: howto run a function w/o text output?
On Jun 22, 9:56 am, dmitrey <[EMAIL PROTECTED]> wrote: > hi all, > I have a > y = some_func(args) > statement, and the some_func() produces lots of text output. Can I > somehow to suppress the one? > Thx in advance, D. [code] import sys import os sys.stdout = open(os.devnull,"w") [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: server wide variables
On Jun 25, 8:29 am, Jay Sonmez <[EMAIL PROTECTED]> wrote: > I want to be able to save some server variables as long as Apache runs > on the server (mod_python). > > How is that possible in Python? I don't have any experience with mod_python, but I'm assuming all of the standard python modules are available. You might check out http://docs.python.org/lib/module-shelve.html. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem mixing gettext and properties
On Jun 26, 10:52 am, André <[EMAIL PROTECTED]> wrote:
> I've encountered a problem using gettext with properties while using a
> Python interpreter.
>
> Here's a simple program that illustrate the problem.
> ==
> # i18n_test.py: test of gettext & properties
>
> import gettext
>
> fr = gettext.translation('i18n_test', './translations',
> languages=['fr'])
> fr.install()
>
> help = _("Help me!")
>
> class Test_i18n(object):
> def get(self):
> __help = _("HELP!")
> return __help
> help_prop = property(get, None, None, 'help')
>
> test = Test_i18n()
>
> print help
> print test.help_prop
> end of file
>
> To run the above program, you need to have the strings translated and
> the proper ".po" and ".mo" files created. (for those interested, I
> can send the whole lot in a zip file)
>
> If I run the program as is, the output is:
> Aidez-moi!
> AIDE!!!
>
> Ok, let's try with the Python interpreter:
>
> ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on
> Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.>>>
> import i18n_test
>
> Aidez-moi!
> AIDE!!!
>
> # No surprise there so far.
>
> >>> print i18n_test.help
> Aidez-moi!
> >>> print i18n_test.test.help_prop
> AIDE!!!
> >>> i18n_test.help
>
> 'Aidez-moi!'
>
> # all of the above are as expected; now for the first surprise
>
> >>> i18n_test.test.help_prop
>
> Traceback (most recent call last):
> File "", line 1, in ?
> File "i18n_test.py", line 12, in get
> __help = _("HELP!")
> TypeError: 'str' object is not callable
>
> # and a second surprise where we try to repeat something that used to
> work
>
> >>> print i18n_test.test.help_prop
>
> Traceback (most recent call last):
> File "", line 1, in ?
> File "i18n_test.py", line 12, in get
> __help = _("HELP!")
> TypeError: 'str' object is not callable
>
> #=
>
> Dare I say: "Help!" I really need to use the above at the
> interpreter prompt.
>
> André
In the interpreter "_" is used to store the return value of the last
statement executed. So when this line is run:
>>> i18n_test.help
"_" is set to 'Aidez-moi!'.
A possible fix, which I have not tested in your context, would be to
explicitly set _ to _ after your module is loaded.
So, try this:
>>> import i18n_test
>>> _ = i18n_test._
... The rest of your code here
I don't know for sure that this will work. From what I have tried
though, assigning to _ seems to disable that feature of the
interpreter.
Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: noob question How do I run a Python script.
> I installed python, run the interpreter and the script... Are you trying to run the script from the interpreter? You _can_ run scripts from the interpreter, but it isn't as simple as typing the name of the script. To me, that is what it sounds like you are trying to do. I don't know what environment you are using, but at the command line (terminal) you should just type the following to run the script: python cleanmbox.py Actually, if you are using *nix use chmod +x chanmbox.py to tell the os it is executable, and then just run "cleanbox.py". If you are using windows, then you don't even have to do that, just double click on it. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a Python Application
On Jul 3, 2:27 pm, [EMAIL PROTECTED] wrote: > Hi, > > I packaged up an application I am developing into an executable. In > the application, it has user configurable options. I would like a way > to restart the application so that the new options the user chooses > can be applied. Firefox can restart itself. Does anyone know how to > accomplish this in Python? > > Here is what I tried: > > > > exePath = os.path.join(os.getcwd(), 'myprogram.exe') > subprocess.Popen(exePath) > sys.exit() > > > > This didn't work. It closed the program, but another instance did not > appear. > > Tips would be appreciated. > > Mike You could package your program into a function or class and just restart that. [code] # global flag for restart. do_restart = False def main(args=None): # program code # set do_restart and return to restart if __name__ == "__main__": retval = main() while do_restart: retval = main() sys.exit(retval) [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: Expandable 2D Dictionaries?
I'm not sure I completely understand what you want, but if you are using Python2.5 defaultdict might be useful. Below is some example code using defaultdict. [code] from collections import defaultdict myvar = defaultdict(dict) myvar["cat"]["paw"] = "SomeString" myvar["dog"]["tail"] = "wags" myvar["cat"]["tongue"] = "sand-paper" myvar["mouse"]["likes"] = "cheese" [/code] The documentation can do a better job of explaining how this works than I can: http://docs.python.org/lib/defaultdict-objects.html -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a Python Application
> Actually I am using wxPython for a GUI front-end. Thus, it is already
> in a class. I am not sure how to apply your idea to a program that is
> already running in an infinite event loop.
I don't know wxPython, but I was able to grab an example program and
adapt it to do what I think you are asking for.
Something like this:
[code]
#! /usr/bin/env python
from wxPython import wx
ID_EXIT = 101
ID_RST = 102
class MyFrame(wx.wxFrame):
def __init__(self, parent, ID, title):
wx.wxFrame.__init__(self, parent, ID, title,
wx.wxDefaultPosition, wx.wxSize(200, 150))
self.CreateStatusBar()
self.SetStatusText("This is the statusbar")
menu = wx.wxMenu()
menu.Append(ID_EXIT, "E&xit", "Terminate the program")
menu.Append(ID_RST, "&Restart", "Restart the program")
menuBar = wx.wxMenuBar()
menuBar.Append(menu, "&File");
self.SetMenuBar(menuBar)
wx.EVT_MENU(self, ID_EXIT, self.TimeToQuit)
wx.EVT_MENU(self, ID_RST, self.TimeToRestart)
def TimeToQuit(self, e):
self.Close(wx.true)
def TimeToRestart(self, e):
global restart
restart = True
self.TimeToQuit(e)
class MyApp(wx.wxApp):
def OnInit(self):
global restart
restart = False
frame = MyFrame(wx.NULL, -1, "Hello from wxPython")
frame.Show(wx.true)
self.SetTopWindow(frame)
return wx.true
if __name__ == "__main__":
MyApp(0).MainLoop()
while restart:
MyApp(0).MainLoop()
[/code]
--
http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
> Should SafeConfigParser.set() be escaping automatically? It seems like that would be a nice feature. However, may I offer up that if you are setting an option and then later on getting that value back in the same program, you probably should have used some other storage mechanism in the first place. That is, you shouldn't store values needed during the runtime of your program in a ConfigParser instance. As far as I can tell, these are the valid use cases for ConfigParser: 1. Use ConfigParser to read values from an config file - This implies .read() followed by .get()s 2. Use ConfigParser to create and write a config file - This implies .set()s followed by .write() 3. Use ConfigParser to read, modify and write a config file. - This implies .read() followed by .get()s followed by .set()s followed by .write() None of the above use cases involve calling .get() after a .set(). Perhaps I am missing a use case though. While I think you have technically pointed out a potential bug, I'm not sure why it matters. Such a bug only comes about for (IMHO) flawed use cases. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
> I agree, but that was a trivial example to demonstrate the problem.
> Writing the file out to disk writes it exactly as set(), causing a get()
> to fail just the same later.
No... The above statement is not true.
The following code:
[code]
from ConfigParser import *
import sys
cp = SafeConfigParser()
cp.add_section("sect")
cp.set("sect","opt","hello%world")
cp.write(sys.stdout)
[/code]
Produces this output:
[sect]
opt = hello%world
The write method never calls get. However, when you read the file that
was output by the above code using .get(...) will raise an error. You
can avoid that error by setting the optional 'raw' parameter to True.
--
http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
> This not only happens when get() after a set(), but with all the use cases
> above. An intervening write()/read() does not change things.
> But I'm not sure it is a bug really. If all % were escaped automatically,
> there is no way to write a templatized value. Maybe SafeConfigParser.set
> should grow an escape argument, controlling whether one wants the value
> escaped or not. For compatibility reasons should default to False, for
> usability reasons should default to True.
The exception is only raised when get is called, the "raw" paremeter
for get(...) is set to False (default) and the string value for that
parameter contains a single "%". None of the cases I stated above call
get() after calling set(). So, the exception will never be raised
because of something the user set. It will be raised if the input file
happens to have a single "%" character in one of the parameter values,
but that content could have been user generated, and it is not
reasonable to assume that fixing the set() method would have prevented
it.
Adding an escape parameter to set will not be used properly. Its
purpose would be to escape lone "%" characters, but if users are
wanting to use the substitution they would always keep escaping off.
It wouldn't allow them catch situations like this:
cp.set("sect","param","this is my value %(key)s and here is a lone %
and here is another %(sub)s", escape=False)
The solution I would propose is to raise an exception on set() if the
value contains a single "%" not followed by a key name enclosed in
parens followed by "s". That puts the burden of escaping on the user,
before passing it to set.
--
http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
> This not only happens when get() after a set(), but with all the use cases
> above. An intervening write()/read() does not change things.
> But I'm not sure it is a bug really. If all % were escaped automatically,
> there is no way to write a templatized value. Maybe SafeConfigParser.set
> should grow an escape argument, controlling whether one wants the value
> escaped or not. For compatibility reasons should default to False, for
> usability reasons should default to True.
The exception is only raised when get is called, the "raw" paremeter
for get(...) is set to False (default) and the string value for that
parameter contains a single "%". None of the cases I stated above call
get() after calling set(). So, the exception will never be raised
because of something the user set. It will be raised if the input file
happens to have a single "%" character in one of the parameter values,
but that content could have been user generated, and it is not
reasonable to assume that fixing the set() method would have prevented
it.
Adding an escape parameter to set will not be used properly. Its
purpose would be to escape lone "%" characters, but if users are
wanting to use the substitution they would always keep escaping off.
It wouldn't allow them catch situations like this:
cp.set("sect","param","this is my value %(key)s and here is a lone %
and here is another %(sub)s", escape=False)
The solution I would propose is to raise an exception on set() if the
value contains a single "%" not followed by a key name enclosed in
parens followed by "s". That puts the burden of escaping on the user,
before passing it to set.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to convert a byte of integer into a list
On Jul 12, 3:34 pm, Godzilla <[EMAIL PROTECTED]> wrote: > Hello, > > I'm trying to find a way to convert an integer (8-bits long for > starters) and converting them to a list, e.g.: > > num = 255 > numList = [1,1,1,1,1,1,1,1] > > with the first element of the list being the least significant, so > that i can keep appending to that list without having to worry about > the size of the integer. I need to do this because some of the > function call can return a 2 lots of 32-bit numbers. I have to find a > way to transport this in a list... or is there a better way? num = 255 numlist = [num >> i & 1 for i in range(8)] -- http://mail.python.org/mailman/listinfo/python-list
Re: Break up list into groups
This is a perfect place for a generator: seq = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15] def gengroups(seq): group = [] for val in seq: if val & 0x80 and group: yield group group = [] group.append(val) yield group if __name__ == "__main__": print list(gengroups(seq)) The above assumes that the first value in the input sequence will have 0x80 set. Your implementation seems to makes the same assumption though. Also, just a note... if len(local) > 0: ... is better written if local: ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Semantics of file.close()
> How do I ensure that the close() methods in my finally clause do not > throw an exception? You have no choice. If close is going to fail, it will fail. Fortunately you can catch the exception and continue on. try: try: file1.write(somestuff) finally: file1.close() except IOError: pass or you could wrap it in the inner scope: try: file1.write(somestuff) finally: try: file1.close() except IOError: pass This doesn't prevent the exception from happening, but it prevents the user for seeing it. Also, you don't need to use semicolons in python. -- http://mail.python.org/mailman/listinfo/python-list
Re: In a dynamic language, why % operator asks user for type info?
I don't have a good answer for you, but you might be interested to read this: http://python.org/dev/peps/pep-3101/. Which according to a recent blog post by BDFL is going to be how string formatting is done in Python3000. The character doesn't specify the type to expect, but the formatting function. So, %s calls a string formatter, %r calls repr and %x calls a hex formatter. The there may be multiple formatters that produce different results for given types. An integer can use %d,%e,%f,%s,%x or %r, and they all produce slightly different results. Also, the formatters take parameters. Such as "%+010.5f"%(1.23) which produces "+001.23000". -- http://mail.python.org/mailman/listinfo/python-list
Re: Break up list into groups
I did some more experimenting and came up with the code below. It shows several methods. When run, the script tests the robustness of each method (roughly), and profiles it using timeit. The results from running on my laptop are shown below the code. seqs = [# Original: [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15], # Single entry: [0xF0, 1, 2, 3], # empty [], # No values with 0x80 set [1, 2, 3, 14, 15], # Does not start with a value that has 0x80 set [1, 2, 3, 14, 15, 0xF0, 1, 2, 3]] expected = [# Original: [[0xF0, 1, 2, 3], [0xF0, 4, 5, 6], [0xF1, 7, 8], [0xF2, 9, 10, 11, 12, 13], [0xF0, 14], [0xF1, 15]], # Single entry: [[0xF0, 1, 2, 3]], # empty [], # No values with 0x80 set [], # Does not start with a value that has 0x80 set [[0xF0, 1, 2, 3]]] def gengroups0(seq): group = None for val in seq: if val & 0x80: if group: yield group group = [] try: group.append(val) except AttributeError: pass if group: yield group def getgroups0(seq): groups = [] group = None for val in seq: if val & 0x80: if group: groups.append(group) group = [] try: group.append(val) except AttributeError: pass if group: groups.append(group) return groups def gengroups1(seq): idxs = [i for i,v in enumerate(seq) if v&0x80] for i,j in zip(idxs,idxs[1:]+[None]): yield seq[i:j] def getgroups1(seq): idxs = [i for i,v in enumerate(seq) if v&0x80] return [seq[i:j] for i,j in zip(idxs,idxs[1:]+[None])] # Similar to the partition method on strings def partition(seq,f=None): if f is None: f = lambda x:x for i,v in enumerate(seq): if f(v): return seq[:i],[seq[i]],seq[i+1:] return seq,[],[] def rpartition(seq, f=None): if f is None: f = lambda x:x for i,v in zip(range(len(seq)-1,-1,-1),seq[::-1]): if f(v): return seq[:i],[seq[i]],seq[i+1:] return ([],[],seq) def gengroups2(seq): while seq: seq, key, val = rpartition(seq, lambda x: x&0x80) if key and val: yield key+val def getgroups2(seq): groups = [] while seq: seq, key, val = rpartition(seq, lambda x: x&0x80) if key and val: groups.append(key+val) return groups def getgroups3(seq): groups = [] for i in seq: if 0x80 & i: groups.append([i]) else: groups[-1].append(i) return [x for x in groups if x] seq = seqs[0] if __name__ == "__main__": from timeit import Timer import __main__ for i in range(4): fname = "getgroups"+str(i) f = getattr(__main__,fname) print fname for i,(s,e) in enumerate(zip(seqs,expected)): print "test %d:"%i, try: if f(s) == e: print "pass" else: print "fail" except: print "error" t = Timer(fname+'(seq)', 'from __main__ import seq,'+fname) print "%.2f usec/pass" % (100 * t.timeit(number=10)/ 10) print Output from running the above: getgroups0 test 0: pass test 1: pass test 2: pass test 3: pass test 4: pass 14.85 usec/pass getgroups1 test 0: pass test 1: pass test 2: pass test 3: pass test 4: pass 13.81 usec/pass getgroups2 test 0: fail test 1: pass test 2: pass test 3: pass test 4: pass 56.38 usec/pass getgroups3 test 0: pass test 1: pass test 2: pass test 3: error test 4: error 16.23 usec/pass `getgropus2' fails test 0 because it produces a reversed list. That can easily be fixed by re-reversing the output before returning. But, since it is by far the slowest method, I didn't bother. `getgroups3' is a method I got from another post in this thread, just for comparison. >From my benchmarks it looks like getgroups1 is the winner. I didn't scour the thread to test all the methods however. -- http://mail.python.org/mailman/listinfo/python-list
Re: Break up list into groups
> A little renaming of variables helps it be a bit more elegant I think ... > > def getgroups8(seq): > groups = [] > iseq = iter(xrange(len(seq))) > for start in iseq: > if seq[start] & 0x80: > for stop in iseq: > if seq[stop] & 0x80: > groups.append(seq[start:stop]) > start = stop > groups.append(seq[start:]) > return groups Excellent work! One more modification and I get below 10us/pass: def getgroups(seq): groups = [] push = groups.append iseq = iter(xrange(len(seq))) for start in iseq: if seq[start] & 0x80: for stop in iseq: if seq[stop] & 0x80: push(seq[start:stop]) start = stop push(seq[start:]) return groups -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it possible to merge xrange and slice?
> Which problems am I overlooking that prevent this? 1. Generators and slices serve two distinctly different tasks. 2. They may have the similar interfaces, but are implemented differently. Each optimized for its specific task. You are essentially asking "Why not do it?", to which I respond "Why do it?". How does this consolidation of features improve Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python user group in Portland, OR?
Python.org lists PORPIG (PORtland Python Intrest Group) but the site that it points to no longer seems to represent that. Also, when I looked into going to a meeting a while back, the last one listed was some time in 2004. I will put this out there though, if someone wants to start a PIG back up for Portland I would certainly be interested. I am at least one Python developer living in the Portland area. The web contains evidence of others as well. In general there is a fairly large software development presence in Portland, especially around Open Source. -- http://mail.python.org/mailman/listinfo/python-list
Re: Time functions
On May 2, 10:21 am, HMS Surprise <[EMAIL PROTECTED]> wrote:
> On May 2, 12:03 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > In <[EMAIL PROTECTED]>, HMS Surprise
> > wrote:
>
> > > I wish to generate a datetime string that has the following format.
> > > '05/02/2007 12:46'. The leading zeros are required.
>
> > > I found '14.2 time' in the library reference and have pulled in
> > > localtime. Are there any formatting functions available or do I need
> > > to make my own? Perhaps there is something similar to C's printf
> > > formatting.
>
> > You mean like `time.strftime()`!? :-)
>
> > Ciao,
> > Marc 'BlackJack' Rintsch
>
> Thanks for posting.
>
> I think I have an import misconception.
>
> I use
> import from time localtime, strftime
> t = strftime('%m/%d/%Y %H:%M', localtime())
>
> This works. How would one use it with the module name pre-pended?
>
> thanx,
> jvh
I would think that what you have written there shouldn't work at
all...
it would need to be:
[code]
from time import localtime, strftime
[/code]
to use the prepended module name just do this instead:
[code]
import time
t = time.strftime('%m/%d/%Y %H:%M', time.localtime())
[/code]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Slicing Arrays in this way
On May 2, 3:03 pm, Tobiah <[EMAIL PROTECTED]> wrote: > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > > -- > Posted via a free Usenet account fromhttp://www.teranews.com >>> seq = range(1,11) >>> seq [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> zip( seq[0::2],seq[1::2] ) [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] if you _really_ need lists then... >>> map(list, zip( seq[0::2],seq[1::2] )) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to replace the last (and only last) character in a string?
On May 3, 7:44 am, Johny <[EMAIL PROTECTED]> wrote: > On May 3, 4:37 pm, [EMAIL PROTECTED] wrote: > > > > > On May 3, 9:27 am, Johny <[EMAIL PROTECTED]> wrote: > > > > Let's suppose > > > s='12345 4343 454' > > > How can I replace the last '4' character? > > > I tried > > > string.replace(s,s[len(s)-1],'r') > > > where 'r' should replace the last '4'. > > > But it doesn't work. > > > Can anyone explain why? > > > > Thanks > > > L. > > > I think the reason it's not working is because you're doing it kind of > > backwards. For one thing, the "string" module is deprecated. I would > > do it like this: > > > s = s.replace(s[len(s)-1], 'r') > > > Although that is kind of hard to read. But it works. > > > Mike > > Mike it does NOT work for me.>>> s.replace(s[len(s)-1], 'r') > > '123r5 r3r3 r5r' > > I need only the last character to be replaced Its not working because str.replace: [docstring] Help on method_descriptor: replace(...) S.replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. [/docstring] Notice the "all occurrences of substring" part. Strings are immutable, so there isn't really any replace, either way you are going to be creating a new string. So the best way to do what (I think) you want to do is this... [code] >>> s = '12345 4343 454' >>> s = s[:-1]+'r' >>> s '12345 4343 45r' [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: Real Time Battle and Python
On May 3, 5:20 am, hg <[EMAIL PROTECTED]> wrote: > Hi, > > I have started to work on a python-based robot, and am interested in your > feedback: > > http://realtimebattle.sourceforge.net/www.snakecard.com/rtb > > hg This is not necessarily a response to your effort, but just a note (rant) about realtimebattle. It reminds me more of homework in 300 and 400 level college engineering classes than a game. Based upon my previous effort and realizations, I found realtimebattle coding to be, from a programming perspective, an exercise in protocol implementation first. Once the protocol work is done you need to implement control algorithms for movement and enemy tracking. Think PID algorithms (Proportional, Integral and Differential). Only when the protocol and control portions are done can you focus on strategy and play the game. You should also note, however, that the first two tasks are quite daunting. And the second is difficult to get right. I found the whole process to be very tiring and not very rewarding. I don't mean to discourage you, I just think it would be more fun to write my own game than to 'play' that one. A better game, from a programming perspective, would be "discretetimebattle". Where each player controls their robot with second order parameters (velocity not force), the world has no third order effects (friction) and the time is discrete. Discrete time meaneing that the protocol updates every player at regular intervals with the same information and, in terms of the simulation, each update represents a set time delta. I would be interested to know if anybody else has played, or tried to play, realtimebattle and has similar sentiments. I do wish you luck though. If you get a robot working you are a far more dedicated and patient individual than me. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: cannot import name .....
I do see one problem there...
if __name__ == 'main':
t = nBaseTest('nBaseTest')
t.logon()
That should be:
if __name__ == "__main__":
t = nBaseTest('nBaseTest')
t.logon()
It should be like that in both files.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Trying to choose between python and java
> #3 Is there any equivalent to jfreechart and jfreereport > (http://www.jfree.orgfor details) in python. I haven't used either extensively but you might check out ReportLab for report generation (http://www.reportlab.org). And MatPlotLib for creating plots, charts and graphs (http://matplotlib.sourceforge.net). There may be alternatives available. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to choose between python and java
> I tend to use the shebang #!/usr/bin/env python in my scripts so far > but I imagine that having that would not work on say windows. Or is > there some kind of file extension association for people running > windows instead of the shebang? The shebang is ignored in Windows (as far as I know). There is are .py, .pyc, .pyo and .pyw associations added to the registry when you install Python on a Windows machine. They can be executed like any other program. > I saw on the python site a slide from 1999 that said that python was > slower then java but faster to develop with is python still slower > then java? I don't have any numbers, but yes it probably is a bit slower for some tasks. Especially for hardcore number crunching. Of course, you can always rewrite the slow bits in C and get a speedup. Also, there are optimizers that are supposed to work pretty well. In the end though, Python is fast enough for most tasks. For very heavy computation I wouldn't use Java either. The interpreter does seem to start much quicker than the JVM. Also, I'm sure it has been mentioned, but you might checkout Jython, which is essentially python written in Java. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Declaring variables
On May 16, 9:57 am, HMS Surprise <[EMAIL PROTECTED]> wrote: > I looked in the language but did not find a switch for requiring > variables to be declared before use. > > Is such an option available? > > Thanks, > > jvh You do have to declare a variable before use. You do so by assigning it a value. You can't use a variable before it has been assigned. In some ways this is less ambiguous than even C where you can declare a variable without assigning a value. Also note that this caries the type information, since the variable is of whatever type was assigned to it. The only thing it doesn't do is give a unique flag that says "hey this is where I'm declared", although I suppose you could do that with a comment. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Joining Lists
One: Not that I know of
Two: You could use list comprehension...
--- CODE --
import os
import glob
patterns = ('.\\t*.py', '.\\*.c??', '.\\*.txt')
filenames = [glob.glob(pat) for pat in patterns]
# Or as a one liner...
filenames = [glob.glob(pat) for pat in ('.\\t*.py', '.\\*.c??', '.\
\*.txt')]
# Also, I don't think specifying the current directory is necessary.
So this should also work:
filenames = [glob.glob(pat) for pat in ('t*.py', '*.c??', '*.txt')]
--
http://mail.python.org/mailman/listinfo/python-list
Re: A newbie question
How about this: [code] def __add__(self,x): return Cc14(self.r+x.r, self.i+x.i) [/code] However... Are you aware that Python has built in support for complex numbers already? >>> x = 4+5j >>> y = 4+5j >>> x+y (8+10j) >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Create an XML document
> How do I get Python to put values into the elements by tag name?
The same way you create put in new elements. Only, you use
'doc.createTextNode' instead of 'doc.createElement' to create it.
from xml.dom.minidom import Document
doc = Document()
zappt = doc.createElement('zAppointments')
zappt.setAttribute('reminder', '15')
doc.appendChild(zappt)
appt = doc.createElement('appointment')
zappt.appendChild(appt)
begin = doc.createElement('begin')
begincont = doc.createTextElement('1179775800')
begin.appendChild(begincont)
appt.appendChild(begin)
duration = doc.createElement('duration')
durationcont = doc.createTextElement('1800')
duration.appendChild(durationcont)
appt.appendChild(duration)
f = file(r'path\to\file.xml', 'w')
f.write(doc.toprettyxml(indent=''))
f.close()
--
http://mail.python.org/mailman/listinfo/python-list
Re: No file from stdin
On May 24, 9:48 am, Tartifola <[EMAIL PROTECTED]> wrote:
> Hi,
> suppose a script of python is waiting for a file from the stdin and none
> is given. How can I make the script to stop and, for example, print an
> error message?
>
> Sorry for the n00b question and thanks
I'm not exactly sure what you mean. This assumes that you intended the
contents of the file be piped in from the command line.
[code]
import sys
if sys.stdin.isatty():
print >>sys.stderr, "expected input from stdin"
sys.exit(1)
sys.stdout.write(sys.stdin.read())
[/code]
If you simply want a prompt "Enter a filename:", followed by an error
if it is not a valid file, I would use something like this:
[code]
import sys
filename = raw_input("Enter a filename:")
try:
f = open(filename)
except IOError,e:
print >>sys.stderr, e.strerror, e.filename
sys.exit(e.errno)
#do stuff with f
[/code]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Large Amount of Data
On May 25, 10:50 am, "Jack" <[EMAIL PROTECTED]> wrote: > I need to process large amount of data. The data structure fits well > in a dictionary but the amount is large - close to or more than the size > of physical memory. I wonder what will happen if I try to load the data > into a dictionary. Will Python use swap memory or will it fail? > > Thanks. The OS will take care of memory swapping. It might get slow, but I don't think it should fail. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Rats! vararg assignments don't work
Your attemtp: [code] first, rest = arglist[0], arglist[1:] [/code] Is the most obvious and probably the most accepted way to do what you are looking for. As for adding the fucntionality you first suggested, it isn't likely to be implemented. The first step would be to write a PEP though. Remember, in Python "there is only one way to do it". So, unless you can come up with a valid use case where that syntax allows you to do something that wasn't possible before, I wouldn't count on getting much support. -- http://mail.python.org/mailman/listinfo/python-list
Re: replace the base class
This is a rather simplistic example, but you may be able to use a mixin class to achieve what you need. The idea is that you write a class that overrides only what is needed to add the new functionality. For you it would be Color. [code] class Graph(object): def _foo(self): print "Graph._foo" class Color(object): def _foo(self): print "Color._foo" class Circle(Graph): def bar(self): self._foo() class ColorCircle(Color,Circle): # the order of parent classes is important pass if __name__ == "__main__": c1 = Circle() c2 = ColorCircle() c1.bar() #prints: Graph._foo c2.bar() #pritns: Color._foo [/code] You might not have to do anything already. Try this and see if it works: [code] ColorCircle(ColorGraph,Circle): pass [/code] Note that you will probably have to create an __init__ method, and explicitly call the __init__ methods for the base classes. If the __init__ for Circle ends up calling the __init__ method from Graph, you may have issues. That is why the Color mixin that I created inherited from object not Graph. It helps to avoid clashing __init__ methods. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: (sort of) deterministic timing in Python
> Do you see the difference? I get a true fixed interval from the first, > including the time to accomplish the event task(s). In the second case, > the sleep just gets tacked on at the end of the events, not very > deterministic (timing-wise). Check out the sched (scheduler) module http://docs.python.org/lib/module-sched.html. Here is an example that shows how to implement a loop (modified from the documentation): (warning, this will run forever) [code] import sched, time s=sched.scheduler(time.time, time.sleep) def print_time(): s.enter(1,1, print_time, ()) print "From print_time", time.time() def print_some_times(): print time.time() s.enter(5, 1, print_time, ()) s.run() if __name__ == "__main__": print_some_times() [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: convert non-delimited to delimited
On Aug 27, 10:59 am, RyanL <[EMAIL PROTECTED]> wrote: > I'm a newbie! I have a non-delimited data file that I'd like to > convert to delimited. > > Example... > Line in non-delimited file: > 01397256359210100534+42050-102800FM-15+1198KAIA > > Should be: > 0139,725635,9,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA > > What is the best way to go about this? I've looked all over for > examples, help, suggestions, but have not found much. CSV module > doesn't seem to do exactly what I want. Maybe I'm just missing > something or not using the correct terminology in my searches. Any > assistance is greatly appreaciated! Using Python 2.4 I don't think you are going to find anything that will just do this for you. You are going to have read the file, figure out where to split the string, and reprint it delimited with commas. As for suggesting code... I can't tell how you actually want to delimit the stuff from the above example? Are the fields always a fixed number of characters? If they aren't then is there some other method for determining how many characters to group into a field? From the looks of it you could split that string any way you want and get something that looks right, but isn't. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way of reading a textfile line by line without throwing an exception
> fp=open(filename, 'r') > for line in fp: > # do something with line > > fp.close() Or, if you are using Python 2.5+, you can use the file context via the `with' statement. [code] from __future__ import with_statement # this line won't be needed in Python 2.6+ with open(filename, 'r') as fp: for line in fp: # do something with line [/code] This basicly just closes the file automatically (even if there is an exception) when the context (part indented under `with') is exited. This is a new feature, but probably the most pythonic way of doing it. That will be especially true in the future. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Haskell like (c:cs) syntax
> Is there a pattern matching construct in Python like (head : tail), meaning > 'head' matches the first element of a list and 'tail' matches the rest? I > could not find this in the Python documentation. Not really, but you could do something like this: [code] def foo(head, *tail): #do stuff with head and tail foo(*seq) [/code] Also, Python 3.0 will have `Extended Iterable Unpacking' http://www.python.org/dev/peps/pep-3132/ This isn't quite the same as Haskell's type matching, but would enable similar behavior in some cases. example: [code] head, *tail = seq [/code] Which would assign the first element of seq to head, and the remainder to tail. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Registering a python function in C
On Aug 30, 2:21 pm, fernando <[EMAIL PROTECTED]> wrote:
> Could someone post an example on how to register a python function as
> a callback in a C function? It expects a pointer to PyObject... how do
> I expose that? Basically, the signature of the function is
> foo(PyObject* obj), where obj is the callback function... It's not
> exactly extending or embedding, I've looked at those examples but they
> don't really show how to do this...
>
> Thanks for the help!
It most definitely is extending or embedding, it just doesn't follow
the examples provided. I can't be too specific because I don't know
what your environment is like. As in, have you already initialized
python and all of that? Do you have access to _any_ PyObject*
variables?
Here is something that _might_ help (not tested):
[code]
PyObject* mod;
PyObject* func;
mod = PyImport_ImportModule("mymodule");
func = PyObject_GetAttrString( mod, "myfunc") ;
foo(func);
[/code]
It might be useful to look at the "Python/C API Reference Manual", not
just the extending and embedding stuff.
http://docs.python.org/api/api.html
Matt
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python is overtaking Perl
> So I think we can at least say from the chart that searches combining > the terms 'python' and 'programming' have been falling, by some > unquantifiable amount (it don't _look_ like much!?), relative to the > number of total searches. I think it is the search volume relative to the total number of searches. So, all the decline means is that the number of searches for "Python programming" releative to all searches done is declining. For example, there is a larger number of people searching for things like "Britney Spears", "Paris Hilton" and "pr0n" than there are for Python. It is simply a sign that Google is becoming more popular with the mainstream user, not python, ruby or even perl becoming less popular. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing zipfile (new style class)
> import zipfile > class walkZip(zipfile): > pass > > if __name__ == "__main__": > print "Hello World" `zipfile' is the name of the module, not a class. What you probably want is this: [code] import zipfile class WalkZip(zipfile.ZipFile): pass if __name__ == "__main__": print "hello world" [/code] Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about PEP 8
> will Py3K change the standard library names in order to follow PEP 8?) Just continue down the list of PEPs and you will find the answer: http://www.python.org/dev/peps/pep-3108/#modules-to-rename This covers built-in modules. It doesn't cover 3rd party modules, like wx. Most likely you will still see pep8 violations in non-standard modules. As for following or not following pep8 in conjunction with 3rd party modules. Just make your code look nice. Don't go out of your way to follow pep8 if it means that there will be a mix of styles that will be confusing. If you are overloading a class that is part of wx I would use the same style that wx uses. The reasoning being that people who might use that class would probably see it as just another wx class, and expect it to look and behave a certain way. Don't dissapoint them. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Is every number in a list in a range?
On Mar 5, 11:03 am, "Steven W. Orr" <[EMAIL PROTECTED]> wrote: > I have a list ll of intergers. I want to see if each number in ll is > within the range of 0..maxnum > > I can write it but I was wondering if there's a better way to do it? > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > happened but none stranger than this. Does your driver's license say Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net I would probably do something using max and min functions like this: seq = [...] # your list if min(seq) >= 0 && max(seq) <= MAXNUM: do stuff -- http://mail.python.org/mailman/listinfo/python-list
Re: Is every number in a list in a range?
On Mar 5, 1:34 pm, "Matimus" <[EMAIL PROTECTED]> wrote: > On Mar 5, 11:03 am, "Steven W. Orr" <[EMAIL PROTECTED]> wrote: > > > I have a list ll of intergers. I want to see if each number in ll is > > within the range of 0..maxnum > > > I can write it but I was wondering if there's a better way to do it? > > > TIA > > > -- > > Time flies like the wind. Fruit flies like a banana. Stranger things have > > .0. > > happened but none stranger than this. Does your driver's license say Organ > > ..0 > > Donor?Black holes are where God divided by zero. Listen to me! We are all- > > 000 > > individuals! What if this weren't a hypothetical question? > > steveo at syslang.net > > I would probably do something using max and min functions like this: > > seq = [...] # your list > > if min(seq) >= 0 && max(seq) <= MAXNUM: > do stuff OOps... I've been writing too much C++ lately (or too little python). That should read: if min(seq) >= 0 and max(seq) <= MAXNUM: do_stuff() -- http://mail.python.org/mailman/listinfo/python-list
Re: Flatten a two-level list --> one liner?
> Any ideas? how about list comprehension (should actually work even if there is an empty sub-list): >>> spam = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] >>> [parrot for egg in spam for parrot in egg] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -m -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to "import"?
> both using os module where should I put the "import os"? In both files? You don't really have a choice, you have to import os in both files. Python will only load the os module into memory once, but the import statements are needed to add the os module to the c and m module namespaces. The code in c.py cannot 'see' the code in m.py, even if it was imported by m.py. The import command is not like #include in C, it is not a code dump. -m -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with str()
Don't use built-ins as variable names. Your code will work if you change this: > methodList = [str for str in names if callable(getattr(obj, str))] to this: > methodList = [s for s in names if callable(getattr(obj, s))] -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menu toplevel or frame
> Please tell me is here anything that I should change. The way you have written it, master _must_ be a Toplevel object. So, maybe parent is the correct name, but it doesn't really matter. As a side note, there is no reason for this class to inherit Frame. Aside from packing and sizing the frame, you appear to do nothing else with it. You could just as easily inherit from object. You should never make a custom widget that packs itself anyway. A frame object should act like a frame. What you have made looks more like what I would call an application class. If you are trying to make a Menu, I would inherit from that instead. As an application class (you will still need the new,save... methods to be defined): class MyApp(object): def __init__(self, master=None): if master: self.master = master else: self.master = Tk() frame = Frame(master, width=200, height=200) frame.pack(fill=BOTH, expand=YES) self.makeMenuBar() def makeMenuBar(self): self.menubar = Menu(self.master) self.master.config(menu=self.menubar) pulldown = Menu(self.menubar, tearoff=0) pulldown.add_command(label='New', command=self.new) pulldown.add_command(label='Open', command=self.onOpen) pulldown.add_command(label='Save', command=self.save) pulldown.add_command(label='Save As', command=self.saveas) pulldown.add_separator() pulldown.add_command(label='Exit', command=self.onExit) self.menubar.add_cascade(label='File', underline=0, menu=pulldown) A menu class (this is untested, but it is close to how I would do it): class MyMenu(Menu): def __init__(self, master=None, **kwargs): Menu.__init__(self, master, **kwargs): self.master = master # This is equivalent to self packing, do it outiside of the widget # self.master.config(menu=self.menubar) pulldown = Menu(self, tearoff=0) pulldown.add_command(label='New', command=self.new) pulldown.add_command(label='Open', command=self.onOpen) pulldown.add_command(label='Save', command=self.save) pulldown.add_command(label='Save As', command=self.saveas) pulldown.add_separator() pulldown.add_command(label='Exit', command=self.onExit) self.add_cascade(label='File', underline=0, menu=pulldown) You can use this in the application class: class MyApp(object): def __init__(self, master=None): if master: self.master = master else: self.master = Tk() self.menubar = MyMenu(self.master) self.master.config(menu=self.menubar) frame = Frame(master, width=200, height=200) frame.pack(fill=BOTH, expand=YES) -- http://mail.python.org/mailman/listinfo/python-list
Re: To count number of quadruplets with sum = 0
> Any ideas to speed it up say 10 times? Or the problem only for C-like > langs? I dout this will speed it up by a factor of 10, but in your solution you are mapping the values in the input file to longs. The problem statement states that the maximum value for any of the numbers is 2**28. I assume the reason for this is precisely to allow you to use 32-bit integers. So, you can safely use int instead, and it _might_ speed up a little. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the insertion point in a list
You might look at the bisect module (part of the standard distribution). -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the insertion point in a list
On Mar 16, 11:20 am, "Matimus" <[EMAIL PROTECTED]> wrote: > You might look at the bisect module (part of the standard > distribution). Here is an example: >>> from bisect import insort >>> x = [0,100,200,1000] >>> insort(x,10) >>> x [0, 10, 100, 200, 1000] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C extension providing... Python's own API?
On Mar 26, 12:21 pm, "Adam Atlas" <[EMAIL PROTECTED]> wrote: > Does anyone know if it would be possible to create a CPython extension > -- or use the ctypes module -- to access Python's own embedding API > (http://docs.python.org/api/initialization.html&c.)? Could a Python > program itself create a sub-interpreter, and work with it with all the > privileges and capabilities that an actual C program would have? > > I realize that this may be a bit too... mystical? ... for a lot of > people's tastes, but I'm just curious if it's possible. :) I think that is what the "code" module is for. Maybe not exactly what you were expecting, but the capability you describe is already there. Being able to access its own interpreter is one of the things that makes Python a dynamic language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel ping problems python puzzler
I wouldn't use threads for system calls. Checkout the subprocess module instead. You can run multiple pipes at the same time (subprocess.Popen). The python documentation for subprocess is pretty good. There are a few examples. Actually, you don't even _need_ the subprocess module, you can use os.popen for similar functionality. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stack experiment
On Apr 3, 8:57 am, [EMAIL PROTECTED] wrote:
> Hi! Im new to Python and doing exercise found from internet. It is
> supposed to evaluate expression given with postfix operator using
> Stack() class.
>
> class Stack:
> def __init__(self):
> self.items = []
>
> def push(self, item):
> self.items.append(item)
>
> def pop(self):
> return self.items.pop()
>
> def isEmpty(self):
> return (self.items == [])
>
> def evaluatePostfix(expr):
> import re
> tokenList = re.split(" ([^0-9])", expr)
> stack = Stack()
> for token in tokenList:
> if token == '' or token == ' ':
> continue
> if token == '+':
> sum = stack.pop() + stack.pop()
> stack.push(sum)
> elif token == '*':
> product = stack.pop() * stack.pop()
> stack.push(product)
> else:
> stack.push(int(token))
> return stack.pop()
>
> print evaluatePostfix("56 47 + 2 *")
>
> Errormsg:
> Traceback (most recent call last):
>File "C:\*\postfix1.py", line 31, in
> print evaluatePostfix("56 47 + 2 *")
>File "C:\*\postfix1.py", line 28, in evaluatePostfix
> stack.push(int(token))
> ValueError: invalid literal for int() with base 10: '56 47'
>
> How can I avoid the error and get desired result?
Two things:
1. The regular expression contains a space, so it is trying to split
on a space character followed by a non number, when you really want to
split on any nonnumber. Remove the space.
tokenList = re.split(" ([^0-9])", expr) -> tokenList =
re.split("([^0-9])", expr)
2. The return statement in evaluatePostfix is part of the for loop, it
will exit on the first loop.
This:
for token in tokenList:
if token == '' or token == ' ':
continue
if token == '+':
sum = stack.pop() + stack.pop()
stack.push(sum)
elif token == '*':
product = stack.pop() * stack.pop()
stack.push(product)
else:
stack.push(int(token))
return stack.pop()
Should Be:
for token in tokenList:
if token == '' or token == ' ':
continue
if token == '+':
sum = stack.pop() + stack.pop()
stack.push(sum)
elif token == '*':
product = stack.pop() * stack.pop()
stack.push(product)
else:
stack.push(int(token))
return stack.pop()
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to remove multiple occurrences of a string within a list?
It depends on your application, but a 'set' might really be what you
want, as opposed to a list.
>>> s = set(["0024","haha","0024"])
>>> s
set(["0024","haha"])
>>> s.remove("0024")
>>> s
set(["haha"])
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to remove multiple occurrences of a string within a list?
On Apr 3, 12:13 pm, "bahoo" <[EMAIL PROTECTED]> wrote:
> On Apr 3, 2:31 pm, "Matimus" <[EMAIL PROTECTED]> wrote:
>
> > It depends on your application, but a 'set' might really be what you
> > want, as opposed to a list.
>
> > >>> s = set(["0024","haha","0024"])
> > >>> s
>
> > set(["0024","haha"])>>> s.remove("0024")
> > >>> s
>
> > set(["haha"])
>
> This sounds cool.
> But is there a command I can convert the "set" back to a "list"?
yeah...
>>> l = list(s)
>>> l
["haha"]
--
http://mail.python.org/mailman/listinfo/python-list
Re: OT: Question about RGB color method
On Apr 10, 12:32 pm, John Salerno <[EMAIL PROTECTED]> wrote: > Sorry for this non-Python question, but since it's computer related I > know you guys will have an answer, and I don't really know where else to > ask. Mainly I'm just curious anyway. > > I'm wondering, why do computers use a RGB color scheme instead of the > primary colors? Is there something you can't do with yellow? It seems > weird that RGB can be combined to make all colors, when that's supposed > to be the job of the primary colors. I'm sure there some technical > computer-related reason that it had to be this way. > > Thanks. See the Wikipedia article on primary colors: http://en.wikipedia.org/wiki/Primary_colors The quick answer is that RGB is a method of additive color mixing, and RBY is subtractive (and its not really RBY but YCM). Also, the colors emitted by your monitor are Red, Green and Blue. -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
On Apr 12, 1:20 am, "7stud" <[EMAIL PROTECTED]> wrote:
> I can't break out of the for loop in this example:
>
> --
> import sys
>
> lst = []
> for line in sys.stdin:
> lst.append(line)
> break
>
> print lst
> ---
>
> But, I can break out of the for loop when I do this:
>
> -
> import sys
>
> lst = []
> for line in open("aaa.txt"):
> lst.append(line)
> break
>
> print lst
> --
>
> Why doesn't break work in the first example?
1. Why are you breaking in the for loop? That will only give you the
first line.
2. Your issue is caused by buffered IO. Because of the buffered IO,
your code is equivalent to doing this:
lst = []
s = sys.stdin.read() #All* of the reading up to EOF is done upfront.
for line in s:
lst.append(line)
break # I'm sure you don't really want the break here though :)
One way to get around the buffering is to do this:
[code]
# Open a file or the input stream
if filename:
f = open(filename,"r")
else:
f = sys.stdin
# Then you check to see if your file is interactive
if f.isatty():
# This is unbuffered, and will iterate the same as f
f = iter(raw_input(),"")
# Now do your stuff
lst = []
for line in f:
lst.append(line)
print lst
[/code]
* well, not ALL, it will read in chunks. But, I think they are 4096
Byte chunks by default.
--
http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
On Apr 12, 8:20 am, Maric Michaud <[EMAIL PROTECTED]> wrote: > Le jeudi 12 avril 2007 16:25, Matimus a écrit : > > > # Then you check to see if your file is interactive > > if f.isatty(): > > # This is unbuffered, and will iterate the same as f > > f = iter(raw_input(),"") > > This should be f = iter(raw_input,"") and this will end in a EOFError and stop > on blank line. > So you need a wrapper like : > > >>> def stdin_iterator() : > > ... while(True) : > ... try : yield raw_input() > ... except EOFError : return > ... > > >>> f = stdin_iterator() > > Do you really need to iterate on the file this way instead of using the > straightforward readline method ? > > >>> import sys > >>> l=sys.stdin.readline() > >>> while(l) : > > ... print l, > ... l=sys.stdin.readline() > > -- > _ > > Maric Michaud > _ > > Aristote -www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 4 26 88 00 97 > Mobile: +33 6 32 77 00 21 You are correct, I looked back to a program I wrote a while ago where I ran into this issue. Here is the actual solution I used: if f.isatty(): f = iter(f.readline,"") -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing elements of a list with a string
Shriphani wrote:
> Hello all,
> I have a problem here. I have a list named list_of_files which
> contains filenames with their timestamps attached to the name. If I
> have a string "fstab", and I want to list out the files in whose names
> the word fstab appears should I go about like this :
>
> def listAllbackups(file):
> list_of_files = os.listdir("/home/shriphani/backupdir")
> for element in list_of_files:
> if element.find(file) != -1:
> date = ###
> time =
> return (date, time)
>
> The major trouble is that the return statement causes it to exit after
> attempt one. How do I use the yield statement here?
I would just do this:
[code]
from glob import glob
def listallbackupfiles(filename):
return glob("/home/shriphani/backupdir/*%s*"%filename)
[/code]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python class method as an argument of a function in a C extension
> Can anybody give me an hint (or some link) on how to define > 'aCFunction' and how to call 'self.myMethod' in the C source code? A python function defined in C accepts a pointer to self and a tuple of arguments, each of which is also a PyObject. If you pass a function or method, it will be included in the tuple of arguments. I don't think there is any difference between passing a method and a function. You can call that method using functions in the `Object Protocol' section of the API, such as PyObject_Call(...). Here is an example from the Python documentation: http://docs.python.org/ext/callingPython.html The first part shows how to get a function as an argument. The following bits of code show how to actually call that function.The example uses PyEval_CallObject, which I can't find documentation to. I'm not sure if it even exists (it may be a documentation error). But from the example it seems to work exactly the same as PyObject_CallObject. Matt -- http://mail.python.org/mailman/listinfo/python-list
