Re: SCGIServer and unusal termination

2009-11-16 Thread Eden Kirin

Anyone?

--
www.vikendi.net -/- www.supergrupa.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get attribute this way

2009-11-16 Thread King
"eval" can solve this problem right away but I am concerned about
security issues. If not "eval" could you suggest something more
efficient way. It won't be a big deal to change the format as
application is still at development stage?

Thanks

Prashant
Python 2.6.2
Win XP 32
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get attribute this way

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 10:53 PM, King  wrote:
> Writing/Reading data to xml is not a problem. The problem is when I
> have to write to attributes in xml, where a connections has been
> established.
> XML:
>  destattribute="node2.gradient.colors[1][2]"/>

You did not include an example like this in your original post.

I'd say you're stuck using eval() unless you want to change your
format or write a parser for the subset of Python involved.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get attribute this way

2009-11-16 Thread King
Writing/Reading data to xml is not a problem. The problem is when I
have to write to attributes in xml, where a connections has been
established.
XML:


While reading back I have to convert both source and destination
strings into object so that I can call connections function using
source and target attributes.

Prashant
Python 2.6.2
Win XP 32
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get attribute this way

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 10:04 PM, King  wrote:
> Python's getattr, setattr and __getattribute__ commands works fine
> with python types.
> For example:
> print o.__getattribute__("name")
> print getattr(o, "name")
> This is the easiest way to get an attribute using a string.
>
> In my case the "Node" class load/creates all the attributes from a xml
> file.
> Example
> 
> 
>
> There are certain atrributes of compound type.
> Example:
> # Array of colors, Here we are referring first color and second element
> (green)
> self.gradient.colors[0][1] = 0.5
> # Array of floats, referring first element
> self.gradient.positions[0] = 1.0
>
> Color, color array and floats are all custom classes.
>
> Now question is how to get these compound attributes using string as
> we do with default singular attributes.
> Example:
> getattr(o, "gradient.colors[0][1] ")
> I need this to save the data of nodes->attributes into a custom xml
> format, when loading this data back, I create the node first and then
> setup values from the saved xml file.

Can't you just iterate over the data structure? I'm not seeing why
you'd need to use getattr() and friends in the first place.

for color in self.gradient.colors:
for element in color:
#output XML fragment

#repeat for self.gradient.positions, etc.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please recommend the books that might be helpful to learn Python :)

2009-11-16 Thread Ben Finney
Psi  writes:

> as the subject says,
>
> any books?

Any web search would lead you to
http://wiki.python.org/moin/PythonBooks>, no?

-- 
 \   “There's no excuse to be bored. Sad, yes. Angry, yes. |
  `\Depressed, yes. Crazy, yes. But there's no excuse for boredom, |
_o__)  ever.” —Viggo Mortensen |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mySQL access speed

2009-11-16 Thread John Nagle

Hans Müller wrote:

Hello,

I have some programs doing a lot sql IO in some mySQL databases.
This works very fine and the DBAPI is quite simple to understand.

Now I came to the point where I had to insert millions of lines into a table.


  If you're loading into an empty table, use the LOAD command.  That's
far faster than doing vast numbers of INSERT operations.  The
LOAD command loads all the data, unindexed, then builds the indices.
Expect a 10x speed improvement or better.

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


Qt Python : QTreeWidget Child Problem

2009-11-16 Thread Threader Slash
Hello Everybody,

I have a QTreewidget that works fine if I have just one level on my
treelist. If I decide to add child sublevels, it gives me an error. Here is
the code, that works nice only without the "childs" lines on it (see after
"child 1" and "child 2").

def eqpt_centralwdg(self,MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")

self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
self.colorTreeWidget.setObjectName("colorTreeWidget")

# father root 1
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
#child 1 - from father 1
item = QtGui.QTreeWidgetItem(item)
#child 2 - from father 1
item = QtGui.QTreeWidgetItem(item)
# father root 2
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)

self.connect(self.colorTreeWidget,
QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
self.eqpt_activateInput)

MainWindow.setCentralWidget(self.centralwidget)

def eqpt_retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
"MainWindow", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.headerItem().setText(0,
QtGui.QApplication.translate("MainWindow", "color", None,
QtGui.QApplication.UnicodeUTF8)
__sortingEnabled = self.colorTreeWidget.isSortingEnabled()
self.colorTreeWidget.setSortingEnabled(False)
# father root 1
self.colorTreeWidget.topLevelItem(0).setText(0,
QtGui.QApplication.translate("MainWindow", "Yellow", None,
QtGui.QApplication.UnicodeUTF8)
#child 1 - from father 1
self.colorTreeWidget.topLevelItem(0).child(0).setText(0,
QtGui.QApplication.translate("MainWindow", "Yellow Sun", None,
QtGui.QApplication.UnicodeUTF8))
#child 2 - from father 1
self.colorTreeWidget.topLevelItem(0).child(1).setText(0,
QtGui.QApplication.translate("MainWindow", "Yellow Gold", None,
QtGui.QApplication.UnicodeUTF8))

# father root 2
self.colorTreeWidget.topLevelItem(1).setText(0,
QtGui.QApplication.translate("MainWindow", "Blue", None,
QtGui.QApplication.UnicodeUTF8)

self.colorTreeWidget.setSortingEnabled(__sortingEnabled)


Here is the output, when it works

def eqpt_activateInput(self,item,col):
print "Qtree ok! pressed"
print item.text(col)

if I exclude the lines related to the "child 1" and "child 2" from the code,
it runs. Otherwise, it gives me the error:

AttributeError: 'NoneType' object has no attribute 'setText'


I used the Qt Designer to generate the code, and added some lines to trigger
events.

Any hints or suggestions are highly appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: overriding __getitem__ for a subclass of dict

2009-11-16 Thread Carl Banks
On Nov 16, 10:32 am, Steve Howell  wrote:
> On Nov 16, 2:35 am, Carl Banks  wrote:
>
>
>
> > On Nov 15, 2:52 pm, Steve Howell  wrote:
>
> > > Does anybody have any links that points to the rationale for ignoring
> > > instance definitions of __getitem__ when new-style classes are
> > > involved?  I assume it has something to do with performance or
> > > protecting us from our own mistakes?
>
> > "Not important enough to justify complexity of implementation."
>
> > I doubt they would have left if out of new-style classes if it had
> > been straightforward to implement (if for no other reason than to
> > retain backwards compatibility), but it wasn't.  The way attribute
> > lookups work meant it would have required all kinds of double lookups
> > and edge cases.  Some regarded it as dubious to begin with.  And it's
> > easily worked around by simply having __getitem__ call another method,
> > as you've seen.  Given all this it made better sense to just leave it
> > out of new-style classes.
>
> Actually, the __getitem__ workaround that I proposed earlier only
> works on subclasses of dict, not dict themselves.  So given a pure
> dictionary object, it is impossible to hook into attribute lookups
> after instantiation in debugging/tracing code.  I know it's not a
> super common thing to do, but it is a legitimate use case from my
> perspective.  But I understand the tradeoffs.  They seem kind of 20th
> century to me, but with Moore's Law declining and all, maybe it's a
> bad time to bring up the "flexibility trumps performance"
> argument. ;)

It's not performance, it's code complexity.

Implementing this would have to added a lot of extra code to the
Python codebase--more than you seem to realize--all in support of a
dubious behavior.  This would have meant more opporunities for bugs,
and an increased maintainence burden.


> The backward compatibility argument also seems a little
> dubious, because if anybody *had* put __getitem__ on a dictionary
> instance before, it would have already been broken code, and if they
> hadn't done it, there would be no semantic change, just a performance
> hit, albeit a pervasive one.

Wrong.  It's only dubious from your narrow mindset that focuses on
your own problem and ignores the greater problem.  When new-style
classes were introduced, they made a decision that magic methods would
no longer work when defined on any instance.  It affected a *lot* more
than just your dictionary use-case.

So please spare me any suggestions that the change didn't carry a
significant backwards incompatibility.  It did, and they made the
change anyway.  That should tell you how difficult it would have been
to implement.


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


Get attribute this way

2009-11-16 Thread King
Python's getattr, setattr and __getattribute__ commands works fine
with python types.
For example:
print o.__getattribute__("name")
print getattr(o, "name")
This is the easiest way to get an attribute using a string.

In my case the "Node" class load/creates all the attributes from a xml
file.
Example



There are certain atrributes of compound type.
Example:
# Array of colors, Here we are referring first color and second element
(green)
self.gradient.colors[0][1] = 0.5
# Array of floats, referring first element
self.gradient.positions[0] = 1.0

Color, color array and floats are all custom classes.

Now question is how to get these compound attributes using string as
we do with default singular attributes.
Example:
getattr(o, "gradient.colors[0][1] ")
I need this to save the data of nodes->attributes into a custom xml
format, when loading this data back, I create the node first and then
setup values from the saved xml file.

Prashant
Python 2.6.2
Win XP 32
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Redirect stdout to a buffer [Errno 9]

2009-11-16 Thread Gabriel Genellina
En Mon, 16 Nov 2009 18:04:21 -0300, Ecir Hana   
escribió:

On Nov 16, 7:21 pm, "Gabriel Genellina" 
wrote:
En Mon, 16 Nov 2009 14:17:52 -0300, Ecir Hana   
escribió:


>> I'm trying to write a simple Win32 app, which may run some Python
>> scripts. Since it is a Windows GUI app, I would like to redirect all
>> output (Python print, C printf, fprinf stderr, ...) to a text area
>> inside the app. In other words, I'm trying to log all the output from
>> the app (C, Python) to a window. So far, this works for C printf():
>> [...]


thanks for the reply!


Sorry, my earlier code was not working as I expected; I wrongly assumed  
the output was being redirected but that was not the case.
The version below ("set paranoid mode on") does redirect printf(),  
fwrite(stdout,...), write(1,...), WriteFile(consolehandle,...), all those  
calls in C, but fails in Python with IOError: [Errno 9] Bad file  
descriptor.
I'm unable to figure out *where* it fails just by reading the Python  
source; one should set a breakpoint in python26.dll to see what actually  
happens.



However, please, could you tell me how many bytes it read here:

ReadFile(hReadPipe, buffer, 19, &nr, NULL);


The code below now reads from the pipe everything that has been written --  
except from Python :(



#include 
#include 
#include 
#include "Python.h"

int error(char* lpszText)
{
LPVOID lpMsgBuf;
DWORD lasterror = GetLastError();

FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
lasterror,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
fprintf(stderr,
"%s: error %d: %s",
lpszText, lasterror, lpMsgBuf);
LocalFree(lpMsgBuf);
return 1;
}

int main()
{
  HANDLE hReadPipe, hWritePipe;
  DWORD nr, nw;
  char buffer[100];
  int fd, i;
  BOOL bResult;

  if (!CreatePipe(
&hReadPipe,
&hWritePipe,
NULL,
0))
return error("cannot create pipe");
  if (!SetStdHandle(STD_OUTPUT_HANDLE, hWritePipe))
return error("SetStdHandle");

  // this was missing in previous version
  fd = _open_osfhandle((intptr_t)hWritePipe, _O_TEXT);
  if (fd==-1) return error("_open_osfhandle");
  if (_dup2(fd, 1)!=0) return error("dup2");

  if (!WriteFile(hWritePipe, "WriteFile(pipe)\n", 16, &nr, NULL)) return  
error("WriteFile(pipe)");
  if (!WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), "WriteFile(stdout)\n",  
18, &nr, NULL)) return error("WriteFile(stdout)");

  fputs("fputs from C\n", stdout);
  if (fwrite("fwrite from C\n", 1, 14, stdout)!=14) return  
error("fwrite!=14");

  if (write(1, "write from C\n", 13)<0) return error("write");
  fflush(stdout);

  fprintf(stderr, "before Python\n");
  Py_Initialize();
  PyRun_SimpleString("import sys;sys.stdout.write('from Python\\n')\n");
  Py_Finalize();

  fprintf(stderr, "before flush 2\n");
  fflush(stdout);

  fprintf(stderr, "before close pipe w\n");
  if (!CloseHandle(hWritePipe)) return error("CloseHandle(hWritePipe)");
  fprintf(stderr, "before close STDOUT Handle\n");
  if (!CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE))) return  
error("CloseHandle(STDOUT)");

  fprintf(stderr, "before read pipe\n");
  // read one char at a time...
  for (i = 0; i


--
Gabriel Genellina

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


Re: overriding __getitem__ for a subclass of dict

2009-11-16 Thread Steve Howell
On Nov 16, 4:06 pm, greg  wrote:
> Christian Heimes wrote:
> > Most magic methods are implemented as descriptors. Descriptors only
> > looked up on the type to increase the performance of the interpreter and
> > to simply the C API.
>
> There's also a semantic problem. Since new-style
> classes are also instances (of class 'type') and you
> can create subclasses of 'type', if special methods
> were looked up on instances, it would be ambiguous
> whether an attribute '__getitem__' on a class was
> meant to specify the behaviour of the [] operation
> on its instances, or on the class itself.
>
> This problem didn't arise with old-style classes,
> because classes and instances were clearly separated
> (i.e. old-style classes were not old-style instances).

That explanation makes some sense to me.  Given the ambiguity and the
backward compatibility issues, I would argue that both of the
commented lines in the program below should fail hard with a useful
warning.  Only one of them actually does.  The other just silently no-
ops.

class A(dict):
pass

a = A()
a['ignore'] = 'x'
a.__getitem__ = lambda key: 'foo' # exercise in futility

b = dict()
b['ignore'] = 'x'
b.__getitem__ = lambda key: 'foo' # hard failure

Tested under 2.6.

It seems like if __getitem__ is truly a special method, it should get
special treatment whenever you try to use it, even if that special
treatment is just an explicit error message that its use makes no
sense in a particular context.  If you allow __getitem__ to exist on
a, then you create situations where __getitem__ is basically an
instance method on an instance of a subtype of dict, which sounds
awfully ambiguous to me, given that the whole intent of __getitem__ is
to define the behavior of [] on classes.







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


Re: overriding __getitem__ for a subclass of dict

2009-11-16 Thread Steve Howell
On Nov 16, 5:46 pm, Steven D'Aprano
 wrote:
> On Mon, 16 Nov 2009 10:32:19 -0800, Steve Howell wrote:
> > Actually, the __getitem__ workaround that I proposed earlier only works
> > on subclasses of dict, not dict themselves.  So given a pure dictionary
> > object, it is impossible to hook into attribute lookups after
> > instantiation in debugging/tracing code.
>
> If you have written your application to avoid unnecessary isinstance and
> type checks, i.e. to use duck-typing, then a technique you might find
> useful is delegation.
>
> class DebuggingDict(object):
>     def __init__(self, dict_to_wrap, hook=None):
>         self.__dict__['_d'] = dict_to_wrap
>         self.__dict__['getitem_hook'] = hook
>     def __getattr__(self, name):
>         return getattr(self._d, name)
>     def __setattr__(self, name, value):
>         setattr(self._d, name, value)
>     def __getitem__(self, key):
>         if self.getitem_hook is not None:
>             self.getitem_hook(self, key)
>         return self._d[key]
>
> And in use:
>
> >>> def hook(self, key):
>
> ...     print "Looking for key", key
> ...>>> d = DebuggingDict({1:'a', 2: 'b'}, hook)
> >>> d[1]
>
> Looking for key 1
> 'a'>>> d[2]
>
> Looking for key 2
> 'b'
>

Yep, this basically resembles the approach that I originally took for
the broader problem, which was that I wanted to see how a third party
library (the Django templating system) was accessing dictionaries that
referred to objects that my tracing code did not create.  Although I
did not instantiate the original objects, I did have the ability to
substitute masquerade objects for the original objects before passing
them along, and my code for the masquerading objects was similar in
spirit to your DebuggingDict.  It actually worked pretty well, except
that eventually my masquerade objects went off to places where I was
not fully able to maintain the illusion of being the original object.
My original post on this thread sheds some light on what I'm doing,
but basically I was trying to masquerade down the whole tree of calls
from Django, which worked fine as long as Django was trying first to
access my objects like dictionaries, which it always does first when
rendering template variables, but all bets are off after that (custom
filters, etc.).

Eventually, I realized that it was easier to just monkeypatch Django
while I was in test mode to get a more direct hook into the behavior I
was trying to monitor, and then I didn't need to bother with
overriding __getitem__ or creating complicated wrapper objects.  I
wrote about it here if anybody is morbidly interested:

http://showellonprogramming.blogspot.com/



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


Re: Newsgroup for beginners

2009-11-16 Thread Tim Chase

 1) Start by complaining that your program doesn't work because
of a bug in Python.


1b) Omit the fact that this is a homework problem, and you want 
c.l.p to do your homework for you



 4) Once people start to get annoyed that you won't post any
example code showing the problem you're having, then you
post code.

 a) Post lots of code.  The bigger the program the better;
try for at least 500 lines -- but make sure that you
leave out a few functions and "import" some libraries
nobody has ever heard of.

 b) Post code that doesn't match the code who's behaviour
you're describing (remember: be vague and be careful
not to actually show real input or output at this
point).

 c) For maximum effect try to make sure that what you post
won't compile by inserting typos and changing the
indentation in a few places.


d) you post a link to your uploaded code on some code-sharing 
site that requires the latest versions of JavaScript, Flash, 
Silverlight, Java, and requires cookies to be enabled just to 
read your flippin' code.



 c) rather than cutting/pasting input and output, make sure
you manually retype it into your posting --
inaccurately.


[sheepish grin]  Guilty as charged on at least one occasion.



It'll take several days and a fair bit of work, but you will be
able to produce a some grouchy responses in c.l.p.


oh, shut up!  ;-)


One will also get rather arcane answers when a poorly thought
out question is answered literally.  IOW, somebody asks "how to
I do B?" when B _really_ isn't something anybody is going to
want to in Python, but if you twist the language around enough
you can actually _do_ B (even if it's quite pointless).  The
real question was "how do I accomplish A", but the poster
having incorrectly assumed the answer is B, didn't ask "how do
I accomplish A?"


"But why can't I use regular expressions to do...?" :-)

Even the best Pythoneers get grouchy ("This parrot wouldn't VOOM 
if you put 4 million volts through it!")


-tkc





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


Re: Command line arguments??

2009-11-16 Thread rantingrick
On Nov 16, 5:30 pm, "Rhodri James" 
wrote:

> We've been living with this pain ever since windowed GUIs encouraged users  
> to put spaces in their file names (Apple, I'm looking at you!).  
> Fundamentally, if people want the pretty they have to live with the  
> consequences.

Thanks everyone , problem solved!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newsgroup for beginners

2009-11-16 Thread Ben Finney
Grant Edwards  writes:

>  2) State that your program "doesn't work", but don't explain
> either what you expect it to do or what it actually does.

A different flavour of this is also good for setting the seeds of
grouchiness:

  2a) Write a Subject field that doesn't say anything about what you're
  asking, so the thread doesn't garner any attention from busy
  people.

  For bonus points, put something like “newbie question” there
  instead of anything actually relevant to the problem.

No, this thread is not an example; the Subject field is an entirely
relevant concise description of the information being sought.

-- 
 \   “bash awk grep perl sed, df du, du-du du-du, vi troff su fsck |
  `\ rm * halt LART LART LART!” —The Swedish BOFH, |
_o__)alt.sysadmin.recovery |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newsgroup for beginners

2009-11-16 Thread Grant Edwards
On 2009-11-17, Paul Rubin  wrote:
> mrholtsr  writes:
>> Is there a Python newsgroup for those who are strictly beginners at
>> programming and python?
>
> This group has its grouchy moments

You've really got to try pretty hard to create one.  But if you
want to, here's how to do it:

 1) Start by complaining that your program doesn't work because
of a bug in Python.

 2) Python programs are portable, so don't reveal what OS or
Python version you're using.  People will ask. Just ignore
them.

 2) State that your program "doesn't work", but don't explain
either what you expect it to do or what it actually does.

 3) Don't post the code that you're having problems with.

 4) Once people start to get annoyed that you won't post any
example code showing the problem you're having, then you
post code.

 a) Post lots of code.  The bigger the program the better;
try for at least 500 lines -- but make sure that you
leave out a few functions and "import" some libraries
nobody has ever heard of.

 b) Post code that doesn't match the code who's behaviour
you're describing (remember: be vague and be careful
not to actually show real input or output at this
point).

 c) For maximum effect try to make sure that what you post
won't compile by inserting typos and changing the
indentation in a few places.

 5) Once you've stalled as long as possible you want to post
code that will comipile and run.  Now we move on to example
inout and output.

 a) post output from a _different_ version of the program
than what you're running.

 b) post input to and output from your program, but make
sure that the output was generated with input
differenent that what was posted.

 c) rather than cutting/pasting input and output, make sure
you manually retype it into your posting --
inaccurately.

In any other newsgroup, you'd have been burnt to a crisp and
plonked long before getting this far, but in c.l.p there are
still going to be a few people trying to help you.  Now is the
time to start making snide comments about how it would be so
much easier in VB/Perl/C++ (pick whichever one you know the
most about).

Pick a feature from VB/Perl/C++ unrelated to the original
problem and start demanding that it be added to Python so that
you can use it to make your program work.

For the final touch, forget about the original "bug" and start
to wax philosophic about how this is just another typical
example of the problems with Python, open-source, mass transit,
the designated hitter, auto-tune, people who like cats, and the
dewey decimal system. Use lots of poetic-sounding but
nonsensical metaphors.

It'll take several days and a fair bit of work, but you will be
able to produce a some grouchy responses in c.l.p.
 
> but for the most part it's reasonably friendly to beginners.
> The worst thing that usually happens is that if you ask a
> simple question, a bunch of experts will show off their
> knowledge to each other by giving you insanely complicated
> answers that you have no reason to want to understand.

That usually happens when the question is vague and incomplete
enough so that people have to guess what is being asked.  Some
people tend to guess more "interesting" questions than others.

One will also get rather arcane answers when a poorly thought
out question is answered literally.  IOW, somebody asks "how to
I do B?" when B _really_ isn't something anybody is going to
want to in Python, but if you twist the language around enough
you can actually _do_ B (even if it's quite pointless).  The
real question was "how do I accomplish A", but the poster
having incorrectly assumed the answer is B, didn't ask "how do
I accomplish A?"

They're really not trying to torture beginners, they just think
it's interesting trying to figure out a way to do B.

Even if you do get some obscure answers, others will always
figure out that what you really wanted to know was "how do I
accomplish A" and tell you the best way to accomplish A and why
B isn't what you want to do.

-- 
Grant

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


ReverseProxy

2009-11-16 Thread Fred C


I have to write a quick and dirty ReverseProxy with Twisted, for one  
of our internal project. I never used Twisted before, and I was  
wondering of someone have an handy example of a ReverseProxy with  
Twisted to help that I can use as bootstrap.


Many thanks.
Fred-- 
http://mail.python.org/mailman/listinfo/python-list


Is pexpect unmaintained now?

2009-11-16 Thread yuzhichang
Pexpect 2.4 is only available at Pypi. Both the homepage of
pexpect(http://www.noah.org/wiki/Pexpect) and download page
(http://sourceforge.net/projects/pexpect/files/) are outdated. The
repository on Github (http://github.com/noahspurrier/pexpect/) has
been removed.

I ever contacted the author(n...@noah.org) but no response till now.

I'm going to fork pexpect on Github and add some features...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread alex23
Steve Ferg  wrote:
> Does anybody know a language with this kind of syntax for
> ifThenElseEndif?

VBScript.

> Is there any particular reason why this might be a *bad* language-
> design idea?

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


Solved: QtPython QtreeWidget - sortingEnabled Problem

2009-11-16 Thread Threader Slash
> --  --
> From: Threader Slash 
> To: python-list@python.org
> Date: Tue, 17 Nov 2009 10:34:34 +1100
> Subject: QtPython QtreeWidget - sortingEnabled Problem
> Hello Everybody,
>
> I trying to do a Qtreewidget to attend a customer design suggestion. I am
> coding it on QtPython. I did a first try using Qt Designer, then generated
> the code. But when I try to run it, an error comes out:
>
> self.centralwidget.setSortingEnabled(__sortingEnabled)
> AttributeError: setSortingEnabled
>
> I googled around, but didn't find any solution for this problem, except
> some suggestion just to simply delete the lines in the code that results in
> the compiling error. But it didn't really help, because if you do so, it
> triggers more error, just like that:
>
> self.treeWidget.topLevelItem(0).child(1).setText(0,
> QtGui.QApplication.translate("MainWindow", "Item Name", None,
> QtGui.QApplication.UnicodeUTF8))
> AttributeError: 'NoneType' object has no attribute 'setText'
>
> Here is my current code to generate a nice simple QtreeWidget/View:
>
> #//===//#
> def color_setupUi(self, MainWindow,phrase):
> MainWindow.setObjectName("MainWindow")
> MainWindow.resize(800, 600)
> self.eqpt_centralwdg(MainWindow)
> self.eqpt_retranslateUi(MainWindow)
> QtCore.QMetaObject.connectSlotsByName(MainWindow)
> #//===//#
> def eqpt_centralwdg(self,MainWindow):
> self.centralwidget = QtGui.QWidget(MainWindow)
> self.centralwidget.setObjectName("centralwidget")
>
> self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
> self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
> self.colorTreeWidget.setObjectName("colorTreeWidget")
>
> item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
> item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
>
> self.centralwidget.setSortingEnabled(__sortingEnabled)
> MainWindow.setCentralWidget(self.centralwidget)
> #//===//#
> def eqpt_retranslateUi(self, MainWindow):
>
> MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
> "MainWindow", None, QtGui.QApplication.UnicodeUTF8)
>
> self.colorTreeWidget.headerItem().setText(0,
> QtGui.QApplication.translate("MainWindow", "color", None,
> QtGui.QApplication.UnicodeUTF8)
> __sortingEnabled = self.colorTreeWidget.isSortingEnabled()
> self.colorTreeWidget.setSortingEnabled(False)
> self.colorTreeWidget.topLevelItem(0).setText(0,
> QtGui.QApplication.translate("MainWindow", "Yellow", None,
> QtGui.QApplication.UnicodeUTF8)
> self.colorTreeWidget.topLevelItem(1).setText(0,
> QtGui.QApplication.translate("MainWindow", "Blue", None,
> QtGui.QApplication.UnicodeUTF8)
> self.colorTreeWidget.setSortingEnabled(__sortingEnabled)
> #//===//#
>
> All other object I needed to implement on Qt using Designer and a little
> bit of code has worked fine so far, e.g. inputLine, comboBox, TabWidget. I
> just got stuck with this TreeWidget error.
>
> Any hints or suggestion are highly appreciated and welcome.
>
> --  --
>


Here is the solution:
1. delete/comment only the following line:
#self.centralwidget.setSortingEnabled(__sortingEnabled)

Then code:
[code]
def eqpt_centralwdg(self,MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")

self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
self.colorTreeWidget.setObjectName("colorTreeWidget")

item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)

self.connect(self.colorTreeWidget,
QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
self.eqpt_activateInput)

MainWindow.setCentralWidget(self.centralwidget)

def eqpt_activateInput(self,item,col):
print "Qtree ok! pressed"
print item.text(col)
[/code]

Hope this may help others too.
ThreaderSlash
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: faster than list.extend()

2009-11-16 Thread Jason Sewall
On Mon, Nov 16, 2009 at 6:28 PM, Raymond Hettinger  wrote:
> On Nov 16, 2:41 pm, Chris Rebert  wrote:
>> On Mon, Nov 16, 2009 at 2:30 PM, Hyunchul Kim
>>
>>  wrote:
>> > Hi, all.
>>
>> > I want to improve speed of following simple function.
>> > Any suggestion?
>>
>> > **
>> > def triple(inputlist):
>> >   results = []
>> >   for x in inputlist:
>> >     results.extend([x,x,x])
>> >   return results
>
>
> Here's an itertools variant that is somewhat speedy when the inputlist
> is long:
>
>    from itertools import *
>
>    def triple3(inputlist, list=list,
> chain_from_iterable=chain.from_iterable, izip=izip):
>        return list(chain_from_iterable(izip(inputlist, inputlist,
> inputlist)))

Even (slightly) faster:

def triple3_mk2(inputlist):
return list(chain.from_iterable(izip(*repeat(inputlist, 3

I tried something like this when I saw Hyunchul's original email, but
I didn't know about chain.from_iterable and it was pretty slow
compared to the original.  Adding (itertools.)repeat to Raymonds
speeds it up 5-10% more.

I'm pretty surprised this is faster than Tim's t2 (which is actually a
little slower than the original); I always thought of comprehensions
as the fastest way to do this find of stuff.

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


Re: Newsgroup for beginners

2009-11-16 Thread Paul Rubin
mrholtsr  writes:
> Is there a Python newsgroup for those who are strictly beginners at
> programming and python?

This group has its grouchy moments but for the most part it's
reasonably friendly to beginners.  The worst thing that usually
happens is that if you ask a simple question, a bunch of experts will
show off their knowledge to each other by giving you insanely
complicated answers that you have no reason to want to understand.
But they're not exactly being hostile when they do that.  They're just
really really into advanced Python programming.  So go ahead and ask
your questions.  The first responses will probably be the most
helpful, after which the response thread will go off into nerdy
tangents that you can ignore.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python simply not scaleable enough for google?

2009-11-16 Thread Paul Rubin
sturlamolden  writes:
> >       Python is a very clean language held back from widespread use by slow
> > implementations.  If Python ran faster, Go would be unnecessary.
> 
> Google is a multi-billion dollar business. They are using Python
> extensively. Yes I know about Unladen Swallow, but why can't they put
> 1 mill dollar into making a fast Python?

I don't think Python and Go address the same set of programmer
desires.  For example, Go has a static type system.  Some programmers
find static type systems to be useless or undesirable.  Others find
them extremely helpful and want to use them them.  If you're a
programmer who wants a static type system, you'll probably prefer Go
to Python, and vice versa.  That has nothing to do with implementation
speed or development expenditures.  If Google spent a million dollars
adding static types to Python, it wouldn't be Python any more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python & Go

2009-11-16 Thread Paul Rubin
sturlamolden  writes:
> A decorator function like @go could just call os.fork and run the
> function in the child. We already have a between-process Queue in
> multiprocessing to use as channels.

Unlike with interthread queues, you have to serialize the values sent
through those multiprocessing channels.  I don't think you can send
functions, generators, file descriptors, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: basic class question..

2009-11-16 Thread Steven D'Aprano
On Sun, 15 Nov 2009 16:26:59 -0800, Pyrot wrote:

> On 11월15일, 오후9시52분, "Diez B. Roggisch"  wrote:
>> Pyrot schrieb:
>>
>> > class rawDNA:
>> >    import string
[...]
> (Tthe core reason that I'm bothering with this at all is because I heard
> imports are costly(in time, space, processing power). If this turns out
> to be a non-issue, than my questions regarding Imports are all moot :->)

Importing a module is only costly the first time (in any session) that 
you do so. Modules are cached, so the second time it is relatively fast.


> I forgot to write about my second question which was:
> 
> what happens when I use the import statement within a class/function
> declaration?
> I'm thinking either
> 1) It imports during the class/function declaration 
> 2) It imports the first time a class/function call(x = rawDNA() ) occurs

It imports when the class/function statement is *run*.

def f():
import math

The body of the function doesn't run until you call the function, so the 
import doesn't happen until you call f().

class K:
import math
def method(self):
import string

The class definition runs when you create the class, which imports math. 
But string is only imported when you call K().method().

> But if it's 2) then is the import valid outside of the function/class?

No. The *name* "math" exists only inside the scope of the function, or 
class, and is not visible outside. 

>>> class K:
... import math
...
>>> K.math

>>> math
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'math' is not defined



> what happens when the last function reference is removed?(del x)

You wrote:

x = rawDNA()

Deleting x won't do anything to the class rawDNA, or to the module string 
which is referenced by the rawDNA class.

If you delete the rawDNA class, that won't do anything to the string 
module cached in sys.



> I respect your(or anyone who would like to help me) time, so all I ask
> is some kind of document or "Best practices" guide dealing all about
> "import".


99.9% of the time you don't need to worry about it. Just import the 
modules you want at the top level of your program, and be happy that it 
all works fine.

The other 0.1% of the time, you might have one or two good reasons for 
putting imports inside functions:

(1) Encapsulation: you want to import a module to use in a function, 
without making it visible to other functions.

(2) Just In Time importing. Imports at the top level slow down your 
program's start up. Normally, this is trivial and it is not worth the 
extra complexity to do something about it, but if you have a particularly 
expensive module which happens to be used only in one function which is 
rarely needed, then you can speed up your program for the majority of 
times by putting the import inside that one function.


However, putting imports inside functions which are then called by 
threads can lead to deadlocks. So you also have to balance the risk of 
that happening.



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


Re: faster than list.extend()

2009-11-16 Thread Gabriel Genellina

En Mon, 16 Nov 2009 19:30:27 -0300, Hyunchul Kim
 escribió:


I want to improve speed of following simple function.
Any suggestion?

**
def triple(inputlist):
  results = []
  for x in inputlist:
results.extend([x,x,x])
  return results
**


These are my best attempts:

def triple3(inputlist):
   results = []
   append = results.append
   for x in inputlist:
 append(x); append(x); append(x)
   return results

def triple4(inputlist, _three=xrange(3)):
  return [x for x in inputlist for _ in _three]

For a 400-items list, triple3 is 40% faster and triple4 25% faster than
yours.

--
Gabriel Genellina

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


Re: overriding __getitem__ for a subclass of dict

2009-11-16 Thread Steven D'Aprano
On Mon, 16 Nov 2009 10:32:19 -0800, Steve Howell wrote:

> Actually, the __getitem__ workaround that I proposed earlier only works
> on subclasses of dict, not dict themselves.  So given a pure dictionary
> object, it is impossible to hook into attribute lookups after
> instantiation in debugging/tracing code.

If you have written your application to avoid unnecessary isinstance and 
type checks, i.e. to use duck-typing, then a technique you might find 
useful is delegation.


class DebuggingDict(object):
def __init__(self, dict_to_wrap, hook=None):
self.__dict__['_d'] = dict_to_wrap
self.__dict__['getitem_hook'] = hook
def __getattr__(self, name):
return getattr(self._d, name)
def __setattr__(self, name, value):
setattr(self._d, name, value)
def __getitem__(self, key):
if self.getitem_hook is not None:
self.getitem_hook(self, key)
return self._d[key]


And in use:

>>> def hook(self, key):
... print "Looking for key", key
... 
>>> d = DebuggingDict({1:'a', 2: 'b'}, hook)
>>> d[1]
Looking for key 1
'a'
>>> d[2]
Looking for key 2
'b'


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


Re: Logic operators with "in" statement

2009-11-16 Thread Xavier Ho
On Tue, Nov 17, 2009 at 12:46 AM, Chris Rebert  wrote:

> On Mon, Nov 16, 2009 at 6:23 AM, Xavier Ho  wrote:
> > AND operator has a higher precedence, so you don't need any brackets
> here, I
> > think. But anyway, you have to use it like that. So that's something
> you'll
> > have to fix first.
>
> Er, you mean lower precedence. Higher precedence means it would bind
> tighter, thus the expression would mean:
> '3' in (l and 'no3') in l
> which is certainly incorrect.
>
>
Thanks for the correction, Chris.

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


ZipFile - file adding API incomplete?

2009-11-16 Thread Glenn Maynard
I want to do something fairly simple: read files from one ZIP and add
them to another, so I can remove and replace files.  This led me to a
couple things that seem to be missing from the API.

The simple approach would be to open each file in the source ZIP, and
hand it off to newzip.write().  There's a missing piece, though:
there's no API that lets me pass in a file-like object and a ZipInfo,
to preserve metadata.  zip.write() only takes the filename and
compression method, not a ZipInfo; writestr takes a ZipInfo but only
accepts a string, not a file.  Is there an API call I'm missing?
(This seems like the fundamental API for adding files, that write and
writestr should be calling.)

The correct approach is to copy the data directly, so it's not
recompressed.  This would need two new API calls: rawopen(), acting
like open() but returning a direct file slice and not decompressing
data; and rawwrite(zinfo, file), to pass in pre-compressed data, where
the compression method in zinfo matches the compression type used.

I was surprised that I couldn't find the former.  The latter is an
advanced one, important for implementing any tool that modifies large
ZIPs.  Short-term, at least, I'll probably implement these externally.

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


Re: overriding __getitem__ for a subclass of dict

2009-11-16 Thread greg

Christian Heimes wrote:


Most magic methods are implemented as descriptors. Descriptors only
looked up on the type to increase the performance of the interpreter and
to simply the C API.


There's also a semantic problem. Since new-style
classes are also instances (of class 'type') and you
can create subclasses of 'type', if special methods
were looked up on instances, it would be ambiguous
whether an attribute '__getitem__' on a class was
meant to specify the behaviour of the [] operation
on its instances, or on the class itself.

This problem didn't arise with old-style classes,
because classes and instances were clearly separated
(i.e. old-style classes were not old-style instances).

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


QtPython QtreeWidget - sortingEnabled Problem

2009-11-16 Thread Threader Slash
Hello Everybody,

I trying to do a Qtreewidget to attend a customer design suggestion. I am
coding it on QtPython. I did a first try using Qt Designer, then generated
the code. But when I try to run it, an error comes out:

self.centralwidget.setSortingEnabled(__sortingEnabled)
AttributeError: setSortingEnabled

I googled around, but didn't find any solution for this problem, except some
suggestion just to simply delete the lines in the code that results in the
compiling error. But it didn't really help, because if you do so, it
triggers more error, just like that:

self.treeWidget.topLevelItem(0).child(1).setText(0,
QtGui.QApplication.translate("MainWindow", "Item Name", None,
QtGui.QApplication.UnicodeUTF8))
AttributeError: 'NoneType' object has no attribute 'setText'

Here is my current code to generate a nice simple QtreeWidget/View:

#//===//#
def color_setupUi(self, MainWindow,phrase):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.eqpt_centralwdg(MainWindow)
self.eqpt_retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#//===//#
def eqpt_centralwdg(self,MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")

self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
self.colorTreeWidget.setObjectName("colorTreeWidget")

item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)

self.centralwidget.setSortingEnabled(__sortingEnabled)
MainWindow.setCentralWidget(self.centralwidget)
#//===//#
def eqpt_retranslateUi(self, MainWindow):

MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
"MainWindow", None, QtGui.QApplication.UnicodeUTF8)

self.colorTreeWidget.headerItem().setText(0,
QtGui.QApplication.translate("MainWindow", "color", None,
QtGui.QApplication.UnicodeUTF8)
__sortingEnabled = self.colorTreeWidget.isSortingEnabled()
self.colorTreeWidget.setSortingEnabled(False)
self.colorTreeWidget.topLevelItem(0).setText(0,
QtGui.QApplication.translate("MainWindow", "Yellow", None,
QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.topLevelItem(1).setText(0,
QtGui.QApplication.translate("MainWindow", "Blue", None,
QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.setSortingEnabled(__sortingEnabled)
#//===//#

All other object I needed to implement on Qt using Designer and a little bit
of code has worked fine so far, e.g. inputLine, comboBox, TabWidget. I just
got stuck with this TreeWidget error.

Any hints or suggestion are highly appreciated and welcome.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Command line arguments??

2009-11-16 Thread Rhodri James
On Mon, 16 Nov 2009 23:18:23 -, rantingrick   
wrote:



I am currently having "fun" with command line arguments in a windows
environment. If i get a path that has spaces anywhere in it my script
gets the wrong arguments from sys.argv. You guy's probably know what i
am talking about. Heres and example.

'C:\\Python26\\Python.exe C:\\echo.py C:\\New Folder\\text.txt'

inside my script i get the following result from sys.argv

['C:\\Python26\\Python.exe', 'C:\\echo.py', 'C:\\New', 'Folder\
\text.txt']

So i've got a few options
  1. have people replace every space in all file paths system wide
(sucks)
  2. Create a custom parser, join the argv list, parse it...(maybe)
  3. please tell me there is an option 3? (hopefully)


Quote the filenames or escape the spaces:

C:\Python26\Python.exe C:\echo.py "C:\New Folder\text.txt"

We've been living with this pain ever since windowed GUIs encouraged users  
to put spaces in their file names (Apple, I'm looking at you!).   
Fundamentally, if people want the pretty they have to live with the  
consequences.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: faster than list.extend()

2009-11-16 Thread Raymond Hettinger
On Nov 16, 2:41 pm, Chris Rebert  wrote:
> On Mon, Nov 16, 2009 at 2:30 PM, Hyunchul Kim
>
>  wrote:
> > Hi, all.
>
> > I want to improve speed of following simple function.
> > Any suggestion?
>
> > **
> > def triple(inputlist):
> >   results = []
> >   for x in inputlist:
> >     results.extend([x,x,x])
> >   return results


Here's an itertools variant that is somewhat speedy when the inputlist
is long:

from itertools import *

def triple3(inputlist, list=list,
chain_from_iterable=chain.from_iterable, izip=izip):
return list(chain_from_iterable(izip(inputlist, inputlist,
inputlist)))

Raymond


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


Re: Command line arguments??

2009-11-16 Thread Benjamin Kaplan
On Mon, Nov 16, 2009 at 6:18 PM, rantingrick  wrote:
> I am currently having "fun" with command line arguments in a windows
> environment. If i get a path that has spaces anywhere in it my script
> gets the wrong arguments from sys.argv. You guy's probably know what i
> am talking about. Heres and example.
>
> 'C:\\Python26\\Python.exe C:\\echo.py C:\\New Folder\\text.txt'
>
> inside my script i get the following result from sys.argv
>
> ['C:\\Python26\\Python.exe', 'C:\\echo.py', 'C:\\New', 'Folder\
> \text.txt']
>
> So i've got a few options
>  1. have people replace every space in all file paths system wide
> (sucks)
>  2. Create a custom parser, join the argv list, parse it...(maybe)
>  3. please tell me there is an option 3? (hopefully)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

The same thing you have to do with every command line program - wrap
it in quotes.
C:\\Python26\\python.exe C:\\echo.py "C:\\New Folder\\text.txt"
-- 
http://mail.python.org/mailman/listinfo/python-list


Command line arguments??

2009-11-16 Thread rantingrick
I am currently having "fun" with command line arguments in a windows
environment. If i get a path that has spaces anywhere in it my script
gets the wrong arguments from sys.argv. You guy's probably know what i
am talking about. Heres and example.

'C:\\Python26\\Python.exe C:\\echo.py C:\\New Folder\\text.txt'

inside my script i get the following result from sys.argv

['C:\\Python26\\Python.exe', 'C:\\echo.py', 'C:\\New', 'Folder\
\text.txt']

So i've got a few options
  1. have people replace every space in all file paths system wide
(sucks)
  2. Create a custom parser, join the argv list, parse it...(maybe)
  3. please tell me there is an option 3? (hopefully)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: faster than list.extend()

2009-11-16 Thread Tim Chase

Hyunchul Kim wrote:

Hi, all.

I want to improve speed of following simple function.
Any suggestion?

**
def triple(inputlist):
  results = []
  for x in inputlist:
results.extend([x,x,x])
  return results
**


Several ways occur to me:

  def t1(i):
for x in i:
  yield x
  yield x
  yield x

  def t2(i):
r = range(3)
return (x for x in i for _ in r)


I prefer to return generators in case the input is large, but in 
both cases, you can just wrap it in list() like


  list(t1(inputlist))

or in t2(), you can just change it to use

return [x for x in i for _ in r]

-tkc




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


Re: Changing the current directory (full post)

2009-11-16 Thread Gabriel Genellina

En Mon, 16 Nov 2009 18:10:51 -0300, Dave Angel  escribió:

Chris Rebert wrote:
On Mon, Nov 16, 2009 at 11:56 AM, vsoler   
wrote:



When I enter IDLE, I'd like to say at the prompt: "my current
directory is...  ...test" and then be able to run a module in that
directory. This is what my problem is!!!



Change directory to the test-directory
Then run idle


Or, modify the Initial Directory in the menu shortcut that you use to  
start IDLE (right click, Properties). Or create another shortcut in your  
desktop using your desired initial directory.


--
Gabriel Genellina

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


Re: faster than list.extend()

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 2:30 PM, Hyunchul Kim
 wrote:
> Hi, all.
>
> I want to improve speed of following simple function.
> Any suggestion?
>
> **
> def triple(inputlist):
>   results = []
>   for x in inputlist:
>     results.extend([x,x,x])
>   return results
> **

You'd probably be better off calling .append() 3 times instead of
.extend() as it would avoid the creation of all those intermediate
3-element lists.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Erik Max Francis

Steve Ferg wrote:

I've often thought that a language with this kind of block-free syntax
would be nice and intuitive:

if  then
do stuff
elif  then
do stuff
else
do stuff
endif

Note that you do not need block delimiters.

Obviously, you could make a more Pythonesque syntax by using a colon
rather then "then" for the condition terminator.  You could make it
more PL/I-like by using "do", etc.

You can write shell scripts using if ... fi, but other than that I
don't recall a language with this kind of syntax.


It's the same syntax, with `fi` written instead of `endif` -- not sure 
why the difference in keyword is that big of a deal to you.


As others have pointed out, either way, there are quite a few languages 
that use this type of syntax.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis
  Mona Lisa / Come to discover / I am your daughter
   -- Lamya
--
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Erik Max Francis

r wrote:

On Nov 16, 10:54 am, Steve Ferg 
wrote:


I've often thought that a language with this kind of block-free syntax
would be nice and intuitive:

if  then
do stuff
elif  then
do stuff
else
do stuff
endif


WHY? Python's syntax is by far the most elegant of all, no need to
show the end of a block. Python is the smartest kid on the block. And
are you saying you would rather type "then" instead of ":" and "endif"
instead of "\n"?

No thanks!


You clipped out the part where he explicitly said it was not a 
suggestion to change Python.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis
  Mona Lisa / Come to discover / I am your daughter
   -- Lamya
--
http://mail.python.org/mailman/listinfo/python-list


faster than list.extend()

2009-11-16 Thread Hyunchul Kim
Hi, all.

I want to improve speed of following simple function.
Any suggestion?

**
def triple(inputlist):
  results = []
  for x in inputlist:
results.extend([x,x,x])
  return results
**

Thank you in advance,

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


Re: mySQL access speed

2009-11-16 Thread Dikkie Dik
> ... But it isn't very fast.
> For executemany I have some hundred thousend lines in a list of tuples.
> I joined() these lines to form an insert into table values () statement 
> and
> blew it into the mysql cmdline client via os.popen().
> This was 60(!) times faster and loaded my table in seconds!
> 
> Is the mySQL module so slow ?


No. The fact that each statement is atomic makes it slow. Try the
multiple queries, but precede them with a "SET AUTOCOMMIT=0" statement
or use a transaction. You will probably see a tremendous speed increase.

When you combine all the queries into one statement, you are effectively
doing the same.

Best regards,
Dikkie.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: directory wildcard

2009-11-16 Thread hong zhang


--- On Mon, 11/16/09, Jeff McNeil  wrote:

> From: Jeff McNeil 
> Subject: Re: directory wildcard
> To: python-list@python.org
> Date: Monday, November 16, 2009, 3:01 PM
> On Nov 16, 3:33 pm, hong zhang
> 
> wrote:
> > List,
> >
> > I try to assign value to force_mcs sitting in a
> wildcard subdirectory /sys/kernel/debug/ieee80211/phy*, but
> python does not work for that such as:
> >
> > os.system("echo %i >
> /sys/kernel/debug/ieee80211/phy*/iwlagn/data/force_mcs" %
> mcs)
> >
> > Any right way to do it?
> >
> > Thanks.
> >
> > --henry
> 
> I'd ditch the echo business altogether. 2.x. Not tested.
> 
> import glob
> 
> mcs = get_mcs_from_somewhere()
> for i in
> glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/
> force_mcs'):
>     with open(i, 'w') as f:
>         print >>f, mcs

This assigns decimal value, how can I assign Hex here to mcs?
> 


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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Barry W Brown
On Nov 16, 10:54 am, Steve Ferg 
wrote:
> This is a question for the language mavens that I know hang out here.
> It is not Python related, except that recent comparisons of Python to
> Google's new Go language brought it to mind.
>
> NOTE that this is *not* a suggestion to change Python.  I like Python
> just the way it is.  I'm just curious about language design.
>
> For a long time I've wondered why languages still use blocks
> (delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.
>
> I've often thought that a language with this kind of block-free syntax
> would be nice and intuitive:
>
>     if  then
>         do stuff
>     elif  then
>         do stuff
>     else
>         do stuff
>     endif
>
> Note that you do not need block delimiters.
>
> Obviously, you could make a more Pythonesque syntax by using a colon
> rather then "then" for the condition terminator.  You could make it
> more PL/I-like by using "do", etc.
>
> You can write shell scripts using if ... fi, but other than that I
> don't recall a language with this kind of syntax.
>
> Does anybody know a language with this kind of syntax for
> ifThenElseEndif?
>
> Is there any particular reason why this might be a *bad* language-
> design idea?

Fortran95.  You can even label the IF...END IF structure -- handy for
immense blocks.

This is not a criticism of Python (or of Fortran).
-- 
http://mail.python.org/mailman/listinfo/python-list


mySQL access speed

2009-11-16 Thread Hans Müller
Hello,

I have some programs doing a lot sql IO in some mySQL databases.
This works very fine and the DBAPI is quite simple to understand.

Now I came to the point where I had to insert millions of lines into a table.
My first aproach was to insert the data using executemany().
That's not bad and fairly simple to use.
But it isn't very fast.
For executemany I have some hundred thousend lines in a list of tuples.
I joined() these lines to form an insert into table values () statement and
blew it into the mysql cmdline client via os.popen().
This was 60(!) times faster and loaded my table in seconds!

Is the mySQL module so slow ?

Any ideas to have the mySQL module working faster ?
The popen() way seems quite clumsy and not very pythonic for me,

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


Re: directory wildcard

2009-11-16 Thread Tim Chase

I try to assign value to force_mcs sitting in a wildcard
subdirectory /sys/kernel/debug/ieee80211/phy*, but python does
not work for that such as:

os.system("echo %i >
/sys/kernel/debug/ieee80211/phy*/iwlagn/data/force_mcs" % mcs)

Any right way to do it?


I'm not sure your code works if there's more than one phy* 
directory in that folder anyways since ">" piping usually only 
works for a single destination.  Though I'd imagine this is only 
a problem for folks that have more than one 802.11 card in their 
machine (which I've done...a useless on-board and a PCMCIA on an 
older laptop).


I'd use python's built-in glob module to do something like

  from glob import glob
  def set_force_mcs(mcs):
for fname in glob('/sys/kernel/debug/'
'ieee80211/phy*/iwlagn/data/force_mcs'):
  f = open(fname, 'w')
  f.write('%i\n' % mcs)
  f.close()
  #the following should all work
  set_force_mcs(True)
  set_force_mcs(False)
  set_force_mcs(1)
  set_force_mcs(0)

(I broke the for/glob line intentionally in a way that python 
transparently restores in case mailers munged them between here 
in there...normally, I'd just use a single string parameter for 
glob() instead of line-breaking it if it fit in 80 chars)


If you're using a more recent version of python that has the 
"with" command (I think it was added in 2.6, and available from 
2.5's future), it could be tidied to


  with open(fname, 'w') as f:
f.write('%i\n' % mcs)


-tkc


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


Re: IDE for python

2009-11-16 Thread Ben Finney
Jonathan Hartley  writes:

> I'd like to offer the group the anecdote of the great Resolver IDE
> migration.
[…]

It's great to see something refreshing and new — data beyond a single
person's subjective experience! — come out of a topic that looked like
it was just going to re-hash the same tired topic.

Thank you.

-- 
 \   “What I resent is that the range of your vision should be the |
  `\ limit of my action.” —Henry James |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the current directory (full post)

2009-11-16 Thread Dave Angel



Chris Rebert wrote:

On Mon, Nov 16, 2009 at 11:56 AM, vsoler  wrote:
  

On Nov 16, 8:45 pm, Chris Rebert  wrote:


On Mon, Nov 16, 2009 at 11:36 AM, vsoler  wrote:
  

On Nov 16, 2:35 am, "Gabriel Genellina" 
wrote:


En Sun, 15 Nov 2009 09:04:06 -0300, vsoler 
escribió:
  

Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
been saving my
*.py files in the C:\Program Files\Python26 directory, which is the
default directory for such files in my system.

However, I have realised that the above is not the best practice.

Therefore I created the C:\Program Files\Python26\test directory and I
want it to be my default directory for saving *.py files, importing
modules, etc.


This is *not* a good place either. Non-privileged users should not have
write permission in the C:\Program Files directory.
  

I'd like to do something like the DOS equivalent of   "CD test" but I
do not know kow to do it.

I am currently doing something really awful: I open a *.py file in the

test subdirectory, I run it with the F5 key and it works! but I am
doing really something stupid.


"it works!" What's the problem then?
  

How should I proceed, if I want to proceed properly?


Sorry but I don't even see your problem. You can save your .py files
anywhere you like...
  

When I enter IDLE, I'd like to say at the prompt: "my current
directory is...  ...test" and then be able to run a module in that
directory. This is what my problem is!!!


1. File -> Open
2. Navigate to file and choose it
3. Press F5
  

Say that you wanted to import a file in the test directory after just
entering IDLE. How would you do it?



import sys
sys.path.insert(0, "C:/path/to/test/dir/here")
import something_in_test_dir

Cheers,
Chris
--
http://blog.rebertia.com

  

Change directory to the test-directory
Then run idle


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


Re: Redirect stdout to a buffer [Errno 9]

2009-11-16 Thread Ecir Hana
On Nov 16, 7:21 pm, "Gabriel Genellina" 
wrote:
> En Mon, 16 Nov 2009 14:17:52 -0300, Ecir Hana   
> escribió:
>
> >> I'm trying to write a simple Win32 app, which may run some Python
> >> scripts. Since it is a Windows GUI app, I would like to redirect all
> >> output (Python print, C printf, fprinf stderr, ...) to a text area
> >> inside the app. In other words, I'm trying to log all the output from
> >> the app (C, Python) to a window. So far, this works for C printf():
> >> [...]
> >> PS: Maybe I'm doind something wrong, but SetStdHandle() does not work
> >> at all
>
> This worked for me:
>
> #include 
> #include "Python.h"
>
> int main()
> {
>    HANDLE hReadPipe, hWritePipe;
>    DWORD nr, nw;
>    char buffer[100];
>
>    CreatePipe(
>      &hReadPipe,
>      &hWritePipe,
>      NULL,
>      1024);
>    SetStdHandle(STD_OUTPUT_HANDLE, hWritePipe);
>
>    Py_Initialize();
>    PyRun_SimpleString("print 'from Python'");
>    Py_Finalize();
>
>    puts("from C\n");
>
>    CloseHandle(hWritePipe);
>    ReadFile(hReadPipe, buffer, 19, &nr, NULL);
>    CloseHandle(hReadPipe);
>    WriteFile(GetStdHandle(STD_ERROR_HANDLE), buffer, nr, &nw, NULL);
>
> }
> > Also, maybe this matters: it's on WinXP, Python 2.6 and MinGW GCC.
>
> I'm using Visual Studio 2008 Express Edition.
>
> --
> Gabriel Genellina

Hi,

thanks for the reply!

However, please, could you tell me how many bytes it read here:

ReadFile(hReadPipe, buffer, 19, &nr, NULL);

because for me, it has read 0. When I run your code, it prints from
both C and Python, but it prints straight to the console, not to the
buffer. Could you also please try to add:

WriteFile(GetStdHandle(STD_ERROR_HANDLE), "\n", 5, &nw, NULL);

before:

WriteFile(GetStdHandle(STD_ERROR_HANDLE), buffer, nr, &nw, NULL);

Does it print "" before "from Python" and "from C" for you?
Because for me it comes afterwards (as nr is 0)...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: directory wildcard

2009-11-16 Thread Jeff McNeil
On Nov 16, 3:33 pm, hong zhang  wrote:
> List,
>
> I try to assign value to force_mcs sitting in a wildcard subdirectory 
> /sys/kernel/debug/ieee80211/phy*, but python does not work for that such as:
>
> os.system("echo %i > /sys/kernel/debug/ieee80211/phy*/iwlagn/data/force_mcs" 
> % mcs)
>
> Any right way to do it?
>
> Thanks.
>
> --henry

I'd ditch the echo business altogether. 2.x. Not tested.

import glob

mcs = get_mcs_from_somewhere()
for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/
force_mcs'):
with open(i, 'w') as f:
print >>f, mcs

Thanks,

Jeff
mcjeff.blogspot.com

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


Re: directory wildcard

2009-11-16 Thread Diez B. Roggisch

hong zhang schrieb:

List,

I try to assign value to force_mcs sitting in a wildcard subdirectory 
/sys/kernel/debug/ieee80211/phy*, but python does not work for that such as:

os.system("echo %i > /sys/kernel/debug/ieee80211/phy*/iwlagn/data/force_mcs" % 
mcs)

Any right way to do it?


Don't use os system. Use subprocess. Which incidentially is mentioned in 
the docs for os.system:


  http://docs.python.org/library/os.html#os.system

Then you can pass the "use_shell=True" parameter - which should work in 
your case.


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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Robert Kern

On 2009-11-16 14:40 PM, Edward A. Falk wrote:

In article,
Steve Ferg  wrote:

I've often thought that a language with this kind of block-free syntax
would be nice and intuitive:

if  then
do stuff
elif  then
do stuff
else
do stuff
endif

Note that you do not need block delimiters.


"then", "else", and "endif" *are* the block delimiters


I think he meant that you don't need *extra* block delimiters or generic block 
delimiters like {}.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Edward A. Falk
In article ,
Steve Ferg   wrote:
>I've often thought that a language with this kind of block-free syntax
>would be nice and intuitive:
>
>if  then
>do stuff
>elif  then
>do stuff
>else
>do stuff
>endif
>
>Note that you do not need block delimiters.

"then", "else", and "endif" *are* the block delimiters

-- 
-Ed Falk, f...@despams.r.us.com
http://thespamdiaries.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


directory wildcard

2009-11-16 Thread hong zhang
List,

I try to assign value to force_mcs sitting in a wildcard subdirectory 
/sys/kernel/debug/ieee80211/phy*, but python does not work for that such as:

os.system("echo %i > /sys/kernel/debug/ieee80211/phy*/iwlagn/data/force_mcs" % 
mcs)

Any right way to do it?

Thanks.

--henry




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


Re: Web servers

2009-11-16 Thread Dave Angel



Virgil Stokes wrote:
Any 
suggestions on using Python to connect to Web servers (e.g. to access 
financial time series data)?


--V. Stokes



You can open a web page for reading with  urllib2 module.  You can parse 
html with beautiful soup, or if it's clean xhtml, with the xml module.


But parsing raw html is error prone, and subject to change as the web 
designer reorganizes things.  So many web servers also have a protocol 
intended for data (as opposed to intended for a browser).  This is 
specific to each service, however.  If you want to get started in your 
reading, you could google for "web services", which is one approach 
using SOAP & WSDL.


Note also that most servers have restrictions on the data you access 
this way.  They may or may not be enforceable, but if you access a lot 
of data from a server, you may be too big a drain on its resources, if 
it's configured for browser access only.


DaveA

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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread r
On Nov 16, 10:54 am, Steve Ferg 
wrote:

> I've often thought that a language with this kind of block-free syntax
> would be nice and intuitive:
>
>     if  then
>         do stuff
>     elif  then
>         do stuff
>     else
>         do stuff
>     endif

WHY? Python's syntax is by far the most elegant of all, no need to
show the end of a block. Python is the smartest kid on the block. And
are you saying you would rather type "then" instead of ":" and "endif"
instead of "\n"?

No thanks!

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


Re: Changing the current directory (full post)

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 11:56 AM, vsoler  wrote:
> On Nov 16, 8:45 pm, Chris Rebert  wrote:
>> On Mon, Nov 16, 2009 at 11:36 AM, vsoler  wrote:
>> > On Nov 16, 2:35 am, "Gabriel Genellina" 
>> > wrote:
>> >> En Sun, 15 Nov 2009 09:04:06 -0300, vsoler 
>> >> escribió:
>>
>> >> > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
>> >> > been saving my
>> >> > *.py files in the C:\Program Files\Python26 directory, which is the
>> >> > default directory for such files in my system.
>>
>> >> > However, I have realised that the above is not the best practice.
>> >> > Therefore I created the C:\Program Files\Python26\test directory and I
>> >> > want it to be my default directory for saving *.py files, importing
>> >> > modules, etc.
>>
>> >> This is *not* a good place either. Non-privileged users should not have
>> >> write permission in the C:\Program Files directory.
>>
>> >> > I'd like to do something like the DOS equivalent of   "CD test" but I
>> >> > do not know kow to do it.
>>
>> >> > I am currently doing something really awful: I open a *.py file in the
>> >> > test subdirectory, I run it with the F5 key and it works! but I am
>> >> > doing really something stupid.
>>
>> >> "it works!" What's the problem then?
>>
>> >> > How should I proceed, if I want to proceed properly?
>>
>> >> Sorry but I don't even see your problem. You can save your .py files
>> >> anywhere you like...
>>
>> > When I enter IDLE, I'd like to say at the prompt: "my current
>> > directory is...  ...test" and then be able to run a module in that
>> > directory. This is what my problem is!!!
>>
>> 1. File -> Open
>> 2. Navigate to file and choose it
>> 3. Press F5
>
> Say that you wanted to import a file in the test directory after just
> entering IDLE. How would you do it?

import sys
sys.path.insert(0, "C:/path/to/test/dir/here")
import something_in_test_dir

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the current directory (full post)

2009-11-16 Thread Rami Chowdhury

On Mon, 16 Nov 2009 11:56:49 -0800, vsoler  wrote:


On Nov 16, 8:45 pm, Chris Rebert  wrote:
On Mon, Nov 16, 2009 at 11:36 AM, vsoler   
wrote:

> On Nov 16, 2:35 am, "Gabriel Genellina" 
> wrote:
>> En Sun, 15 Nov 2009 09:04:06 -0300, vsoler 
>> escribió:

>> > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
>> > been saving my
>> > *.py files in the C:\Program Files\Python26 directory, which is the
>> > default directory for such files in my system.

>> > However, I have realised that the above is not the best practice.
>> > Therefore I created the C:\Program Files\Python26\test directory  
and I

>> > want it to be my default directory for saving *.py files, importing
>> > modules, etc.

>> This is *not* a good place either. Non-privileged users should not  
have

>> write permission in the C:\Program Files directory.

>> > I'd like to do something like the DOS equivalent of   "CD test"  
but I

>> > do not know kow to do it.

>> > I am currently doing something really awful: I open a *.py file in  
the

>> > test subdirectory, I run it with the F5 key and it works! but I am
>> > doing really something stupid.

>> "it works!" What's the problem then?

>> > How should I proceed, if I want to proceed properly?

>> Sorry but I don't even see your problem. You can save your .py files
>> anywhere you like...

>> --
>> Gabriel Genellina

> Gabriel,

> When I enter IDLE, I'd like to say at the prompt: "my current
> directory is...  ...test" and then be able to run a module in that
> directory. This is what my problem is!!!

1. File -> Open
2. Navigate to file and choose it
3. Press F5

Cheers,
Chris
--http://blog.rebertia.com


Say that you wanted to import a file in the test directory after just
entering IDLE. How would you do it?


http://docs.python.org/library/os.html#os.chdir and  
http://docs.python.org/library/sys.html#sys.path may be able to help you...




--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the current directory (full post)

2009-11-16 Thread vsoler
On Nov 16, 8:45 pm, Chris Rebert  wrote:
> On Mon, Nov 16, 2009 at 11:36 AM, vsoler  wrote:
> > On Nov 16, 2:35 am, "Gabriel Genellina" 
> > wrote:
> >> En Sun, 15 Nov 2009 09:04:06 -0300, vsoler 
> >> escribió:
>
> >> > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
> >> > been saving my
> >> > *.py files in the C:\Program Files\Python26 directory, which is the
> >> > default directory for such files in my system.
>
> >> > However, I have realised that the above is not the best practice.
> >> > Therefore I created the C:\Program Files\Python26\test directory and I
> >> > want it to be my default directory for saving *.py files, importing
> >> > modules, etc.
>
> >> This is *not* a good place either. Non-privileged users should not have
> >> write permission in the C:\Program Files directory.
>
> >> > I'd like to do something like the DOS equivalent of   "CD test" but I
> >> > do not know kow to do it.
>
> >> > I am currently doing something really awful: I open a *.py file in the
> >> > test subdirectory, I run it with the F5 key and it works! but I am
> >> > doing really something stupid.
>
> >> "it works!" What's the problem then?
>
> >> > How should I proceed, if I want to proceed properly?
>
> >> Sorry but I don't even see your problem. You can save your .py files
> >> anywhere you like...
>
> >> --
> >> Gabriel Genellina
>
> > Gabriel,
>
> > When I enter IDLE, I'd like to say at the prompt: "my current
> > directory is...  ...test" and then be able to run a module in that
> > directory. This is what my problem is!!!
>
> 1. File -> Open
> 2. Navigate to file and choose it
> 3. Press F5
>
> Cheers,
> Chris
> --http://blog.rebertia.com

Say that you wanted to import a file in the test directory after just
entering IDLE. How would you do it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the current directory (full post)

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 11:36 AM, vsoler  wrote:
> On Nov 16, 2:35 am, "Gabriel Genellina" 
> wrote:
>> En Sun, 15 Nov 2009 09:04:06 -0300, vsoler 
>> escribió:
>>
>> > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
>> > been saving my
>> > *.py files in the C:\Program Files\Python26 directory, which is the
>> > default directory for such files in my system.
>>
>> > However, I have realised that the above is not the best practice.
>> > Therefore I created the C:\Program Files\Python26\test directory and I
>> > want it to be my default directory for saving *.py files, importing
>> > modules, etc.
>>
>> This is *not* a good place either. Non-privileged users should not have
>> write permission in the C:\Program Files directory.
>>
>> > I'd like to do something like the DOS equivalent of   "CD test" but I
>> > do not know kow to do it.
>>
>> > I am currently doing something really awful: I open a *.py file in the
>> > test subdirectory, I run it with the F5 key and it works! but I am
>> > doing really something stupid.
>>
>> "it works!" What's the problem then?
>>
>> > How should I proceed, if I want to proceed properly?
>>
>> Sorry but I don't even see your problem. You can save your .py files
>> anywhere you like...
>>
>> --
>> Gabriel Genellina
>
> Gabriel,
>
> When I enter IDLE, I'd like to say at the prompt: "my current
> directory is...  ...test" and then be able to run a module in that
> directory. This is what my problem is!!!

1. File -> Open
2. Navigate to file and choose it
3. Press F5

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the current directory (full post)

2009-11-16 Thread vsoler
On Nov 16, 2:35 am, "Gabriel Genellina" 
wrote:
> En Sun, 15 Nov 2009 09:04:06 -0300, vsoler 
> escribió:
>
> > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
> > been saving my
> > *.py files in the C:\Program Files\Python26 directory, which is the
> > default directory for such files in my system.
>
> > However, I have realised that the above is not the best practice.
> > Therefore I created the C:\Program Files\Python26\test directory and I
> > want it to be my default directory for saving *.py files, importing
> > modules, etc.
>
> This is *not* a good place either. Non-privileged users should not have
> write permission in the C:\Program Files directory.
>
> > I'd like to do something like the DOS equivalent of   "CD test" but I
> > do not know kow to do it.
>
> > I am currently doing something really awful: I open a *.py file in the
> > test subdirectory, I run it with the F5 key and it works! but I am
> > doing really something stupid.
>
> "it works!" What's the problem then?
>
> > How should I proceed, if I want to proceed properly?
>
> Sorry but I don't even see your problem. You can save your .py files  
> anywhere you like...
>
> --
> Gabriel Genellina

Gabriel,

When I enter IDLE, I'd like to say at the prompt: "my current
directory is...  ...test" and then be able to run a module in that
directory. This is what my problem is!!!

Thank you if you can help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web servers

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 11:17 AM, Virgil Stokes  wrote:
> Any suggestions on using Python to connect to Web servers (e.g. to access
> financial time series data)?

In what format? Using what protocol?
(*Insert other basic questions that need answering in order to answer
your question here*)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 8:54 AM, Steve Ferg
 wrote:
> This is a question for the language mavens that I know hang out here.
> It is not Python related, except that recent comparisons of Python to
> Google's new Go language brought it to mind.
>
> NOTE that this is *not* a suggestion to change Python.  I like Python
> just the way it is.  I'm just curious about language design.
>
> For a long time I've wondered why languages still use blocks
> (delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.
>
> I've often thought that a language with this kind of block-free syntax
> would be nice and intuitive:
>
>    if  then
>        do stuff
>    elif  then
>        do stuff
>    else
>        do stuff
>    endif
>
> Note that you do not need block delimiters.

> Does anybody know a language with this kind of syntax for
> ifThenElseEndif?

Ruby:

if count > 10
  puts "Try again"
elsif tries == 3
  puts "You lose"
else
  puts "Enter a number"
end

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Web servers

2009-11-16 Thread Virgil Stokes
Any suggestions on using Python to connect to Web servers (e.g. to 
access financial time series data)?


--V. Stokes

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


Re: A "terminators' club" for clp

2009-11-16 Thread gil_johnson
On Nov 14, 12:08 pm, r  wrote:
> On Nov 14, 7:28 am, gil_johnson  wrote:

> Actually there is a "rank this post" (gotta be careful with that
> verbage!) AND a "report this post as spam". Of course it only exists
> in GG's and not Usenet. I *do* know that the star system is used quite
> frequently, but i doubt anyone bothers to use the "report as spam"
> link since it seems have no effect whatsoever.

Heh. I should look around more before posting. It does prove your
point, though. The 'spam' button is ubiquitous, but so seldom used
it's forgotten.

Actually, my enthusiasm for my idea faded with a little thought. It is
an extra effort to open spam to get to the 'spam' button, and sends
the message to the spammer that people are, indeed opening their junk.
I'd use it if I opened a message with a deceptive subject.
Gil

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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread MRAB

Nobody wrote:

On Mon, 16 Nov 2009 08:54:28 -0800, Steve Ferg wrote:


For a long time I've wondered why languages still use blocks
(delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.

I've often thought that a language with this kind of block-free syntax
would be nice and intuitive:

if  then
do stuff
elif  then
do stuff
else
do stuff
endif

Note that you do not need block delimiters.



Does anybody know a language with this kind of syntax for
ifThenElseEndif? 


BBC BASIC V had if/then/else/endif (it didn't have elif).


I forgot about that one. :-(

I used to do this in order if I wanted to avoid a lot of indentation:

CASE TRUE OF
WHEN 
do something
WHEN 
do something
OTHERWISE
do something
ENDCASE


"make" has if/else/else/endif (it doesn't have a dedicated elif, but
"else if ..." behaves like elif rather than starting a nested "if").


Is there any particular reason why this might be a *bad* language-
design idea?


Blocks can be useful for other reasons (e.g. limiting variable scope), so
if you already have them, you don't need to provide dedicated blocks
for control constructs.



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


Re: overriding __getitem__ for a subclass of dict

2009-11-16 Thread Steve Howell
On Nov 16, 2:35 am, Carl Banks  wrote:
> On Nov 15, 2:52 pm, Steve Howell  wrote:
>
> > Does anybody have any links that points to the rationale for ignoring
> > instance definitions of __getitem__ when new-style classes are
> > involved?  I assume it has something to do with performance or
> > protecting us from our own mistakes?
>
> "Not important enough to justify complexity of implementation."
>
> I doubt they would have left if out of new-style classes if it had
> been straightforward to implement (if for no other reason than to
> retain backwards compatibility), but it wasn't.  The way attribute
> lookups work meant it would have required all kinds of double lookups
> and edge cases.  Some regarded it as dubious to begin with.  And it's
> easily worked around by simply having __getitem__ call another method,
> as you've seen.  Given all this it made better sense to just leave it
> out of new-style classes.

Actually, the __getitem__ workaround that I proposed earlier only
works on subclasses of dict, not dict themselves.  So given a pure
dictionary object, it is impossible to hook into attribute lookups
after instantiation in debugging/tracing code.  I know it's not a
super common thing to do, but it is a legitimate use case from my
perspective.  But I understand the tradeoffs.  They seem kind of 20th
century to me, but with Moore's Law declining and all, maybe it's a
bad time to bring up the "flexibility trumps performance"
argument. ;)  The backward compatibility argument also seems a little
dubious, because if anybody *had* put __getitem__ on a dictionary
instance before, it would have already been broken code, and if they
hadn't done it, there would be no semantic change, just a performance
hit, albeit a pervasive one.

> Unfortunately not all such decisions and justifications are collected
> in a tidy place.
>

Yep, that's why I was asking here.  I figured somebody might remember
a thread on python-dev where this was discussed, or something like
that.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: tkFileDialog question

2009-11-16 Thread Matt Mitchell



 
---
The information contained in this electronic message and any attached 
document(s) is intended only for the personal and confidential use of the 
designated recipients named above. This message may be confidential. If the 
reader of this message is not the intended recipient, you are hereby notified 
that you have received this document in error, and that any review, 
dissemination, distribution, or copying of this message is strictly prohibited. 
If you have received this communication in error, please notify sender 
immediately by telephone (603) 262-6300 or by electronic mail immediately. 
Thank you.
 
-Original Message-
From: python-list-bounces+mmitchell=transparent@python.org
[mailto:python-list-bounces+mmitchell=transparent@python.org] On
Behalf Of r
Sent: Monday, November 16, 2009 12:16 AM
To: python-list@python.org
Subject: Re: tkFileDialog question

Matt,

There is also a nice thing you need to know about Python if you
already do not know. That is the fact that all empty collections bool
to False. This makes Truth testing easier.

>>> bool([])
False
>>> bool('')
False
>>> bool({})
False
>>> bool([1])
True
>>> bool([[]])
True
>>> bool(' ')
True

any empty collection, string, or 0 always bools to False.
-- 
http://mail.python.org/mailman/listinfo/python-list



Thank you both for all the help.  Your suggestions have helped clean up
a bunch of my code.

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


Re: Redirect stdout to a buffer [Errno 9]

2009-11-16 Thread Gabriel Genellina
En Mon, 16 Nov 2009 14:17:52 -0300, Ecir Hana   
escribió:



I'm trying to write a simple Win32 app, which may run some Python
scripts. Since it is a Windows GUI app, I would like to redirect all
output (Python print, C printf, fprinf stderr, ...) to a text area
inside the app. In other words, I'm trying to log all the output from
the app (C, Python) to a window. So far, this works for C printf():
[...]
PS: Maybe I'm doind something wrong, but SetStdHandle() does not work
at all


This worked for me:

#include 
#include "Python.h"

int main()
{
  HANDLE hReadPipe, hWritePipe;
  DWORD nr, nw;
  char buffer[100];

  CreatePipe(
&hReadPipe,
&hWritePipe,
NULL,
1024);
  SetStdHandle(STD_OUTPUT_HANDLE, hWritePipe);

  Py_Initialize();
  PyRun_SimpleString("print 'from Python'");
  Py_Finalize();

  puts("from C\n");

  CloseHandle(hWritePipe);
  ReadFile(hReadPipe, buffer, 19, &nr, NULL);
  CloseHandle(hReadPipe);
  WriteFile(GetStdHandle(STD_ERROR_HANDLE), buffer, nr, &nw, NULL);
}


Also, maybe this matters: it's on WinXP, Python 2.6 and MinGW GCC.


I'm using Visual Studio 2008 Express Edition.

--
Gabriel Genellina

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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Nobody
On Mon, 16 Nov 2009 08:54:28 -0800, Steve Ferg wrote:

> For a long time I've wondered why languages still use blocks
> (delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.
> 
> I've often thought that a language with this kind of block-free syntax
> would be nice and intuitive:
> 
> if  then
> do stuff
> elif  then
> do stuff
> else
> do stuff
> endif
> 
> Note that you do not need block delimiters.

> Does anybody know a language with this kind of syntax for
> ifThenElseEndif? 

BBC BASIC V had if/then/else/endif (it didn't have elif).

"make" has if/else/else/endif (it doesn't have a dedicated elif, but
"else if ..." behaves like elif rather than starting a nested "if").

> Is there any particular reason why this might be a *bad* language-
> design idea?

Blocks can be useful for other reasons (e.g. limiting variable scope), so
if you already have them, you don't need to provide dedicated blocks
for control constructs.

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


Re: Image to SVG conversion with Python

2009-11-16 Thread Nobody
On Mon, 16 Nov 2009 07:19:49 -0800, Carlo DiCelico wrote:

> I need to convert JPEG and PNG files to SVG. I'm currently using PIL
> to generate the JPEG/PNG files to begin with. However, I need to be
> able to scale the generated images up in size without a loss of image
> quality. Using SVG seems to be the best way to do this, other than
> generating the images in the maximum size/resolution in the first
> place, which would be too resource intensive.
> 
> I've looked around online and have found some tools for creating SVGs
> but none for converting an image into SVG.
> 
> Does anyone have any experience doing this? What would be the best way
> to go about this?

JPEG/PNG are raster formats, SVG is a vector format.

To convert raster graphics to vector graphics, you need a "tracing"
program (aka "image tracing", "vector tracing", "vectorizing"), e.g.
potrace (this program is often bundled with InkScape):

http://potrace.sourceforge.net/

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


Re: import subprocess in python

2009-11-16 Thread Nobody
On Mon, 16 Nov 2009 04:58:00 -0800, sturlamolden wrote:

> On 16 Nov, 13:50, Kuhl  wrote:
> 
>> Python 2.2.3 (#1, Feb  2 2005, 12:22:48)
> 
>> What's the mistake that I am making? How to solve it?
> 
> Your Python version is too old.

Your Python version is *way* too old.

If you're lucky, people who use features of Python 2.5 or 2.6 will mention
that you need Python 2.5 or 2.6, but having at least Python 2.4 is
generally taken for granted.

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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Robin Becker

Robin Becker wrote:
...

modern sh seems to use this with "fi" as endif eg

~:
$ if true; then
 > echo true
 > elif false; then
 > echo false
 > else
 > echo hostile logic
 > fi
true
~:
$



I meant to say that since sh uses this construct it cannot be too bad as a 
language construct since the world is built with sh and bash and similar.


Of course that's a bad argument since there's more cobol than everything else 
put together (allegedly).

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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread MRAB

Steve Ferg wrote:

This is a question for the language mavens that I know hang out here.
It is not Python related, except that recent comparisons of Python to
Google's new Go language brought it to mind.

NOTE that this is *not* a suggestion to change Python.  I like Python
just the way it is.  I'm just curious about language design.

For a long time I've wondered why languages still use blocks
(delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.

I've often thought that a language with this kind of block-free syntax
would be nice and intuitive:

if  then
do stuff
elif  then
do stuff
else
do stuff
endif

Note that you do not need block delimiters.

Obviously, you could make a more Pythonesque syntax by using a colon
rather then "then" for the condition terminator.  You could make it
more PL/I-like by using "do", etc.

You can write shell scripts using if ... fi, but other than that I
don't recall a language with this kind of syntax.

Does anybody know a language with this kind of syntax for
ifThenElseEndif?

Is there any particular reason why this might be a *bad* language-
design idea?


Ada and Turing have:

if  then
do stuff
elsif  then
do stuff
else
do stuff
end if

Comal has:

if  then
do stuff
elif  then
do stuff
else
do stuff
end if

Modula-2 has:

if  then
do stuff
elsif  then
do stuff
else
do stuff
end
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newsgroup for beginners

2009-11-16 Thread George Oliver
On Nov 16, 8:35 am, Terry Reedy  wrote:
> mrholtsr wrote:
> > Is there a Python newsgroup for those who are strictly beginners at
> > programming and python?
>
> gmane.comp.python.tutor, which I believe mirrors the tutor-list

There also is a beginner's forum at python-forum.org:

http://www.python-forum.org/pythonforum/viewforum.php?f=3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Redirect stdout to a buffer [Errno 9]

2009-11-16 Thread Ecir Hana
On Nov 15, 5:28 pm, Ecir Hana  wrote:
> Hello,
>
> I'm trying to write a simple Win32 app, which may run some Python
> scripts. Since it is a Windows GUI app, I would like to redirect all
> output (Python print, C printf, fprinf stderr, ...) to a text area
> inside the app. In other words, I'm trying to log all the output from
> the app (C, Python) to a window. So far, this works for C printf():
>
> int fds[2];
> _pipe(fds, 1024, O_TEXT);
> _dup2(fds[1], 1);
> ...
> and then I read from pipe's read-end and append the text to the text
> area.
>
> But when I try to run:
> Py_Initialize();
> PyRun_SimpleString("print 'abc'");
> Py_Finalize();
>
> I get an error:
> IOError: [Errno 9] Bad file descriptor
>
> What am I doing wrong? How to redirect standard IO, both for C and for
> Python?
> PS: Maybe I'm doind something wrong, but SetStdHandle() does not work
> at all

Also, maybe this matters: it's on WinXP, Python 2.6 and MinGW GCC.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Adrian Cherry
Steve Ferg  wrote in
news:ff92db5b-9cb0-4a72-b339-2c5ac02fb...@p36g2000vbn.googlegro
ups.com: 

> This is a question for the language mavens that I know hang
> out here. It is not Python related, except that recent
> comparisons of Python to Google's new Go language brought it
> to mind. 
> 
> NOTE that this is *not* a suggestion to change Python.  I
> like Python just the way it is.  I'm just curious about
> language design. 
> 
> For a long time I've wondered why languages still use blocks
> (delimited by do/end, begin/end, { } , etc.) in ifThenElse
> statements. 
> 
> I've often thought that a language with this kind of
> block-free syntax would be nice and intuitive:
> 
> if  then
> do stuff
> elif  then
> do stuff
> else
> do stuff
> endif
> 
> Note that you do not need block delimiters.
> 
> Obviously, you could make a more Pythonesque syntax by using
> a colon rather then "then" for the condition terminator. 
> You could make it more PL/I-like by using "do", etc.
> 
> You can write shell scripts using if ... fi, but other than
> that I don't recall a language with this kind of syntax.
> 
> Does anybody know a language with this kind of syntax for
> ifThenElseEndif?
> 
> Is there any particular reason why this might be a *bad*
> language- design idea?

I believe MATLAB has similar if syntax - please correct me if I'm 
wrong.

From

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.html

"The if function can be used alone or with the else and elseif 
functions. When using elseif and/or else within an if statement, 
the general form of the statement is"

if expression1
statements1
elseif expression2
statements2
else
statements3
end


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


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread James Harris
On 16 Nov, 16:54, Steve Ferg  wrote:
> This is a question for the language mavens that I know hang out here.
> It is not Python related, except that recent comparisons of Python to
> Google's new Go language brought it to mind.
>
> NOTE that this is *not* a suggestion to change Python.  I like Python
> just the way it is.  I'm just curious about language design.
>
> For a long time I've wondered why languages still use blocks
> (delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.
>
> I've often thought that a language with this kind of block-free syntax
> would be nice and intuitive:
>
>     if  then
>         do stuff
>     elif  then
>         do stuff
>     else
>         do stuff
>     endif
>
> Note that you do not need block delimiters.
>
> Obviously, you could make a more Pythonesque syntax by using a colon
> rather then "then" for the condition terminator.  You could make it
> more PL/I-like by using "do", etc.
>
> You can write shell scripts using if ... fi, but other than that I
> don't recall a language with this kind of syntax.
>
> Does anybody know a language with this kind of syntax for
> ifThenElseEndif?
>
> Is there any particular reason why this might be a *bad* language-
> design idea?

There are some. For example, Ada uses similar. See

  http://en.wikipedia.org/wiki/Ada_%28programming_language%29#Control_structures

These other newsgroups may be of interest:

  comp.programming
  comp.lang.misc

The latter is used by people designing programming languages where you
can find knowledgeable comments aplenty.

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


Re: Image to SVG conversion with Python

2009-11-16 Thread Carlo DiCelico
On Nov 16, 11:48 am, Dave Angel  wrote:
> Carlo DiCelico wrote:
> > I need to convert JPEG and PNG files to SVG. I'm currently using PIL
> > to generate the JPEG/PNG files to begin with. However, I need to be
> > able to scale the generated images up in size without a loss of image
> > quality. Using SVG seems to be the best way to do this, other than
> > generating the images in the maximum size/resolution in the first
> > place, which would be too resource intensive.
>
> > I've looked around online and have found some tools for creating SVGs
> > but none for converting an image into SVG.
>
> > Does anyone have any experience doing this? What would be the best way
> > to go about this?
>
> > Thanks,
> > Carlo
>
> I have no direct experience with SVG, but have used and analyzed other
> formats.
>
> I expect it's unreasonable to convert jpg or png files to SVG.  The
> latter is a vector format, and can't efficiently represent pixels, which
> is all you have in the jpg files.  And even if you did it brute force,
> it still wouldn't scale any better than the original jpg.  If the jpg
> file was generated from lines, and wasn't too crowded, it *might* be
> possible to analyze it to reconstruct the vectors, but it would be both
> very slow, and inaccurate.
>
> In Photoshop PSD files, you can have vector layers and RGB layers (plus
> other kinds).  You convert a vector layer (such as text) to bits by
> rasterizing (or flattening).  And once you do, it no longer scales
> cleanly.  For instance, when I'm sending composite images to a printer,
> I get much better quality sending the raster portion separate from the
> text, either as layers in a PSD file, or in a PDF file, or even as two
> separate files that they will merge later.  (In that case, I usually
> send a low-res flattened file, so they can see how it's supposed to look)
>
> I'd say you should change your python code to generate the svg files
> first (perhaps usinghttp://code.activestate.com/recipes/325823/)
>
> Then you might want to use (http://www.imagemagick.org/script/index.php
> ) to convert it to jpg or other format.
>
> DaveA

Thanks, this makes perfect sense.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Robin Becker

Steve Ferg wrote:
.


if  then
do stuff
elif  then
do stuff
else
do stuff
endif

Note that you do not need block delimiters.

Obviously, you could make a more Pythonesque syntax by using a colon
rather then "then" for the condition terminator.  You could make it
more PL/I-like by using "do", etc.

You can write shell scripts using if ... fi, but other than that I
don't recall a language with this kind of syntax.

Does anybody know a language with this kind of syntax for
ifThenElseEndif?

...

modern sh seems to use this with "fi" as endif eg

~:
$ if true; then
> echo true
> elif false; then
> echo false
> else
> echo hostile logic
> fi
true
~:
$

--
Robin Becker

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


Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-16 Thread Steve Ferg
This is a question for the language mavens that I know hang out here.
It is not Python related, except that recent comparisons of Python to
Google's new Go language brought it to mind.

NOTE that this is *not* a suggestion to change Python.  I like Python
just the way it is.  I'm just curious about language design.

For a long time I've wondered why languages still use blocks
(delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.

I've often thought that a language with this kind of block-free syntax
would be nice and intuitive:

if  then
do stuff
elif  then
do stuff
else
do stuff
endif

Note that you do not need block delimiters.

Obviously, you could make a more Pythonesque syntax by using a colon
rather then "then" for the condition terminator.  You could make it
more PL/I-like by using "do", etc.

You can write shell scripts using if ... fi, but other than that I
don't recall a language with this kind of syntax.

Does anybody know a language with this kind of syntax for
ifThenElseEndif?

Is there any particular reason why this might be a *bad* language-
design idea?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Image to SVG conversion with Python

2009-11-16 Thread Dave Angel

Carlo DiCelico wrote:

I need to convert JPEG and PNG files to SVG. I'm currently using PIL
to generate the JPEG/PNG files to begin with. However, I need to be
able to scale the generated images up in size without a loss of image
quality. Using SVG seems to be the best way to do this, other than
generating the images in the maximum size/resolution in the first
place, which would be too resource intensive.

I've looked around online and have found some tools for creating SVGs
but none for converting an image into SVG.

Does anyone have any experience doing this? What would be the best way
to go about this?

Thanks,
Carlo

  
I have no direct experience with SVG, but have used and analyzed other 
formats.


I expect it's unreasonable to convert jpg or png files to SVG.  The 
latter is a vector format, and can't efficiently represent pixels, which 
is all you have in the jpg files.  And even if you did it brute force, 
it still wouldn't scale any better than the original jpg.  If the jpg 
file was generated from lines, and wasn't too crowded, it *might* be 
possible to analyze it to reconstruct the vectors, but it would be both 
very slow, and inaccurate.



In Photoshop PSD files, you can have vector layers and RGB layers (plus 
other kinds).  You convert a vector layer (such as text) to bits by 
rasterizing (or flattening).  And once you do, it no longer scales 
cleanly.  For instance, when I'm sending composite images to a printer, 
I get much better quality sending the raster portion separate from the 
text, either as layers in a PSD file, or in a PDF file, or even as two 
separate files that they will merge later.  (In that case, I usually 
send a low-res flattened file, so they can see how it's supposed to look)


I'd say you should change your python code to generate the svg files 
first (perhaps using http://code.activestate.com/recipes/325823/ )


Then you might want to use ( http://www.imagemagick.org/script/index.php 
) to convert it to jpg or other format.


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


Re: Newsgroup for beginners

2009-11-16 Thread Terry Reedy

mrholtsr wrote:

Is there a Python newsgroup for those who are strictly beginners at
programming and python?


gmane.comp.python.tutor, which I believe mirrors the tutor-list

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


Re: A "terminators' club" for clp

2009-11-16 Thread Terry Reedy

kj wrote:

In <7x3a4i56u7@ruckus.brouhaha.com> Paul Rubin 
 writes:


kj  writes:

frequent* clp posters the ability to *easily* delete spam from the
comp.lang.python server?



Um, this is usenet; there is no comp.lang.python server.  Are you
saying you want a moderated newsgroup?  Hmm, maybe this group is busy
enough that there is some merit to that idea.


Sorry, I had a mistaken view of how usenet was implemented.  But
yeah, I guess I'm thinking of a moderated newsgroup, but with a
large number of moderators working in parallel, and a very lax
acceptance policy.  The goal is to filter out only the obvious
spam, and let through all the other non-spam traffic as quickly as
possible...  What do I mean by "obvious spam"?  Well, among the
most recent messages (that have survived my killfile policies) I
see the following subject lines:

* Top 10 US mp3 songs.Cheers
* www.find68.com cheaper nike shoes g-satr kidrobot hoodies ed hardy star red 
monkey gino green global true religion ed-hardy kidrobot jeans hoodies china 
supplier wholesaler exporters,manufacture
* "jobs in france" "jobs in france for english people" "jobs in france for foreigners" "jobs in france for australians" 
"jobs in france for foreigners " "jobs in france for new zealanders" "jobs" "paris jobs" http://jobs-in-fr 
ance.blogspot.com/
* "germany jobs" "germany job sites" "germany job search" "jobs in germany" "german jobs" "germany jobs it" 
"germany jobs for foreigners" "germany jobsite" "germany jobs in english" on http://jobs-germany.blogspot.com/

Those look pretty obvious to me.

But, as I already showed, I'm out of my depth here,
so I'd better shut up.


Some usenet newsgroups were/are moderated either by a robot, a person, 
or a team (as you suggested). But a particular newsgroup has to be set 
up that way from the beginning. Last I knew, it wan/is? difficult to 
convert an unmoderated group to moderation.


Terry Jan Reedy

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


Re: (unknown)

2009-11-16 Thread Gabriel Genellina

En Mon, 16 Nov 2009 11:11:20 -0300, Tommy Grav  escribió:

On Nov 15, 2009, at 11:08 AM, Gabriel Genellina wrote:


En Fri, 13 Nov 2009 16:05:26 -0300, Ronn Ross   
escribió:


I'm attempting to convert latitude and longitude coordinates from  
degrees

minutes and second to decimal form. I would like to go from:
   N39 42 36.3 W77 42 51.5
to:
-77.739855,39.70


decimal = degrees + minutes/60.0 + seconds/3600.0
N,E are positive; S,W are negative.
But the above numbers don't match.


It is more complicated than that. For negative numbers the value is  
degrees -minutes/60. - seconds/3600.

And people always trip up on numbers that start with -00 :)


I set the sign of the result *after* computing it, so it doesn't matter.

py> 39 + 42/60.0 + 36.3/3600
39.7100837
py> 77 + 42/60.0 + 51.5/3600
77.7143055

Either the example above is incorrect, or there is another thing involved.

--
Gabriel Genellina

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


Python-URL! - weekly Python news and links (Nov 16)

2009-11-16 Thread Gabriel Genellina
QOTW:  "The promise is 'batteries included.'  Nobody promised you a
nickel metal hydride battery that you can use as a replacement in your
Prius." - Stephen J. Turnbull
http://mail.python.org/pipermail/python-dev/2009-November/094014.html


Google's new language, Go, has similarities to Python:
http://groups.google.com/group/comp.lang.python/t/c1c4a8fe741c689a/

Is Python scalable enough for Google (or any other huge application)?
http://groups.google.com/group/comp.lang.python/t/ceef2ae6b4472b61/

Is it possible to get the physical memory address of a variable in python?
http://groups.google.com/group/comp.lang.python/t/969462b9a3b452/

Serialize objects as Python code:
http://groups.google.com/group/comp.lang.python/t/98536e7910e65256/

Overriding __getitem__ for a subclass of dict:
http://groups.google.com/group/comp.lang.python/t/d9b822119fc0917c/

Ensure a script is run with a certain range of Python versions:
http://groups.google.com/group/comp.lang.python/t/d21a492be99c90e8/

How to install applications when Python is not already present:
http://groups.google.com/group/comp.lang.python/t/495794a40d18fbc/

Turtle graphics are just for kids - or not? Its advantages when teaching
Python programming:
http://groups.google.com/group/comp.lang.python/t/d55388b0fdd9ed2f/

Using dynamic property names:
http://groups.google.com/group/comp.lang.python/t/f7b8829c97dcc3f9/

How can a module react differently when imported from one place or another?
http://groups.google.com/group/comp.lang.python/t/da162dc08f1c3550/

Sharing distributed objects between Python and C++:
http://groups.google.com/group/comp.lang.python/t/5a567a1a180511eb/

Beware: threads + import don't mix well!
http://groups.google.com/group/comp.lang.python/t/a60c83590a016528/

locals() and frame.f_locals return old data:
http://groups.google.com/group/comp.lang.python/t/fa17941218c6e89e/

Instantiate classes using names from the command line:
http://groups.google.com/group/comp.lang.python/t/d597a1a42b88c0d1/

New syntax proposal: if some_expression as x: do_something_with(x)
http://groups.google.com/group/comp.lang.python/t/55e7578903747dc4/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiasts":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" site:
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.ac

Re: C api question and determining PyObject type

2009-11-16 Thread Gabriel Genellina

En Mon, 16 Nov 2009 07:44:34 -0300, lallous  escribió:


Actually, the object class is defined as:
class __object(object):
def __getitem__(self, idx):
return getattr(self, idx)

Anyway, now I check like this:

bool PyIsSequenceType(PyObject *obj)
{
  if (!PySequence_Check(obj))
return false;
  Py_ssize_t sz = PySequence_Size(obj);
  if (sz == -1 || PyErr_Occurred() != NULL)
  {
PyErr_Clear();
return false;
  }
  return true;
}

I don't like it, any other suggestions?


Yes: find another name for the "thing" you're checking for. It's not the  
same as a "sequence" in the Python sense.


Perhaps you want to consider your type a mapping? Sequences and mappings  
have a lot in common (mappings have length too.) In C you have separate  
slots tp_as_sequence, tp_as_mapping; but in Python code, __getitem__ is  
used for both meanings (and goes into both set of pointers.) tp_as_mapping  
takes precedence over tp_as_sequence.


--
Gabriel Genellina

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


Re: C api question and determining PyObject type

2009-11-16 Thread Gabriel Genellina

En Mon, 16 Nov 2009 07:44:34 -0300, lallous  escribió:


Actually, the object class is defined as:
class __object(object):
def __getitem__(self, idx):
return getattr(self, idx)

Anyway, now I check like this:

bool PyIsSequenceType(PyObject *obj)
{
  if (!PySequence_Check(obj))
return false;
  Py_ssize_t sz = PySequence_Size(obj);
  if (sz == -1 || PyErr_Occurred() != NULL)
  {
PyErr_Clear();
return false;
  }
  return true;
}

I don't like it, any other suggestions?


Yes: find another name for the "thing" you're checking for. It's not the  
same as a "sequence" in the Python sense.


Perhaps you want to consider your type a mapping? Sequences and mappings  
have a lot in common (mappings have length too.) In C you have separate  
slots tp_as_sequence, tp_as_mapping; but in Python code, __getitem__ is  
used for both meanings (and goes into both set of pointers.) tp_as_mapping  
takes precedence over tp_as_sequence.


--
Gabriel Genellina

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


Image to SVG conversion with Python

2009-11-16 Thread Carlo DiCelico
I need to convert JPEG and PNG files to SVG. I'm currently using PIL
to generate the JPEG/PNG files to begin with. However, I need to be
able to scale the generated images up in size without a loss of image
quality. Using SVG seems to be the best way to do this, other than
generating the images in the maximum size/resolution in the first
place, which would be too resource intensive.

I've looked around online and have found some tools for creating SVGs
but none for converting an image into SVG.

Does anyone have any experience doing this? What would be the best way
to go about this?

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


Re: (unknown)

2009-11-16 Thread Tommy Grav

On Nov 15, 2009, at 11:08 AM, Gabriel Genellina wrote:

> En Fri, 13 Nov 2009 16:05:26 -0300, Ronn Ross  escribió:
> 
>> I'm attempting to convert latitude and longitude coordinates from degrees
>> minutes and second to decimal form. I would like to go from:
>>N39 42 36.3 W77 42 51.5
>> to:
>> -77.739855,39.70
>> 
>> Does anyone know of a library or some existing out their to help with this
>> conversion?
> 
> Should be:
> 
> decimal = degrees + minutes/60.0 + seconds/3600.0
> N,E are positive; S,W are negative.
> 
> But the above numbers don't match.

It is more complicated than that. For negative numbers the value is degrees 
-minutes/60. - seconds/3600.
And people always trip up on numbers that start with -00 :)

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


Re: python simply not scaleable enough for google?

2009-11-16 Thread Paul Boddie
On 16 Nov, 05:51, sturlamolden  wrote:
>
> NASA can find money to build a space telescope and put it in orbit.
> They don't find money to create a faster Python, which they use for
> analyzing the data.

Is the analysis in Python really what slows it all down?

> Google is a multi-billion dollar business. They are using Python
> extensively. Yes I know about Unladen Swallow, but why can't they put
> 1 mill dollar into making a fast Python?

Isn't this where we need those Ohloh figures on how much Unladen
Swallow is worth? ;-) I think Google is one of those organisations
where that Steve Jobs mentality of shaving time off a once-per-day
activity actually pays off. A few more cycles here and there is
arguably nothing to us, but it's a few kW when running on thousands of
Google nodes.

> And then there is IBM and Cern's Blue Brain project. They can set up
> the fastest supercomputer known to man, but finance a faster Python?
> No...

Businesses and organisations generally don't spend any more money than
they need to. And if choosing another technology is cheaper for future
work then they'll just do that instead. In a sense, Python's
extensibility using C, C++ and Fortran have helped adoption of the
language considerably, but it hasn't necessarily encouraged a focus on
performance.

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


Re: Python & Go

2009-11-16 Thread Graham Breed

Terry Reedy wrote:

It seems to me that generators are already 'channels' that connect the 
calling code to the __next__ method, a semi-coroutine based on the body 
of the generator function. At present, the next method waits until an 
object is requested. Then it goes into action, yields an object, and 
rests again. For parallel operations, we need eager, anticipatory 
evaluation that produces things that *will* be needed rather than lazy 
evaluation of things that *are* needed and whose absence is holding up 
everything else.


Yes, generators look very much like channels.  The obvious 
thing, from where I'm sitting, is to have a function called 
"channel" that takes an iterator, runs it in a different 
thread/process/goroutine, and returns an iterator that reads 
from the channel.  A single threaded version would look very 
much like "iter" so let's use iter to get a working example:


#!/usr/bin/python2 -u

channel = iter # placeholder for missing feature

def generate():
i = 2
while True:
yield i
i += 1

def filter(input, prime):
for i in input:
if i%prime != 0:
yield i

ch = channel(generate())
try:
while True:
prime = ch.next()
print prime
ch = channel(filter(ch, prime))
except IOError:
pass

That works fine in a single thread.  It's close to the 
original go example, hence the evil shadowing of a builtin. 
 I don't think the "channel" function would present any 
problems given an appropriate library to wrap.  I got 
something like this working with Jython and the E language 
but, as I recall, had an accident and lost the code.  If 
somebody wants to implement it using multiprocessing, go to it!



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


Re: Logic operators with "in" statement

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 6:23 AM, Xavier Ho  wrote:

 '3' in l and 'no3' in l
> True
>
> AND operator has a higher precedence, so you don't need any brackets here, I
> think. But anyway, you have to use it like that. So that's something you'll
> have to fix first.

Er, you mean lower precedence. Higher precedence means it would bind
tighter, thus the expression would mean:
'3' in (l and 'no3') in l
which is certainly incorrect.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newsgroup for beginners

2009-11-16 Thread Tim Chase

mrholtsr wrote:

Is there a Python newsgroup for those who are strictly beginners at
programming and python?


http://mail.python.org/mailman/listinfo/tutor

-tkc


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


Re: Logic operators with "in" statement

2009-11-16 Thread Tim Chase

Here I expected to get True in the second case too, so clearly I don't
really get how they work.


You're seeing short-circuit evaluation:

  >>> "3" or "4"  # true
  '3'
  >>> '4' or '3'  # true
  '4'
  >>> '4' in l# false
  False
  >>> '3' or False  # true
  '3'
  >>> '4' or '42' in l  # true: same as "'4' or ('42' in l)"
  '4'
  >>> '4' or '42'
  '4'
  >>> ('4' or '42') in l # true:  same as "'4' in l"
  '4'

It just happens that sometimes you get unexpected results that 
happen to be right because of how Python handles strings/numbers 
as booleans and order-of-operations.



What I really need is to create a sequence of "if" statements to check
the presence of elements in a list, because some of them are mutually
exclusive, so if for example there are both "3" and "no3" it should
return an error.


The "in" operator only checks containment of one item, not 
multiples, so you have to manage the checking yourself.  This is 
fairly easy with the any()/all() functions added in 2.5:


  any(i in l for i in ("3", "4"))
  all(i in l for i in ("3", "4"))

For more complex containment testing, using sets will be more 
efficient and offers a richer family of batch operators 
(contains, intersection, union, difference, issubset, issuperset)


-tkc




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


Re: Logic operators with "in" statement

2009-11-16 Thread Xavier Ho
On Tue, Nov 17, 2009 at 12:08 AM, Mr.SpOOn  wrote:

> Sorry for replying to myself, but I think I understood why I was wrong.
>
> The correct statement should be something like this:
>
> In [13]: ('b3' and '5') in l or ('3' and 'b3') in l
> Out[13]: True
>
>
Carlo, I'm not sure what that achieves. Care to enlighten me?

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logic operators with "in" statement

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 6:08 AM, Mr.SpOOn  wrote:
> Sorry for replying to myself, but I think I understood why I was wrong.
>
> The correct statement should be something like this:
>
> In [13]: ('b3' and '5') in l or ('3' and 'b3') in l
> Out[13]: True

No, you've just run into another misunderstanding.

Given the expression `X and Y`:
If bool(X) is False, it evaluates to X.
Otherwise, it evaluates to Y.

In other words, the subexpression which ends up determining the truth
of the conjunction is what the conjunction evaluates to. `or` works
similarly.
This allows for tricky tricks like:
foo = possiblyFalse or default # use default if given value is false

Thus, due to the parentheses, your expression is equivalent to:
'5' in l or 'b3' in l
Which I trust is not what you intended.

Again, you need to write separate `in`s for each item you need to
check the membership of:
('b3' in l and '5' in l) or ('3' in l and 'b3' in l)

Cheers,
Chris
--
Python language lawyer at your service
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logic operators with "in" statement

2009-11-16 Thread Xavier Ho
On Tue, Nov 17, 2009 at 12:02 AM, Mr.SpOOn  wrote:

> Hi,
> I'm trying to use logical operators (or, and) with the "in" statement,
> but I'm having some problems to understand their behavior.
>

Hey Carlo, I think your issue here is mistaking 'in' as a statement. It's
just another logic operator, much like 'and' and 'or'... it's not a
statement in itself. At least, I don't think that's how you'd call 'in'.

You have to remember that Python's logical operators (and, or) works
slightly different than most languages. It doesn't return True or False, if
the things compared aren't boolean values. Instead, it returns the first
thing that makes the decision.

For example a statement such as

>>>'3' and '4'
'4'

returns the string literal 4.

1.
Python's AND operator returns the first element if the first one is False;
else, it returns the second element. That's all it does.

Python's OR operator returns the first element if the first one is True;
else, it returns the second element.

Think about it. It's a little strange, but they don't return a pure Boolean
value.

2.
Only the empty string is considered False. Any non-empty strings have True
values.

3.
The proper way of using the in operator is probably such: (There may be a
better way I'm not aware of.)

>>> '3' in l and '4' in l
False

>>> '3' in l and 'no3' in l
True

AND operator has a higher precedence, so you don't need any brackets here, I
think. But anyway, you have to use it like that. So that's something you'll
have to fix first.



> What I really need is to create a sequence of "if" statements to check
> the presence of elements in a list, because some of them are mutually
> exclusive, so if for example there are both "3" and "no3" it should
> return an error


One idea I can think of is to have a presence count; assuming the input is
non-repeating, you increase this count by 1, starting at 0. If you get
anything above one, return this error you speak of, and that might be a good
start.

Good luck,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logic operators with "in" statement

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 6:02 AM, Mr.SpOOn  wrote:
> Hi,
> I'm trying to use logical operators (or, and) with the "in" statement,
> but I'm having some problems to understand their behavior.
>
> In [1]: l = ['3', 'no3', 'b3']
>
> In [2]: '3' in l
> Out[2]: True
>
> In [3]: '3' and '4' in l
> Out[3]: False
>
> In [4]: '3' and 'no3' in l
> Out[4]: True
>
> This seems to work as I expected.

No, it doesn't. You are misinterpreting. Membership tests via `in` do
NOT distribute over `and` and `or`.

'3' and '4' in l
is equivalent to:
('3') and ('4' in l)

Recall that non-empty sequences and containers are conventionally True
in Python, so your expression is logically equivalent to:
'4' in l
With '3' not being checked for membership at all.

To check multiple items for membership in a contains, you must write
each `in` test separately and then conjoin then by the appropriate
boolean operator:

'3' in l and '4' in l

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >