Re: Database recommendations for Windows app

2005-06-22 Thread Dan
Take a look at Firebird.  It can be run in embedded mode.  It might be 
overkill for your needs though...

On 6/22/2005 10:37 AM, Gregory PiƱero wrote:
> I always figured a problem with using MySQL was distribution.  Would
> you have to tell your users to install MySQL and then to leave the
> service running?  I've never found an easy way to embed MySQL into a
> python app, and even if you could, would you then have to pay for it?
> 
> -Greg
> 
> 
> On 6/22/05, Thomas Bartkus <[EMAIL PROTECTED]> wrote:
> 
>>"Will McGugan" <[EMAIL PROTECTED]> wrote in message
>>news:[EMAIL PROTECTED]
>>
>>>Hi,
>>>
>>>I'd like to write a windows app that accesses a locally stored database.
>>>There are a number of tables, the largest of which has 455,905 records.
>>>
>>>Can anyone recommend a database that runs on Windows, is fast /
>>>efficient and can be shipped without restrictions or extra downloads?
>>>
>>>I have googled and found plenty of information on databases, its just
>>>that I dont have enough experience with databases to know which one is
>>>best for my task!
>>
>>If you are writing strictly for the MS Windows platform
>>  And
>>If the database is running single user with a "locally stored database" on a
>>Windows workstation.
>>  Then
>>The MS Access file based (.mdb) system is hard to argue with.
>>You wouldn't have to distribute the (rather expensive) Access application
>>since this is little more than a front for the underlying DAO/ADO database
>>libraries that are built into the warp and woof of MS Windows.  Your Python
>>application can address the DAO or ADO directly as these will libraries will
>>be pre-installed and/or freely available for MS Windows.  Fast, freely
>>available, no license restrictions, and no need for extra downloads for a
>>reasonably recent (Win2000, XP) operating system.
>>
>>On the other hand, if operating system portability were a concern (as it
>>should be!), I might suggest MySQL.
>>A Python/MySQL application can jump between Windows to Linux (all flavors!)
>>to Unix to BSD without need to alter a single line of code.
>>
>>You were writing a Python app, weren't you :-)
>>Thomas Bartkus
>>
>>
>>--
>>http://mail.python.org/mailman/listinfo/python-list
>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Database recommendations for Windows app

2005-06-22 Thread Dan
On 6/22/2005 11:38 AM, Thomas Bartkus wrote:
> Will McGugan" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> 
>>Hi,
>>
>>I'd like to write a windows app that accesses a locally stored database.
>>There are a number of tables, the largest of which has 455,905 records.
>>
>>Can anyone recommend a database that runs on Windows, is fast /
>>efficient and can be shipped without restrictions or extra downloads?
>>
>>I have googled and found plenty of information on databases, its just
>>that I dont have enough experience with databases to know which one is
>>best for my task!
> 
> 
> If you are writing strictly for the MS Windows platform
>And
> If the database is running single user with a "locally stored database" on a
> Windows workstation.
>Then
> The MS Access file based (.mdb) system is hard to argue with.
> You wouldn't have to distribute the (rather expensive) Access application
> since this is little more than a front for the underlying DAO/ADO database
> libraries that are built into the warp and woof of MS Windows.  Your Python
> application can address the DAO or ADO directly as these will libraries will
> be pre-installed and/or freely available for MS Windows.  Fast, freely
> available, no license restrictions, and no need for extra downloads for a
> reasonably recent (Win2000, XP) operating system.
> 

And then XP Autoupdate executes, some of those Access/MSDE libraries are 
updated, and you app is broken.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Database recommendations for Windows app

2005-06-22 Thread Dan
On 6/22/2005 1:14 PM, Dave Cook wrote:
> On 2005-06-22, Cameron Laird <[EMAIL PROTECTED]> wrote:
> 
> 
>>Are you saying that Python-based applications are particularly
>>vulnerable in this all-too-common scenario?  If so, I'm not
>>getting it; why is the architecture described more fragile than
>>more traditional Windows-oriented development patterns?  If not,
>>then, ... well then I truly don't get your point.
> 
> 
> Maybe the point is the downside of depending on installed DLLs rather than
> shipping your own.
> 
> Dave Cook

Yes, DLL hell.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: create a pdf file

2005-06-22 Thread Dan
On 6/22/2005 1:58 PM, Alberto Vera wrote:
> Hello:
> 
> I found a script that convert a file to PDF format , but it was made in PHP
> 
> Do you know any script using Python?
> 
> Regards

See http://www.reportlab.org/rl_toolkit.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Database recommendations for Windows app

2005-06-23 Thread Dan
On 6/22/2005 3:08 PM, Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>, Dan  <[EMAIL PROTECTED]> wrote:
> 
>>On 6/22/2005 1:14 PM, Dave Cook wrote:
>>
>>>On 2005-06-22, Cameron Laird <[EMAIL PROTECTED]> wrote:
>>>
>>>
>>>
>>>>Are you saying that Python-based applications are particularly
>>>>vulnerable in this all-too-common scenario?  If so, I'm not
>>>>getting it; why is the architecture described more fragile than
>>>>more traditional Windows-oriented development patterns?  If not,
>>>>then, ... well then I truly don't get your point.
>>>
>>>
>>>Maybe the point is the downside of depending on installed DLLs rather than
>>>shipping your own.
>>>
>>>Dave Cook
>>
>>Yes, DLL hell.
> 
> 
> ?
> 
> OK, I'm with you part of the way.  Typical "Access" developers 
> are *always* involved with DLL hell, right?  You're surely not
> saying that Python worsens that frustration, are you?

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


Re: Database recommendations for Windows app

2005-06-23 Thread Dan
On 6/22/2005 9:51 PM, Peter Hansen wrote:
> Will McGugan wrote:
> 
>> Thanks for the replies. I think I'm going to go with sqllite for now.
> 
> 
> Your list didn't mention a few things that might be critical. 
> Referential integrity?  Type checking?  SQLite currently supports 
> neither.  Just make sure you check the list of supported features to see 
> that it really does what you need.
> 
> -Peter

So in SQLLite, what happens of you try to store XYZ in an integer field?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you program in Python?

2005-07-06 Thread Dan
On 7/6/2005 5:38 AM, Jorgen Grahn wrote:
> On Sun, 03 Jul 2005 17:35:16 +0100, anthonyberet <[EMAIL PROTECTED]> wrote:
> ...
> 
>>What I would really like is something like an old-style BASIC 
>>interpreter, in which I could list, modify and test-run sections of 
> 

You probably want to check out Wing IDE 2.0.  There is a free trial.
-- 
http://mail.python.org/mailman/listinfo/python-list


import Help Needed - Newbie

2005-07-07 Thread Dan
Hi

I am trying to learn Python with the "Dive Into Python" book coming from 
VB, but am getting stuck at Example 2.3 
(http://www.diveintopython.org/getting_to_know_python/everything_is_an_object.html).
 
   Here is what I get following the book's directions for:

 >>> import odbchelper
Traceback (most recent call last):
   File "", line 1, in 
ImportError: No module named odbchelper

I am thinking this has something to do with the PATH that Python 
traverses to find code to load as a module.  I would greatly appreciate 
it if you could help me get this to work.

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


Re: import Help Needed - Newbie

2005-07-08 Thread Dan
On 7/7/2005 5:50 PM, GregM wrote:
> A search on google for odbchelper resulted in:
> http://linux.duke.edu/~mstenner/free-docs/diveintopython-3.9-1/py/odbchelper.py
> 
> I think this will help you.
> Greg.
> 

That is the previous example which worked for me fine.  I have this code 
on a network drive so is this why I can't import it as a module?

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


Re: Packages and modules

2005-07-26 Thread Dan
> > no executable code in
> > __init__.py is executed, even though "import test" seems to succeed.

I've discovered that "import test" *does* cause executable code in the
package to be executed. However, I can't execute it on the command line
using "python test". Is there a way to do this?

> There _is_ a standard library package called test

Oh, you're right. But I've renamed the module to XYZ and I still have
the problem.

-- 
  They had a big meeting, drank some beer and had some pizza and
  decided 'A' would be 65.
   - Jim Greenly, professor at Georgia Institute of Technology


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


Re: [OT] Problems with permissions etc

2005-07-27 Thread Dan
> 2. I am using wxPython, which was compiled from source.

Maybe you had a good reason to install from source. But if you didn't, I
suggest using a sys-admin's convenience tool, such as "apt". Both will
probably succeed, a sys-admin tool will manage dependencies for you and
will be easier to upgrade.

-- 
   I'm actually hoping that [Linux] won't take more than 25 or 30%
   of the market. If Linux owned 95% of the market it would be
   ... as sick [as Windows]. There is some need for competition.
   - Linus Torvalds


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


Re: Create a variable "on the fly"

2005-07-27 Thread Dan
> make_variable('OSCAR', 'the grouch');
> print OSCAR;

Try using "setattr". (It's in __builtins__; you don't have to import
anything.)

>>> print setattr.__doc__
setattr(object, name, value)

Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.

-- 
   If builders built buildings the way programmers write programs,
   the first woodpecker that came along would destroy civilization.
  - Original author unknown


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


MESSAGE NOT DELIVERED: Returned mail: Data format error

2005-07-27 Thread dan
Your message could not be delivered. The User is out of space. Please try to 
send your message again at a later time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing arguments to function - (The fundamentals are confusing me)

2005-08-09 Thread Dan
> Does that mean Python functions aren't always byref, 
> but are sometimes byval for nonmutables?

Don't think of it as byref or byval (as they are used in Visual Basic).
All parameters are passed the same way: by reference instead of by copy.

It's a little difficult to get your head around, but I promise that once
you understand it it will seem simple and intuitive.

  def reassign(x):
  x = ['foo']

"reassign" has no effect, even on a mutable type like a list. It simply
changes what "x" refers to, which isn't very useful because the name "x"
only exists inside the function.

In Python everything is treated the same way. Even integers are objects:

   >>> n = 1
   >>> n.__hex__()
   '0x1'

What other programming languages do you know? Maybe we can draw a
comparison to something you're familiar with.

-- 
   Presumably, we're all fully qualified computer nerds here,
   so we are allowed to use "access" as a verb. Be advised,
   however, that the practice in common usage drives
   English-language purists to scowling fidgets.
  - from Sybex's "Perl, CGI and JavaScript", p. 256


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


Re: What are modules really for?

2005-08-10 Thread Dan
> Functions existing in a module? Surely if "everything is an object" (OK 
> thats Java-talk but supposedly Python will eventually follow this too) 
> then there should be nothing in a module thats not part of a class.

No, it's a bit the other way around. In Python, functions are objects:

  >>> del MyFunction
  >>> def MyFunction(x='abc', y='xyz'): pass
  ...
  >>> print MyFunction.func_defaults
  ('abc', 'xyz')

> Related classes in the same file? Be careful. Doesn't anything "knowing" 
> about anything else compromise encapsulation?

You might think of modules in Python as like packages in Java. However,
putting classes in the same module doesn't give them any additional
powers to interact with each other. (At least, not that I know of.)

-- 
   Distributed computing is like driving a wagon pulled
   by a thousand chickens.
   - Paul Lindner


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


Re: searching a list of dictionaries for an element in a list.

2005-08-10 Thread Dan
> I want to search list1, and the result should be all dictionaries where
> primarycolor is in input. I can do this using a double for-loop, but is
> there a more efficent way?

Of course.:-)

L = [dict for dict in list1 if dict['primarycolor'] in input]

In older versions of Python, we would use the "filter" function, which
accomplishes the same thing.

-- 
  [Mozilla] Firefox is better than Explorer by leaps and bounds. I
  don't miss Explorer one iota. Give Firefox a day's worth of Web
  surfing, and you won't either.
  - Forbes (short link: http://tinyurl.com/56j8m )


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


Re: Regular expression to match a #

2005-08-11 Thread Dan
> My (probably to naive) approach is: p = re.compile(r'\b#include\b)

I think your problem is the \b at the beginning. \b matches a word break
(defined as \w\W or \W\w). There would only be a word break before the #
if the preceding character were a \w (that is, [A-Za-z0-9_], and maybe
some other characters depending on your locale).

However, the \b after the "include" is exactly what you want.

-- 
   I had picked out the theme of the baby's room and done other
   things. I decided to let Jon have this.
   - Jamie Cusack (of the Netherlands), whose husband Jon
 finally talked her into letting him name their son Jon 2.0


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


Re: Writing a small battleship game server in Python

2005-08-11 Thread Dan
> The server should accept connections from new players and be able to handle 
> multiple games concurrently.

Multiple threads would be the way to go for a real application. But if
you want to avoid the complexity involved in threading and
synchronization in this exercize, you can avoid threads by using
"select" instead:
  http://www.python.org/doc/2.3.5/lib/module-select.html

The "select" function allows you to determine (without blocking) which
sockets have input available.

Python's "select" is a wrapper for the C function with the same name. On
Unix you can learn more about it using "man select".

-- 
  Yield in childhood to selfishness and you will find it the
  most enchaining tyrrany on earth.
- Oswald Chambers, My Utmost For His Highest, p. 74


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


Re: __getattribute__ for class object

2005-08-12 Thread Dan
> > but if i want to have a __getattribute__ for class attributes
>
> Read something on metaclasses.

Depending on what you want to do, it might be better to use properties
instead:

  class Meta(type):
 x = property(lambda klass: 'Called for '+str(klass))

  class Foo(object):
 __metaclass__=Meta

  print Foo.x

-- 
  Do I know what's in this bill? Are you kidding? Only God knows...
  - U.S. Senator Robert Byrd, when asked if he knew the
contents of a $520 billion, 4000-page spending bill


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


Re: __del__ pattern?

2005-08-16 Thread Dan
> What does "default" mean, and is that definition in conflict with what
I 
> said? The docs say it means INADDR_ANY.

someSocket.bind(('', somePort)) means accept connections from any
machine. (We use INADDR_ANY instead of '' in C.)

someSocket.bind(('localhost', somePort)) means accept only connections
from the local machine.

Obviously, the second form is much more secure. Even if you don't plan
on accepting any of the connections, it's always more secure to let the
operating system turn everyone else away.

-- 
 Marc Ewing had a reputation for being able to fix any computer
 problem at his university. He always wore a red baseball,
 and so was known as "the guy in the red hat". Later, when he 
 started his own open-source company, he wondered what to call it...




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


String functions deprication

2005-08-16 Thread Dan
> http://www.python.org/doc/2.4.1/lib/node110.html
>
> These methods are being deprecated.  What are they being replaced
> with?

They're being made methods of the string class itself.

For example:
  >>> s = 'any old string'
  >>> string.split(s, ' ') # Old way
  ['any', 'old', 'string']
  >>> s.split()# New way
  ['any', 'old', 'string']

-- 
  You know, I've been real busy.
  - Mike Foster, then-governor of Louisiana, when
asked the name of his newborn seventh grandchild.


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


PyXML and xml.dom

2005-08-17 Thread Dan
I'm writing a Python program that does some XML parsing, though nothing
heavy, and I want to avoid requiring the user to install additional
libraries like PyXML.

The documentation for my version of Python (2.3.5) mentions PyXML as an
additional library while discussing the DOM module
. I don't seem
to have PyXML installed on my system, but:

  >>> import xml.dom.minidom
  >>> print xml.dom.minidom.xml.__doc__
  [blah, blah]
  The full PyXML package, available from http://pyxml.sf.net, 
  is installed. 
  [blah, blah]

Is PyXML now part of the Python distribution, or is it still an add-on?

-- 
  In the early 1980s, teenagers began "getting high" from aerosols,
  despite clear warnings of death. Then liability lawyer Victor E.
  Schwartz suggested adding a (false) warning of facial
  disfigurement. According to Schwartz, "We haven't had a liability
  claim since."


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


Re: strptime() doesn't recognize BST as a valid timezone

2005-09-16 Thread Dan
> I get: "ValueError: time data did not match format: ..."

I'm running Linux in London, and I don't get that error.

Python 2.3.5 (#2, May 29 2005, 00:34:43)
[GCC 3.3.6 (Debian 1:3.3.6-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> date_str = "Wed Sep 14, 2005 5:07 PM BST"
>>> format = "%a %b %d, %Y %I:%M %p %Z"
>>> time.strptime(date_str, format)
(2005, 9, 14, 17, 7, 0, 2, 257, 1)

However, when I used another timezone (I tried EST and PST), I got the
same error you did.

I really don't know enough about how Python handles dates to tell you
anything more.

-- 
  Diplomacy is saying "nice doggy" until you find a rock.
 - submitted by Nancy Greer
   to the CleanStuff mailing list


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


Re: are variables local only to try/except blocks?

2005-09-20 Thread Dan
> try:
>try:
>   doSomething1
>   excp = 0
>except:
>   excp = 1
>#endTry

Note that you can use "else" after "except" for precisely this purpose:

try:
   foo()
except:
   print 'Exception raised'
else:
   print 'No exception raised'

-- 
   Optimism is the faith that leads to achievement; nothing can be
   done without hope.
- Helen Keller


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


Re: Python GUIs

2005-09-21 Thread Dan
> B='\x12','\x32'
> B[0]='\x12'
>
> I cannot get this to work,

"B" is a tuple, which means it can't be assigned to. Try this:
  B=['\x12','\x32']

-- 
  Do I know what's in this bill? Are you kidding? Only God knows...
  - U.S. Senator Robert Byrd, when asked if he knew the
contents of a $520 billion, 4000-page spending bill


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


Re: best solution to for loop

2005-09-22 Thread Dan
> Hi, I have several apps which connect to a database,  fetch some data
> an put this into a gtk.TreeStore, but if the result set is 1500 row
> long, the app response slowly

The first thing to test is whether it's Python or the database that's
the bottleneck. 1500 rows isn't all that much for a database, but it
might not be trivial either.

Even if the bottleneck is Python, the solution might be to limit the
amount of data that you process. For example, rather than displaying all
1500 records in a tree (nobody wants to scroll through 1500 records
anyway), try grouping them by the first letter of their name. Display a
tree consisting of each letter, then when the user clicks that letter:

  cur.execute("SELECT * FROM clients WHERE name LIKE '" + letter + "%'")

-- 
   I had picked out the theme of the baby's room and done other
   things. I decided to let Jon have this.
   - Jamie Cusack (of the Netherlands), whose husband Jon
 finally talked her into letting him name their son Jon 2.0


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


Re: How to tell if an exception has been caught ( from inside the exception )?

2005-09-22 Thread Dan
If the exception isn't caught, it is printed to standard error. This
means that either __str__ or __repr__ is called (to convert it to a
displayable string). If the exception is caught, those methods
*probably* won't be called.

-- 
Where you are is not as important as where you are going.
- Oliver Wendell Holmes, U.S. Supreme Court Justice


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


Re: Open PDF

2005-09-22 Thread Dan
> I would like to know how to open a PDF document from a python script

You mean open it and display it to the user? Under Windows you may be
able to get away with just "executing" the file (as though it were an
executable):

  import os
  os.system("c:/path/to/file.pdf")

Under Linux you can probably use xpdf or gpdf:

  os.system("xpdf /path/to/file.pdf")

Note that you should check the return code of "system" to see if the
execution was successful. For example, the user might not have xpdf
installed.

-- 
  Don't try to be charming, witty or intellectual. Just be yourself.
  - Mrs. Cuomo's poorly worded advice to her husband (then
governor of New York) shortly before his speech to the
New York Press Club


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


Re: Redirecting ./configure --prefix

2004-12-13 Thread Dan
Dave Reed wrote:
LD_LIBRARY_PATH=/some/private/dir/lib; export LD_LIBRARY_PATH
LD_LIBRARY_PATH does the trick, and sys.path seems okay by default.
Thanks!
/Dan
--
dedded att verizon dott net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Performance (pystone) of python 2.4 lower then python 2.3 ???

2004-12-14 Thread Dan
Lucas Hofman wrote:
A 7% speed DECREASE??? According to the documentation it should be a 5% increase?
I also see an 8-10% speed decrease in 2.4 (I built) from 2.3.3 (shipped 
w/Fedora2) in the program I'm writing (best of 3 trials each).  Memory 
use seems to be about the same.

2.4:   real2m44.131s
2.3.3: real2m29.865s
/Dan
--
dedded att verizon dott net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Performance (pystone) of python 2.4 lower then python 2.3 ???

2004-12-15 Thread Dan
Skip Montanaro wrote:
Dan> I also see an 8-10% speed decrease in 2.4 (I built) from 2.3.3
    Dan> (shipped w/Fedora2) in the program I'm writing (best of 3 trials
Dan> each).  Memory use seems to be about the same.
How do you how the compiler flags were the same if you didn't compile both
versions yourself?
I don't, and I also don't know if the Redhat folks modified the sources 
in some way.  That's why I mentioned the difference in builds.  But I 
suppose that makes this as good as no data.

/Dan
--
dedded att verizon dott net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs. Perl

2004-12-15 Thread Dan
I'm inexperienced in both languages, and am toying around with
both now, so I offer these comments with warnings of the blind
leading the blind.
As far as regular expressions go I can't offer much information.
They both meet my needs.  I prefer the Python syntax, however:
it is possible in both languages to compile a regex once and use
it many times, but it is more plainly specified in Python.
One difference I've noticed between the two languages is variable
scope.  By default, Perl variables are global, but there is a "my"
keyword that makes scope behave much as in C:
#!/usr/bin/env perl
my $foo = "globally defined \$foo";
sub func_2 {
print "func_2: $foo\n";
}
sub func_1 {
my $foo = "func_1 defined \$foo";
print "func_1: $foo\n";
if (1) {
my $foo = "if_block defined \$foo";
print "if_block: $foo\n";
}
print "func_1: $foo\n";
func_2()
}
print "main: $foo\n";
func_1();
func_2();
print "main: $foo\n";
Here's the output.  Note that the assignment within the if_block
only holds within that block (it would have held to the end of
func_1() if not for the "my" keyword).  Note that the call of
func_2() from within func_1() does _not_ see the effect of the
assignment in func_1().
main: globally defined $foo
func_1: func_1 defined $foo
if_block: if_block defined $foo
func_1: func_1 defined $foo
func_2: globally defined $foo
func_2: globally defined $foo
main: globally defined $foo
In Python, unless I just haven't figured it out yet, you can't
quite get this C-like scoping.  You can have global variables,
and variables local to functions, but I don't see any way to get
a variable local to an if block.
There is another keyword in Perl called "local" that makes
variables behave much like those of Emacs Lisp.  Take this
program for example:
#!/usr/bin/env perl
$foo = "globally defined \$foo";
sub func_2 {
print "func_2: $foo\n";
}
sub func_1 {
local $foo = "func_1 defined \$foo";
print "func_1: $foo\n";
func_2()
}
print "main: $foo\n";
func_1();
func_2();
print "main: $foo\n";
Here's the output:
main: globally defined $foo
func_1: func_1 defined $foo
func_2: func_1 defined $foo
func_2: globally defined $foo
main: globally defined $foo
Notice that the first call of func_2() from func_1() _does_ see
the "local" assignment in func_1(), but that once func_1()
returns the global definition of $foo is restored and is now in
effect when func_2() is called from main.  I don't believe
Python has anything like this, but I don't know Python well
enough to be sure.  I can't think of how this would be useful in
Perl or Python, but it seems useful in Emacs Lisp.
Another difference between the languages is the amount of error
checking done at compile time.  Perl seems to catch more errors
at compile time.
You asked if Python is missing any features of Perl.  Perl has a
"tainted" mode that guards against insecure use of data provided
by users.  I don't know that Python has any equivalent.  I've
not used this, and I don't know how robust it's considered.
Another advantage of Perl is wider availability.  Until about a
year and a half ago, my primary environment was VMS.  And the
newest version of Python I could find for VMS was 1.4 when the
latest Python was 2.2.2.  Perl's well supported on VMS, and is
embeddable in VMS DCL command scripts.
But, for me, each language has one big advantage over the other.
Perl is the scripting language almost universally used in my
workplace.  There are a lot of existing scripts and lots of
local expertise in Perl.  I don't know of any existing Python
scripts, or Python users, in my building.  That's Perl's
strength in my world.  On the other hand, I find Perl's syntax
really hard to deal with.  I'm not a programmer, I'm an engineer
who infrequently needs to write a small program.  So, I write
something, and then find that I need to modify it or write
something new six months later.  I invariably forget everything
I know about Perl in six months.  I've been "learning" Perl
since 1998, but find I keep reverting to C (or even Emacs Lisp!)
for small, simple programs because I can't remember how to do it
in Perl.  So, I thought I'd give Python a try.  The syntax
certainly seems a lot cleaner and easier to remember.  We'll see
how it goes.
/Dan
--
dedded att verizon dott net
--
http://mail.python.org/mailman/listinfo/python-list


Redirecting ./configure --prefix

2004-12-14 Thread Dan
I suspect this isn't specifically a Python question, but I
encountered it with Python so I thought I'd ask here.
I'm running Linux (Fedora 2), and just downloaded the Python 2.4
kit.  I did the following from my user account:
./configure --prefix=/some/private/dir --enable-shared
make
make test # all was okay
make install
Now, when I try to run this I get the following error:
python: error while loading shared libraries:
libpython2.4.so.1.0: cannot open shared object file: No such
file or directory
This library is in /some/private/dir/lib, but that directory is
not being searched.
So, I have these questions:
- Can I get Python to search /some/private/dir/lib for
  library files?
- Will sys.path be okay?  How can I make it okay?
- Is there anything else I need to worry about?
Any help would be appreciated.
Thanks,
Dan
--
dedded att verizon dott net
--
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-17 Thread Dan
Steve Holden wrote:
Which, now I remember, Digital Equipment extended to floating-point in 
their FOCAL language. 
Never used FOCAL, or VAX Basic for that matter (was it the same thing?), 
but I can remember calling the VAX Basic BAS$EDIT routine from Pascal in 
college.  BAS$EDIT had most of the basic string operations that are 
common today, like trimming whitespace, splitting, upper or lower 
casing, etc., and using it was easier than using Pascal's facilities.

My wife picked up an old (c) 1978 version of DEC's Basic user's guide, 
and it doesn't list this function, so it must have been added between 
then and 1985 when I encountered it.

/Dan
--
dedded att verizon dott net
--
http://mail.python.org/mailman/listinfo/python-list


Sockets

2005-04-07 Thread Dan



I'm using the socket module and have run into a problem.

I want to send binary data over the connection.  With C, this is easy:

write(sock_fd, data, length);

But it appears that the Python socket module has no method to send
binary data, it only sends strings.  So there's no argument to tell it
the length, it stops when it gets the end of string character (null).

The only way I can see around it is to encode the data, but this is
really just an inelegant hack.

Any suggestions?  Python is still new to me and I can't say that I've
mastered all its nuances.

Dan

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


Re: Sockets

2005-04-07 Thread Dan
On Thu, 7 Apr 2005 21:52:11 -0500, [EMAIL PROTECTED] wrote:

>Python strings always carry their length, and can have embedded NULs.
>s.write("\0\1\2\3")
>should write 4 bytes to the socket 's'.

I'm taking binary data from a database, so it's not really a Python
string.  Is there an easy way to convert it?

Thanks

Dan

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


Re: Sockets

2005-04-07 Thread Dan
On Fri, 08 Apr 2005 03:06:38 -, Grant Edwards <[EMAIL PROTECTED]>
wrote:


>Nope. You're thinking of C strings. Python strings aren't
>terminated with a null. 

Yes, that make sense.  Thanks for the input, and the note on struct.

Dan

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


Can't Stop Process On Windows

2005-04-11 Thread Dan

I have a python script running under Windows XP that I need to
terminate from the keyboard.  A control-c works fine under Linux, but
not under Windows.  I'm pretty sure that the culprit is 'select' that
I'm using to multiplex socket i/o, which seems to be blocking the
keyboard interrupt.  Is there some way around this?

Dan

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


Re: Can't Stop Process On Windows

2005-04-13 Thread Dan
On Tue, 12 Apr 2005 06:53:04 -0600, Dave Brueck
<[EMAIL PROTECTED]> wrote:


>Are you calling select with a long timeout? An alternative would be to call 
>select with a much shorter timeout, but call it multiple times from a loop.

That seems to have fixed the problem.  Changed it from no timeout to
one second.

Thanks

Dan

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


Re: Compute pi to base 12 using Python?

2005-04-13 Thread Dan
On 13 Apr 2005 12:06:26 -0400, [EMAIL PROTECTED] (Roy Smith) wrote:

>Scott David Daniels  <[EMAIL PROTECTED]> wrote:
>>If you think those are fun, try base (1j - 1)
>
>Get real.  I can't imagine using anything so complex.

Well said.  :-)

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


Re: Compute pi to base 12 using Python?

2005-04-13 Thread Dan
On Wed, 13 Apr 2005 03:27:06 -0700, Dick Moores <[EMAIL PROTECTED]>
wrote:

> I'm just trying to help an artist acquaintance who needs (I just 
>learned) the first 3003 digits of pi to the base 12.

Now you've got me curious.  Why would an artist want the first 3003
digits of pi to the base 12?

Dan

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


Inelegant

2005-04-14 Thread Dan

I've just begun playing with Python, and so far I like what I see.
It's a very elegant language.  But I've found something that's, well,
a bit ugly.  Maybe someone can point out to me where I'm wrong.

If you use triple quotes to define a string, then the newlines are
implicitly included.  This is a very nice feature.  But if you're
inside a function or statement, then you'll want the string to be
positioned along that indentation.  And the consequences of this is
that the string will include those indentations.

For example:

def SomeFunction()
   if SomeCondition:
  MyString = 
  """
  The quick brown fox
  """
  print MyString

The output will be:

  The quick brown fox

But what you really want is:

The quick brown fox

The way around it is to write the function thus:

def SomeFunction()
   if SomeCondition:
  MyString = 
"""
The quick brown fox
"""
  print MyString

But that's just ugly.  It seems to me that the string should be
interpreted with the edge along the indentation line, not from the
start of the line.  But that would probably create other problems.

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


Apache mod_python

2005-04-17 Thread Dan

I've been writing a server application in Python.  The app listens on
a socket and interfaces to a database.

Now I'd like to write a web application to also access the database.
It seems natural to use Python.  I've installed mod_python (Debian
libapache2-mod-python2.3, mod_python 3.1.3-4).

My question is, how mature/stable is mod_python?  Is it suitable for a
production environment?  The documentation is a bit lacking, and I've
found some errors in the demo example where it looks like the link
should work, but it doesn't. (Could well be something I'm doing.).
I've also noted that there's still work being done on it.

Thanks.

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


Strings

2005-04-21 Thread Dan
I've having trouble coming to grip with Python strings.

I need to send binary data over a socket.  I'm taking the data from a
database.  When I extract it, non-printable characters come out as a
backslash followed by a three numeric characters representing the
numeric value of the data.  I guess this is what you would call a raw
Python string.  I want to convert those four characters ( in C-think,
say "\\012" ) into a single character and put it in a new string.

There's probably a simple way to do it, but I haven't figured it out.
What I've done so far is to step through the string, character by
character.  Normal characters are appended onto a new string.  If I
come across a '\' character, I look for the next three numeric
characters.  But I don't know how to convert this code into a single
character and append it onto the new string.

I'm sure what I'm doing is long and convoluted.  Any suggestions would
be appreciated.

Dan

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


Re: New line

2005-04-21 Thread Dan
On Thu, 21 Apr 2005 21:34:03 +0100, "ionic" <[EMAIL PROTECTED]> wrote:

Open a text editor and write your code.  Save the file with a .py
extension, i.e., myprogram.py.  From the command line type 'python
myfile.py'

Dan

>
>Ok sorry guys,
>
>using the python gui, if i hit the 'enter' key python just executes what
>ever ive typed.  It doesnt take me to the next line.
>
>How do i type several lines without executing after each line?
>
>Cheers

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


Re: Strings

2005-04-21 Thread Dan
On Thu, 21 Apr 2005 10:09:59 -0400, Peter Hansen <[EMAIL PROTECTED]>
wrote:

Thanks, that's exactly what I wanted.  Easy when you know how.

Dan

>Dan wrote:
>> I've having trouble coming to grip with Python strings.
>> 
>> I need to send binary data over a socket.  I'm taking the data from a
>> database.  When I extract it, non-printable characters come out as a
>> backslash followed by a three numeric characters representing the
>> numeric value of the data.  I guess this is what you would call a raw
>> Python string.  I want to convert those four characters ( in C-think,
>> say "\\012" ) into a single character and put it in a new string.
>
>Does this help?
>
> >>> s = 'foo \\012 bar'
> >>>
> >>> s.decode('string-escape')
>'foo \n bar'
> >>> print s.decode('string-escape')
>foo
>  bar
> >>>
>
>Note that the \n in the first one is because I didn't
>*print* the result, but merely allowed the interpreter
>to call repr() on it.  repr() for a newline is of course
>backslash-n, so that's what you see (inside quotation marks)
>but the string itself has only 9 characters in it, as
>you wished.
>
>-Peter

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


re: how to stop python

2006-07-30 Thread Dan
bruce bedouglas at earthlink.net posted:

 > perl has the concept of "die". does python have anything
 > similar. how can a python app be stopped?

I see this sort of statement a lot in Perl:
 open(FH, "myfile.txt") or die ("Could not open file");

I've no idea why you're asking for the Python equivalent to die, but if 
it's for this sort of case, you don't need it.  Usually in Python you 
don't need to explicitly check for an error.  The Python function will 
raise an exception instead of returning an error code.  If you want to 
handle the error, enclose it in a try/except block.  But if you just 
want the program to abort with an error message so that you don't get 
silent failure, it will happen automatically if you don't catch the 
exception.  So the equivalent Python example looks something like this:
 fh = file("myfile.txt")

If the file doesn't exist, and you don't catch the exception, you get 
something like this:
$ ./foo.py
Traceback (most recent call last):
   File "./foo.py", line 3, in ?
 fh = file("myfile.txt")
IOError: [Errno 2] No such file or directory: 'myfile.txt'

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


Re: Windows vs. Linux

2006-07-31 Thread Dan
Andy Dingley wrote:
[snip]
 > Python is one of the best languages I've found for
 > platform-independence - significantly better than Perl.
[big snip]

This statement was given in the context of Windows and Linux, and I've 
precious little experience doing anything on Windows. So I won't 
challenge it in the least, and in fact do not doubt it.

But taken out of that context, I'll challenge it.  I was first exposed 
to Python about five or six years ago--my boss asked me to consider it. 
What I found was that the current version of Python was V2.2, but newest 
version (that I could find) that ran on VMS was V1.4.  I decided to 
stick with Perl, which provides excellent support for VMS.

Now that I no longer need to worry about VMS, I prefer Python. Quite a bit.

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


Re: Windows vs. Linux

2006-08-01 Thread Dan
Edmond Dantes wrote:
> Dan wrote:
> 
>> But taken out of that context, I'll challenge it.  I was first exposed
>> to Python about five or six years ago--my boss asked me to consider it.
>> What I found was that the current version of Python was V2.2, but newest
>> version (that I could find) that ran on VMS was V1.4.  I decided to
>> stick with Perl, which provides excellent support for VMS.
> 
> What, you couldn't just take the latest source for Python and compile it
> under VMS?
> 
> :-)
> 
> I say that in jest, but I am surprised there were no Unix/Linux libraries
> available for VMS, which would've made the port easier -- and more up to
> date.
> 

Well, I never looked into a port, but there were certainly Unix 
libraries available for VMS.  (I believe VMS is POSIX-compliant, but 
don't quote me on that.)

/Dan

-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


md5 question

2006-08-03 Thread Dan
I have a question regarding the md5 module. Is there a way in
"initialize" the md5 to a hex value, and continue processing with that
value.

For example:
In [13]:md5_h = md5.md5("Hello world")

In [14]:md5_h.hexdigest()
Out[14]:'3e25960a79dbc69b674cd4ec67a72c62'

In [15]:md5_w = md5.md5("Hello")

In [16]:md5_w.hexdigest()
Out[16]:'8b1a9953c4611296a827abf8c47804d7'

In [17]:md5_w.update(" world")

In [18]:md5_w.hexdigest()
Out[18]:'3e25960a79dbc69b674cd4ec67a72c62'

now pretend I wanted to save the string
'8b1a9953c4611296a827abf8c47804d7', and later create a new md5 object
such that when I did md5_w.update(" world") it would then have the hex
value '3e25960a79dbc69b674cd4ec67a72c62'. Is that possible? I've looked
for initialization options in the documentation and searched c.l.p.,
but no luck. 

-Dan

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


Question on try/except

2006-08-07 Thread Dan
While perusing sre.py in the standard library, I came upon this snippet 
of code in the _compile() function definition:

 try:
 p = sre_compile.compile(pattern, flags)
 except error, v:
 raise error, v # invalid expression

Is there some particular use in catching an exception and immediately 
re-raising it?  Why catch it at all?

/Dan

-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter module not found

2006-08-08 Thread Dan
Shuaib wrote:
> Hey again,
> 
> I am using the latest python available on my system (2.4). So I don't
> think that's the problem.
> 
> Any more ideas? Do I need to install Tkinter as a seperate
> module/package? As I said, I've already installed Tcl/Tk, though.

This is a wild guess, but I just installed Python 2.5b3 from source to 
play with it, and on the first attempt I didn't get Tkinter.  Turns out 
I was missing tcl.h and tk.h in /usr/include.  On my system (Fedora), I 
had to install tcl-devel and tk-devel to get those header files.

Since you mentioned Gentoo, which builds from source, maybe you have a 
similar issue.  Although you'd think there'd be some dependency checking 
  in your package system that would catch it.  Like I said, this is just 
a wild guess.

/Dan

-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global Objects...

2006-08-16 Thread Dan
KraftDiner wrote:
> I have a question..
> 
> myGlobalDictionary = dictionary()
> 
> 
> class someClass:
>def __init__(self):
>   self.x = 0;
>def getValue(self, v)
>   myGlobalDictionary.getVal(v)
> 
> 
> myGlobalDictionary doesn't seem to be visible to my someClass methods.
> Why?  What should I do?
> 

This works:

 >>> class dictionary(dict):
... def getVal(self, key):
... return self[key]
...
 >>> myGlobalDictionary = dictionary()
 >>>
 >>> myGlobalDictionary['spam'] = 'eggs'
 >>>
 >>> class someClass:
...def __init__(self):
...   self.x = 0;
...def getValue(self, v):
...   return myGlobalDictionary.getVal(v)
...
 >>>
 >>> mySomeThing = someClass()
 >>>
 >>> print mySomeThing.getValue('spam')
eggs
 >>>


-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: capture video from camera

2006-06-08 Thread dan
aljosa wrote:
> i had no intention to say that videocapture is bad but it's not what
> i'm looking for.
> concerning docs, everybody has their own view on how docs should look
> like.
>
> that said, i should have written more clearly what i'm looking for.

Hi aljosa,

I hope you won't be deterred from posting further questions to the
group by Fredrik's somewhat terse and unfriendly reply.

comp.lang.python is a forum generally noted for its pleasing admixture
of erudition and encouragement. Fredrik is uncommonly distinguished in
the scope and depth of his knowledge. He does himself, and the group in
general, an injustice by the intolerance of his response.

With best wishes,

Dan

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


Re: capture video from camera

2006-06-09 Thread dan
K.S.Sreeram wrote:
> dan wrote:
> > I hope you won't be deterred from posting further questions to the
> > group by Fredrik's somewhat terse and unfriendly reply.
> >
> > comp.lang.python is a forum generally noted for its pleasing admixture
> > of erudition and encouragement. Fredrik is uncommonly distinguished in
> > the scope and depth of his knowledge. He does himself, and the group in
> > general, an injustice by the intolerance of his response.
>
> People need to learn to be precise and to-the-point in their posts. If
> not, its a waste of time for a lot of people.. more so for frequent
> contributors like fredrik. I hope criticism like yours does not deter him!
>
Hi K.S,

People learn through encouragement and appropriate example, not through
criticism...

Best wishes,

Dan

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


Allowing ref counting to close file items bad style?

2006-08-29 Thread Dan
Is this discouraged?:

 for line in open(filename):
 

That is, should I do this instead?:

 fileptr = open(filename)
 for line in fileptr:
 
 fileptr.close()

Can I count on the ref count going to zero to close the file?

How about a write case?  For example:

 class Foo(list):
 def __init__(self):
 self.extend([1, 2, 3, 4])
 def write(self, fileptr):
 for item in self:
 fileptr.write("%s\n" % item)

 foo_obj = Foo()
 foo_obj.write(open("the.file", "w"))

Is my data safer if I explicitly close, like this?:
 fileptr = open("the.file", "w")
 foo_obj.write(fileptr)
 fileptr.close()

I understand that the upcoming 'with' statement will obviate this 
question, but how about without 'with'?

/Dan

-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing ref counting to close file items bad style?

2006-08-29 Thread Dan
Paul Rubin wrote:
> Dan <[EMAIL PROTECTED]> writes:
>> Is this discouraged?:
>>
>>  for line in open(filename):
>>  
> 
> Yes.

Well, not what I wanted to hear, but what I expected.

Thanks,
Dan

-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing ref counting to close file items bad style?

2006-08-31 Thread Dan
BJƶrn Lindqvist wrote:
> On 8/30/06, Dan <[EMAIL PROTECTED]> wrote:
>> Is my data safer if I explicitly close, like this?:
>>  fileptr = open("the.file", "w")
>>  foo_obj.write(fileptr)
>>  fileptr.close()
> 
> Have you ever experienced a problem caused by not explicitly closing
> your file handles?
> 

No.  If I had, I wouldn't have asked the question.  It seems to work, 
but can I really count on it?

I am a sample of one (In that happy place that Brooks described as 
quadrant 1, where a person writes programs for himself to be run on his 
own computer.  Or perhaps to be run by a handful of co-workers.)  Such a 
small sample isn't statistically significant; a 100% success rate 
doesn't mean much.  I've also never had a burned CD go bad, but I know 
that they do.

/Dan

-- 
dedded att verizon dott net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: utf - string translation

2006-11-22 Thread Dan
Thank you for your answers.

In fact, I'm getting start with Python.

I was looking for transform a text through elementary cryptographic
processes (VigenĆØre).
The initial text is in a file, and my system is under UTF-8 by default
(Ubuntu)

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


Re: utf - string translation

2006-11-26 Thread Dan
On 22 nov, 22:59, "John Machin" <[EMAIL PROTECTED]> wrote:

> > processes (VigenĆØre)
> So why do you want to strip off accents? The history of communication
> has several examples of significant difference in meaning caused by
> minute differences in punctuation or accents including one of which you
> may have heard: a will that could be read (in part) as either "a chacun
> d'eux million francs" or "a chacun deux million francs" with the
> remainder to a 3rd party.
>
of course.
My purpose is not doing something realistic on a cryptographic view.
It's for learning rudiments of programming.
In fact, coding characters is a kind of cryptography I mean, sometimes,
when friends can't read an email because of the characters used...

I wanted to strip off accents because I use the frequences of the
charactacters. If  I only have 26 char, it's more easy to analyse (the
text can be shorter for example)

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


Re: Some general questions about using "stdin","stdout"....

2006-02-16 Thread Dan
Hello.

If you're new to Python, then input/output isn't the best place to
start. Begin with the tutorial:
  http://docs.python.org/tut/tut.html
Other documentation is also linked to from there.

However, I will briefly answer your questions.

>   print "hello"|sys.stdin.read()

In Python the | operator has a different meaning than in a shell. In
Python it means "bitwise or":

>>> print 5 | 9
13


> Why can't i "write" to the stdin?

There may be some contorted way to do that under Unix, but it's not a
good idea. You can pipe input to your program from a shell (as you've
already done), but it's not a good idea to redirect input from within
your program.

You can accomplish the same thing like this:

   if i_want_to_redirect_input:
  my_input_source = open('file.txt')
   else:
  my_input_source = sys.stdin
   # Now read from my_input_source instead of stdin.

-- 
  They had a big meeting, drank some beer and had some pizza and
  decided 'A' would be 65.
   - Jim Greenly, professor at Georgia Institute of Technology


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


Creating Files

2005-05-04 Thread Dan


I know how to open a system file with Python, but is there some way to
create one if it's not there?

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


Re: Mod_python

2005-05-04 Thread Dan
On 3 May 2005 19:22:52 -0700, "Gensek" <[EMAIL PROTECTED]>
wrote:

>I want to use mod_python, but I'm having trouble. Here's what I have in
>my config:

I've been using cherrypy (cherrypy.org) instead of apache with
mod_python.  In a lot of cases, apache is overkill.  With cherrypy you
can build a web application with a built in web server. It might be
worth a look, it's reasonably easy to use.

Dan


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


Re: Creating Files

2005-05-04 Thread Dan
On Wed, 04 May 2005 10:24:23 +0200, bruno modulix <[EMAIL PROTECTED]>
wrote:

>As in any other language I know : just open it in write mode !-)

Easy when you know how.

Thanks

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


Sockets

2005-05-05 Thread Dan


I have a problem and I don't quite know how to implement the solution.

I'll have a server application that will listen on a tcp port and make
many similtaneous connections to remote clients.  From time to time,
I'll need to write a small amount of data on one of those sockets.  A
notification to write to one of the sockets will come from another
program/process.

I think that the best way to send the notification to this server
application is via a udp message.  Alternatively, I could use tcp, but
I don't think I'll need the extra complexity for what I want to do.
(Other suggestions welcome.)

The server application will multiplex the connections using 'select',
so much of the time it will be blocked on 'select'.

My problem is how to also listen on a udp port while the process is
blocked by 'select'.  Should I run a separate thread?  And if so can I
share the socket connection across the two threads?  (Thread 1 will be
accepting client connections, thread 2 will we writing data to it.)
Or should I simply let 'select' time out after some period?

I'm a bit lost as to how to do this, I hope someone can put me on the
right track.  Any solution that I use should be applicable on Linux
and Windows platforms.

Thanks

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


Controlling source IP address within urllib2

2005-06-03 Thread Dan
Does anybody know how to control the source IP address (IPv4) when
using the urllib2 library?  I have a Linux box with several IP
addresses in the same subnet, and I want to simulate several
individuals within that subnet accessing web pages independently.  I
need the functionality of urllib2 because there will be redirects and
other HTTP-type functions to implement.  It would be nice if I could
create (and bind) sockets myself and then tell the urllib functions to
use those sockets.  Perhaps there is some sort of "back-door" way of
doing this??? Any hints are appreciated!
-Dan

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


Re: Controlling source IP address within urllib2

2005-06-06 Thread Dan
John,
Thanks for your input.  I can kind of see the light in this, but I'm
having difficulty knowing where the "do_open" method comes from.  Also,
I'll need to follow redirects, so I assume then I would add a
HTTPRedirectHandler instance to the urllib2.build_opener. (?)  Thanks
again for your help.
-Dan

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


Re: Controlling source IP address within urllib2

2005-06-08 Thread Dan
John,
Thanks again for your help!
I think that the do_open function in AbstractHTTPHandler does not
return the correct object type as required by the opener.  When I
include the code you recommended, the implementation comes back with
the message, "urlopen error unknown url type: http".  Strange, because
I would think that overriding the "http_open" function in the handler
would have signaled that this function is capable of handling http.  If
I call the HTTPHandler base class "http_open" function from within the
derived class, all works okay, but of course, I don't get to use the
source IP address I wanted to use.
I'll keep trying and let you know what I find.
-Dan

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


Re: Controlling source IP address within urllib2

2005-06-09 Thread Dan
Just FYI ... I finally got this to work.  Unfortunately, I was unable
to use the urllib2 library.  The embedded Linux team here informed me
that the urllib2 library will not be available on the machine I wanted
to deploy on, so I had to go back to using the urllib and httplib
libraries.  After trying several things, I finally gave up and hacked
the library code directly.  It turned out to be quite easy.  I just had
to wedge in a "self.sock.bind()" call in front of the
"self.sock.connect()" call within the HTTPConnection class inside the
httplib library.  (I used the bind() function to nail down the source
IP address of the client.)  Of course, I had to weave in some code that
allowed me to pass the client IP address through the URLopener class in
the urllib library.  Everything seems to work so far.

John, thanks again for your help.  You pointed me in the right
direction.

-Dan

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


Callback scoping

2007-07-05 Thread Dan
So, I think I understand what python's scoping is doing in the
following situation:
>>> x = [ lambda: ind for ind in range(10) ]
>>> x
[ at 0x00BEC070>,  at 0x00BEC7F0>,
 at 0x00BECA70>,  at 0x00C1EBF0>,
 at 0x00C1EE30>,  at 0x00C228F0>,
 at 0x00C228B0>,  at 0x00C28730>,
 at 0x00C286F0>,  at 0x00C287F0>]
>>> x[0]()
9
>>> x[5]()
9
>>> x[9]()
9
>>> ind
9
>>> ind = 2
>>> x[0]()
2
>>>

But, I'm wondering what is the easiest (and/or most pythonic) way to
get the behavior I want? (If you haven't guessed, I want a list of (no
parameter) functions, each of which returns its index in the list.)

-Dan

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


re compiled object result caching?

2007-08-29 Thread Dan

I find myself often using regular expressions in the following
pattern:

foo_re = re.compile(r"foo(bar)")
# . . .
re_result = foo_re.search(line)
if re_result:
bar = re_result.group(1)
# . . .

But, I keep thinking this is awkward, and I would kind of like to have
the re object to cache its result; along the lines of:

foo_re = re.compile(r"foo(bar)")
# . . .
if foo_re.search(line):
foo_re.last_result().group(1)

I realize I could do this with a wrapper object (I'm not sure if I can
subclass the re object..), but I was wondering what the community
thought of this. Good idea? Bad? Would it be difficult to add to the
standard re module? The only real downside I can think of is thread
safety. The other practical benefit I can think of is situations like
the following:

if unlikely_condition and foo_re.search(line):
   # . . .

With the current implementation I think you would either have to do
the search even if unlikely_condition is False, or you would have to
do an annoying nested if. Is there another way to achieve this that
I'm not thinking of?

-Dan

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-10-01 Thread dan
Ken Tilton wrote:
> Kenny happened to solve the traveling 
> salesman problem and protein-folding and passed the fricking Turing test 
> by using add-42 wherever he needed 42 added to a number, and  RMS wants 
> credit and ownership and control of it all. 

That might be what RMS wants (or not, I've never asked him), but it 
doesn't follow from the licence.  What follows from the licence is that 
you have to distribute the derived work as GPL _or not at all_.  I 
practice - if not in marketing terms - that's no more a land grab than a 
proprietary licence saying "you can't use this to add your own numbers 
to 42 at all and if you do we'll eat your brains".

The other consideration is that, and notwitshtanding any text to the 
contrary in the GPL, it's not actually up to the copyright holder to 
define what "derived work" means: it's for the court to decide that. 
Now, I don't want to imply that courts are rational animals that can be 
relied on to understand all the issues in technical cases like this (ha, 
I slay myself) but really, if there's a reasonable concern that an 
implementation of the major advances in computer science you describe 
are legally derivative of someone's function that adds 42 to its 
argument, your legal system is fucked.  Redo from start.


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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-10-03 Thread dan
George Neuner wrote:
> Symbolism over substance has become the mantra
> of the young.

"Symbolism: The practice of representing things by means of symbols or 
of attributing symbolic meanings or significance to objects, events, or 
relationships."

One might even suggest that all written language is based on the use of 
words as symbols.

"Substance: (2)
a. Essential nature; essence.
b. Gist; heart."

"Mantra: A sacred verbal formula repeated in prayer, meditation, or 
incantation, such as an invocation of a god, a magic spell, or a 
syllable or portion of scripture containing mystical potentialities."

Perhaps the young people you're referring to are not the same young 
people that I know, because I've never even heard of a religion whose 
object of reverence is meta-level analysis of language.

Tell me, do you know what "hyperbole" means?


-dan "or 'rhetorical'"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using regular express to analyze lisp code

2007-10-04 Thread Dan
On Oct 4, 1:13 pm, Kelie <[EMAIL PROTECTED]> wrote:
> hello,
>
> i've spent couple of hours trying to figure out the correct regular
> expression to catch a VisualLisp (it is for AutoCAD and has a syntax
> that's similar to common lisp) function body. VisualLisp is case-
> insensitive. Any line beginning with ";" is for comment (can have
> space(s) before ";").
>
> here is an example of VisualLisp function:
>
> (defun get_obj_app_names (obj / rv)
>   (foreach app (get_registered_apps (vla-get-document obj))
> (if (get_xdata obj app)
>   (setq rv (cons app rv))
> )
>   )
>   (if rv
> ;;"This line is comment (comment)"
> ;;) This line is also comment
> (acad_strlsort rv)
> nil
>   )
> )
>
> for a function named foo, it is easy to find the beginning part of the
> function
> "(defun foo", but it is hard to find the ")" at the end of code block.
> if eventually i can't come up with the solution using regular
> expression only, what i was thinking is after finding the beginning
> part, which is "(defun foo" in this case, i can count the parenthesis,
> ignoring anything inside "" and any line for comment, until i find the
> closing ")".
>
> not sure if i've made myself understood. thanks for reading.
>
> kelie

So, paren matching is a canonical context-sensitive algorithm. Now,
many regex libraries have *some* not-purely-regular features, but I
doubt your going to find anything to match parens in a single regex.
If you want to go all out you can use a parser generator (for python
parser generators, see http://python.fyxm.net/topics/parsing.html).
Otherwise, you can go about it the quick-and-dirty way you describe:
scan for matching open and close parens, and ignore things in quotes
and comments.

-Dan

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


Re: How can Python print the value of an attribute but complain it does not exist?

2007-10-10 Thread Dan
On Oct 10, 3:03 pm, Emre  Sevinc <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm a Python newbie and I'm having a strange trouble with the
> following code:
>
> generatefeedvector-debug.py
> ===
> import feedparser
> import re
>
> def getwordcounts(url):
> # Parse the feed
> d = feedparser.parse(url)
> wc = {}
>
> # Loop over all the entries
> for e in d.entries:
> if 'summary' in e: summary = e.summary
> else: summary = e.description
>
> # Extract a list of words
> words = getwords(e.title + ' ' + summary)
> for word in words:
> wc.setdefault(word, 0)
> wc[word] += 1
>
> print d.feed.title
> return d.feed.title
>
> def getwords(html):
> # Remove all the HTML tags
> txt = re.compile(r'<[^>]+>').sub('', html)
>
> # Split words by all non-alpha characters
> words = re.compile(r'[^A-Z^a-z]+').split(txt)
>
> # Convert to lowercase
> return [word.lower() for word in words if word != '']
>
> apcount = {}
> wordcounts = {}
> for feedurl in file('feedlist1-2.txt'):
> title = getwordcounts(feedurl)
> ==
>
> When I run it:
>
> $ python generatefeedvector-debug.py
> Signal vs. Noise
> Traceback (most recent call last):
>   File "generatefeedvector-debug.py", line 37, in ?
> title = getwordcounts(feedurl)
>   File "generatefeedvector-debug.py", line 21, in getwordcounts
> print d.feed.title
>   File "/var/lib/python-support/python2.4/feedparser.py", line 236, in
> __getattr__
> raise AttributeError, "object has no attribute '%s'" % key
> AttributeError: object has no attribute 'title'
>
> The strange thing is that it DOES print the value d.feed.title then
> complains AttributeError: object has no attribute 'title'. What am I
> doing wrong?
>
> The file feedlist1-2.txt includes just a single line:
>
> $ cat feedlist1-2.txthttp://feeds.feedburner.com/37signals/beMH
>
> I'm using Python 2.4 on Debian GNU/Linux.
>
> Any ideas about how to fix this error message?
>
> Regards,
>
> --
> Emre Sevinc

This is a bit of a guess, but prehaps the file has a blank line, so
the first url is fine, but the second (non-existant) url doesn't have
a title. You can test this by doing:

> for feedurl in file('feedlist1-2.txt'):
>if feedurl.strip():
>   title = getwordcounts(feedurl)

-Dan

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


optparse help output

2007-10-24 Thread Dan
I've been using optparse for a while, and I have an option with a
number of sub-actions I want to describe in the help section:

parser.add_option("-a", "--action",
  help=\
"""Current supported actions: create, build, import, exp_cmd and
interact.

create   -- Vaguely depreciated, should create a new project, but it
is
not currently suppored. First create a project in SVN,
then
use import.

build-- Build the project (invoking make usually).

import   -- Put the project under metaman control. Assumes that
the current working directory is a SVN-controlled
sandbox. Metaman checks out its own copy, does analysis
to determine dependencies and the metadata to be
collected.

interact -- Creates a MetaMan object and starts the python interactive
interpreter. Designed for debugging or advanced usage.
The MetaMan object is bound to the identifier 'mm'. Only
use this option if you know what you're doing.

exp_cmd --  add an experiment for strataman.
""")

Unfortunately, when I run the script with --help, this is what I get
for the -a option:
  -aACTION, --action=ACTION
Current supported actions: create, build,
import,
exp_cmd and interact.  create   -- Vaguely
depreciated,
should create a new project, but it
is not
currently suppored. First create a project in
SVN, then
use import.  build-- Build the project
(invoking
make usually).  import   -- Put the project
under
metaman control. Assumes that the
current
working directory is a SVN-controlled
sandbox. Metaman checks out its own copy, does
analysis
to determine dependencies and the metadata to
be
collected.  interact -- Creates a MetaMan
object and
starts the python interactive
interpreter.
Designed for debugging or advanced usage.
The MetaMan object is bound to the identifier
'mm'.
Only use this option if you know
what
you're doing.  exp_cmd --  add an experiment
for
    strataman.

Is there any way to get the formatting I want?

-Dan

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


Re: optparse help output

2007-10-24 Thread Dan
On Oct 24, 12:06 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > I've been using optparse for a while, and I have an option with a
> > number of sub-actions I want to describe in the help section:
>
> > parser.add_option("-a", "--action",
> >   help=\
>
> [snipped formatted help]> """)
>
> > Unfortunately, when I run the script with --help, this is what I get
> > for the -a option:
>
> [snipped munged formatting of help]
>
> > Is there any way to get the formatting I want?
>
> I had the same issue:
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> and was directed by Ben Finney to check out a custom formatter.
> I got it working to my satisfaction and posted it in that thread:
>
> http://groups.google.com/group/comp.lang.python/msg/09f28e26af0699b1
>
> It may be a little more kind in what it does with your help-text.
>   If you need variant behavior you can take my code and mung it
> even further.
>
> The changes are basically a copy&paste (including the comments,
> which Steven D'Aprano suggested might be better made into
> docstrings) of the format_description() and format_option() calls
> from the standard-library's source, and changing a few small
> lines to alter the behavior of calls to textwrap.*
>
> Hope this helps,
>
> -tkc

Thanks, Tim!

That was incredibly helpful. I did alter it to format paragraphs, but
maintain the double newlines. Also, I made a few changes to work with
the 2.3 version of optparse. Posted below for anyone who might want
it. (Also to work as a standalone .py file)

-Dan


# From Tim Chase via comp.lang.python.

from optparse import IndentedHelpFormatter
import textwrap

class IndentedHelpFormatterWithNL(IndentedHelpFormatter):
  def format_description(self, description):
if not description: return ""
desc_width = self.width - self.current_indent
indent = " "*self.current_indent
# the above is still the same
bits = description.split('\n')
formatted_bits = [
  textwrap.fill(bit,
desc_width,
initial_indent=indent,
subsequent_indent=indent)
  for bit in bits]
result = "\n".join(formatted_bits) + "\n"
return result

  def format_option(self, option):
# The help for each option consists of two parts:
#   * the opt strings and metavars
#   eg. ("-x", or "-fFILENAME, --file=FILENAME")
#   * the user-supplied help string
#   eg. ("turn on expert mode", "read data from FILENAME")
#
# If possible, we write both of these on the same line:
#   -xturn on expert mode
#
# But if the opt string list is too long, we put the help
# string on a second line, indented to the same column it would
# start in if it fit on the first line.
#   -fFILENAME, --file=FILENAME
#   read data from FILENAME
result = []
opts = option.option_strings
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
  opts = "%*s%s\n" % (self.current_indent, "", opts)
  indent_first = self.help_position
else: # start help on same line as opts
  opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
  indent_first = 0
result.append(opts)
if option.help:
  help_text = option.help
# Everything is the same up through here
  help_lines = []
  help_text = "\n".join([x.strip() for x in
help_text.split("\n")])
  for para in help_text.split("\n\n"):
help_lines.extend(textwrap.wrap(para, self.help_width))
if len(help_lines):
  # for each paragraph, keep the double newlines..
  help_lines[-1] += "\n"
# Everything is the same after here
  result.append("%*s%s\n" % (
indent_first, "", help_lines[0]))
  result.extend(["%*s%s\n" % (self.help_position, "", line)
for line in help_lines[1:]])
elif opts[-1] != "\n":
  result.append("\n")
return "".join(result)

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


Re: renice

2007-10-26 Thread Dan
On Oct 26, 4:30 am, mokhtar <[EMAIL PROTECTED]> wrote:
> Hi
>
> Is it possible to renice the python process executing the current python
> script ?:confused:
> --
> View this message in 
> context:http://www.nabble.com/renice-tf4695834.html#a13422771
> Sent from the Python - python-list mailing list archive at Nabble.com.

On UNIX:
>>> import os
>>> os.system("renice -n %d %d" % ( new_nice, os.getpid() ) )
(untested)

I don't know if windows has the concept of renice...

-Dan

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


xml.dom.minidom memory usage

2007-02-01 Thread Dan
I'm using python's xml.dom.minidom module to generate xml files, and
I'm running into memory problems. The xml files I'm trying to create
are relatively flat, with one root node which may have millions of
direct child nodes.

Here's an example script:
#!/usr/bin/env python


import xml.dom.minidom


def gen_xml(n):
doc  = xml.dom.minidom.Document()
root = xml.dom.minidom.Element("foo")
root.ownerDocument = doc
root.setAttribute("one", "1")
doc.appendChild(root)
for x in xrange(n):
elem = xml.dom.minidom.Element("bar")
elem.ownerDocument = doc
elem.setAttribute("attr1", "12345678")
elem.setAttribute("attr2", "87654321")
root.appendChild(elem)
return doc


if I run gen_xml(100), my python process ends up using all my 90%
of my memory, and the system ends up thrashing (Linux, P4, 1G ram,
python 2.4.3) .

So, my questions are (1) am I doing something dumb in the script that
stops python from collecting temp garbage? (2) If not, is there
another reasonable module to generate xml (as opposed to parsing it),
or should I just implement my own xml generation solution?

Thanks,
-Dan

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


Re: xml.dom.minidom memory usage

2007-02-01 Thread Dan
On Feb 1, 3:12 pm, Jonathan Curran <[EMAIL PROTECTED]> wrote:
> Dan,
> The DOM (Document Object Model) is such that it loads all the 
> elements of the
> XML document into memory before you can do anything with it. With your file
> containing millions of child nodes this will eat up as much memory as you
> have. A solution to this is to use the SAX method of parsing XML documents
> and working on it. SAX is such that it only reads the XML doc. a node (or a
> few nodes) at a time.
>
> Unfortunately, the use of DOM or SAX completely depends on what kind of
> processing you need to be done on the XML document. If it is editing a record
> at a time (from what I've gathered from your code) it would be wise to use
> SAX. I highly suggest looking into this method of processing.
>
> - Jonathan Curran

Jonathan,

Thanks for the response. I'm comfortable using SAX for parsing, but
I'm unsure how it helps me with XML generation. To clarify in my
example code, with the DOM document, I can call doc.toxml() or
doc.toprettyxml(), and get the desired output (an xml file). AFAIK,
SAX has no analog, it just does parsing. Is there a way to do XML
generation with SAX that I'm unaware of?

-Dan

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


Re: How do I change elements in a list?

2007-11-06 Thread Dan
On Nov 6, 4:11 pm, "Just Another Victim of the Ambient Morality"
<[EMAIL PROTECTED]> wrote:
> How do you change certain elements in a list?  I'm looking to do the
> Python equivalent of this Ruby code:
>
> ->  first = [1, 2]
> =>  [1, 2]
> ->  second = first
> =>  [1, 2]
> ->  first.map! {|i| i + 1}
> =>  [2, 3]
> ->  first
> =>  [2, 3]
> ->  second
> =>  [2, 3]
>
> I need to change a list, in place, so other variables referencing that
> list also see the change.
> Thank you...


>>> first = [1,2]
>>> second = first
>>> for i in range(len(first)):
first[i] += 1

>>> first
[2, 3]
>>> second
[2, 3]

-Dan

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


Re: is it possible to install 2 Python versions on windows XP ?

2007-12-17 Thread Dan
On Dec 17, 11:07 am, Stef Mientki <[EMAIL PROTECTED]>
wrote:
> hello,
>
> I'm currently using Python 2.4,
> and I don't dare to switch to 2.5,
> because I depend heavily on Scipy, which is based on 2.4
>
> To test some other Python programs I need Python version 2.5.
> I've tried to install 2.5 in the past,
> but got a lot of trouble trying to uninstall it to go back to 2.4.
>
> Is there a safe way to install Python 2.5,
> without affecting the Python 2.4 version and  the windows registry,
> on windows XP ?
>
> thanks,
> Stef Mientki

I'm currently running 2.3 and 2.5 on the same XP system with no
problems. As I remember the installs didn't effect each other at all.

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


sybase open client 15_0

2006-05-25 Thread Dan
I have compiled and installed sybase-.037 , the module to add sybase to 
python.  However, when I try to use it I get Import error: 
/usr/local/lib/python2.3/site-packages/sybasect.so

undefined symbol: cs_dt_info

I've seen some posts on the internet with other people having this issue. 
But nothing they've suggested has resolved this issue.  Maybe python just 
needs to be installed again or upgraded to support sybase Open Client.

Thanks,
~DjK 


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


Re: sybase open client 15_0

2006-05-25 Thread Dan
I'm running SLES 9.3 on Tyan with 2 single core 64-bit Opteron & 8 GB of 
memory and SWAP.

OCS-15_0
sybperl-2.18
python 2.3.5



"Dan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I have compiled and installed sybase-.037 , the module to add sybase to 
>python.  However, when I try to use it I get Import error: 
>/usr/local/lib/python2.3/site-packages/sybasect.so
>
> undefined symbol: cs_dt_info
>
> I've seen some posts on the internet with other people having this issue. 
> But nothing they've suggested has resolved this issue.  Maybe python just 
> needs to be installed again or upgraded to support sybase Open Client.
>
> Thanks,
> ~DjK
> 


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


Re: Interesting Thread Gotcha

2008-01-15 Thread Dan
On Jan 15, 10:07 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]>
wrote:
> I thought I would share this nasty little gotcha with the group.
>
> Consider the following code fragment:
>
> 
> print 'starting kbd thread'
> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q))
> print 'starting main loop'
> error = Mainloop(s,port_q,active_q_list)
> 
>
> It produces, as output, the following:
>
> starting kbd thread
> we get here - a
>
> It does not print 'starting main loop', the Mainloop routine
> is never executed, and no exceptions are raised.
>
> Here is the offending routine that seems to capture the control:
>
> 
> def kbd_driver(out_q,in_q):
> """
> thread to look for keyboard input and to put it on the queue out_q
> also looks for replies on in_q and prints them
> """
>
> kbdname = '/dev/stdin'
>
> kbd  = open(kbdname,'r+',1) # Reading, line buffered
>
> unblock(kbd) # Call the magic to unblock keyboard
> print 'we get here - a'
> while True:
>
> try:
> d = kbd.readline()  # see if any kbd input
> except:
> IOError
> try:
> msg=in_q.get(block=False)
> except Queue.Empty:
> time.sleep(0.1)
> continue
> print msg
> time.sleep(0.1)
> continue
> d = d.rstrip()# get rid of line feed
> out_q.put([d + '\r',in_q]) # add a carriage return and return q and 
> send
> to port
> 
>
> The unblock is a routine that unblocks a port using fcntl - it
> is not the problem.  In case you don't believe me, here it is:
>
> def unblock(f):
>  """Given file 'f', sets its unblock flag to true."""
>
> fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
>
> I will post the solution tomorrow when I read my mail,
> if no one has spotted it by then.
>
> - Hendrik

>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q))

Needs to be
>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q))

Commas are important!

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


Re: Interesting Thread Gotcha

2008-01-16 Thread Dan
On Jan 16, 11:06 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Hendrik van Rooyen wrote:
> > "Dan"  wrote:
>
> >> >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q))
>
> >> Needs to be
> >> >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q))
>
> >> Commas are important!
>
> >> -Dan
>
> > Absolutely! - well spotted!
>
> > As the first correct respondent, you win the freedom to spend a week in
> > Naboomspruit at your own expense.
>
> > It would have been nice, however, to have gotten something like:
>
> > TypeError - This routine needs a tuple.
>
> > instead of the silent in line calling of the routine in question,
> > while failing actually to start a new thread.
>
> You can't prevent the silent inline-calling - otherwise, how would you do
> this:
>
> def compute_thread_target():
> def target():
> pass
> return target
>
> thread.start_new_thread(compute_thread_target())
>
> Of course start_new_thread could throw an error if it got nothing callable
> as first argument. No idea why it doesn't.
>
> Diez

Of course, in his case, having start_new_thread throw an error
wouldn't have helped, since he went into an infinite loop while
evaluating the parameters for start_new_thread.

Would it be possible to have pychecker (or some such) warn that there
is an insufficient parameter count to start_new_thread? I guess that
would require knowing the type of thread. . .

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


Re: Interesting Thread Gotcha

2008-01-16 Thread Dan
On Jan 16, 1:33 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Dan schrieb:
>
>
>
> > On Jan 16, 11:06 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> Hendrik van Rooyen wrote:
> >>> "Dan"  wrote:
> >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q))
> >>>> Needs to be
> >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q))
> >>>> Commas are important!
> >>>> -Dan
> >>> Absolutely! - well spotted!
> >>> As the first correct respondent, you win the freedom to spend a week in
> >>> Naboomspruit at your own expense.
> >>> It would have been nice, however, to have gotten something like:
> >>> TypeError - This routine needs a tuple.
> >>> instead of the silent in line calling of the routine in question,
> >>> while failing actually to start a new thread.
> >> You can't prevent the silent inline-calling - otherwise, how would you do
> >> this:
>
> >> def compute_thread_target():
> >> def target():
> >> pass
> >> return target
>
> >> thread.start_new_thread(compute_thread_target())
>
> >> Of course start_new_thread could throw an error if it got nothing callable
> >> as first argument. No idea why it doesn't.
>
> >> Diez
>
> > Of course, in his case, having start_new_thread throw an error
> > wouldn't have helped, since he went into an infinite loop while
> > evaluating the parameters for start_new_thread.
>
> > Would it be possible to have pychecker (or some such) warn that there
> > is an insufficient parameter count to start_new_thread? I guess that
> > would require knowing the type of thread. . .
>
> What has this to do with the second argument? It's perfectly legal to
> have a function as thread-target that takes no arguments at all, so
> enforcing a second argument wouldn't be helpful - all it would do is to
> force all developers that don't need an argument tuple to pass the empty
> tuple. So there was no insufficient argument count.
>
> And none of these would solve the underlying problem that in python
> expressions are evaluated eagerly. Changing that would mean that you end
> up with a totally new language.
>
> the only thing that could help to a certain extend would be static
> types. Which we don't want here :)
>
> Diez

It doesn't seem to be legal in my version of python (or the doc):

>>> import thread
>>> def bat():
print "hello"


>>> thread.start_new_thread(bat)

Traceback (most recent call last):
  File "", line 1, in 
thread.start_new_thread(bat)
TypeError: start_new_thread expected at least 2 arguments, got 1
>>> thread.start_new_thread(bat, ())
2256hello


>>>

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


Re: How to manipulate elements of a list in a single line of code?

2008-02-25 Thread Dan
On Feb 25, 4:39 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
> I would like to translate the contents of a list. For instance, let's
> say I've got a list of strings and I want to append "foo" to each
> element. I might do the following;
>
>   list1 = ['a', 'b', 'c']
>   for i in range(0, len(list1)): list1[i] += 'foo'
>
> Ok, that much works. But what if I don't want to modify the contents
> of list1. Instead, I want list2 to hold the modified contents, like
> so:
>
> 1  list1 = ['a', 'b', 'c']
> 2  list2 = []
> 3  for item in list1: list2.append(item + 'foo')
>
> Is there a way to express lines 2-3 sort-of ilke this:
>
>   list2 = [ for item in list1: item + 'foo' ]
>
> Any ideas?
>
> Thanks,
> --Steve

You're so close.

>>> list2 = [ item+"foo" for item in list1 ]

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


Python 3 and my Mac (Leopard)

2008-12-24 Thread Dan
Wanted to learn python, got Mark Summerfield's new book "Programming in 
Python 3".  Having a hard time getting python 3 and IDLE working on my 
Mac with Leopard.  The mac "resources" on the python.org site seem a 
bit out of date, and don't really mention python 3.  Are there any 
resources out there?  Is the python community just not interested in 
Macs?  I've tried googling and the usual search strategies.  Any help 
would be appreciated.


DAN

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


Re: Is there any way to find out the definition of a function in a file of C language?

2009-04-16 Thread Dan

you rule, just for your sig...  Zork in all forms ftw

namekuseijin wrote:

Jebel escreveu:

Hi ,everyone. I have the name of a function of C language, and have
the source file which the function is defined in. And I want to find
out the type and name of the parameters. If I need to analyze the file
by myself, or have some way to do it more easily?


ever heard of grep?  ctags for vim or emacs?


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


Re: ask for a RE pattern to match TABLE in html

2008-06-27 Thread Dan
On Jun 27, 1:32 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
> In article
> <[EMAIL PROTECTED]>,
>  Jonathan Gardner <[EMAIL PROTECTED]> wrote:
>
> > On Jun 26, 3:22 pm, MRAB <[EMAIL PROTECTED]> wrote:
> > > Try something like:
>
> > > re.compile(r'.*?', re.DOTALL)
>
> > So you would pick up strings like "foo > td>"? I doubt that is what oyster wants.
>
> I asked a question recently - nobody answered, I think
> because they assumed it was just a rhetorical question:
>
> (i) It's true, isn't it, that it's impossible for the
> formal CS notion of "regular expression" to correctly
> parse nested open/close delimiters?

Yes. For the proof, you want to look at the pumping lemma found in
your favorite Theory of Computation textbook.

>
> (ii) The regexes in languages like Python and Perl include
> features that are not part of the formal CS notion of
> "regular expression". Do they include something that
> does allow parsing nested delimiters properly?

So, I think most of the extensions fall into syntactic sugar
(certainly all the character classes \b \s \w, etc). The ability to
look at input without consuming it is more than syntactic sugar, but
my intuition is that it could be pretty easily modeled by a
nondeterministic finite state machine, which is of equivalent power to
REs. The only thing I can really think of that is completely non-
regular is the \1 \2, etc syntax to match previously match strings
exactly. But since you can't to an arbitrary number of them, I don't
think its actually context free. (I'm not prepared to give a proof
either way). Needless to say that even if you could, it would be
highly impractical to match parentheses using those.

So, yeah, to match arbitrary nested delimiters, you need a real
context free parser.

>
> --
> David C. Ullrich


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


Re: For_loops hurt my brain.

2008-07-16 Thread Dan
On Jul 16, 1:42 pm, [EMAIL PROTECTED] wrote:
> This script uses a simple for loop to zip some files. However I am
> repeating code that cries out for a nested loop. My two lists of
> files_to_be_zipped (spare and seekfacts) are of uneven length so I
> can't seem to decipher the "for_logic". I would appreciate any help.
> Thanks, Bill
>
> import zipfile
> import os
>
> zips = [
> 'c:/spare.zip',
> 'c:/seekfacts.zip'
> ]
> spare = [
> 'c:/spare/huge.fm3',
> 'c:/spare/huge.wk3'
> ]
> seekfacts = [
> 'c:/seekfacts/bookmark.html',
> 'c:/seekfacts/index.htm',
> 'c:/seekfacts/seek.css',
> 'c:/seekfacts/seek.js'
> ]
>
> zFile = zipfile.ZipFile(zips[0], 'w')
> for files in spare:
> zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED)
> zFile.close()
>
> zFile = zipfile.ZipFile(zips[1], 'w')
> for files in seekfacts:
> zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED)
> zFile.close()

I would do something like this:
# UNTESTED

import zipfile
import os

zip_dict = { 'spare' : ['c:/spare.zip', 'c:/seekfacts.zip'],
 'seekfacts' : [
'c:/seekfacts/bookmark.html',
'c:/seekfacts/index.htm',
'c:/seekfacts/seek.css',
'c:/seekfacts/seek.js'
] }

for key,value in zip_dict.items():
zFile = zipfile.ZipFile("c:/%s.zip" % key, 'w')
    for fname in value:
zFile.write(fname, os.path.basename(files),
zipfile.ZIP_DEFLATED)
zFile.close()

# End untested code.

This implicitly maps thing with the key foo to the zip file c:/
foo.zip, but if you want to be more general, I would suggest thinking
about making a class.

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


Re: interpreter vs. compiled

2008-07-18 Thread Dan
On Jul 18, 2:17 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Jul 17, 11:39 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 18 Jul., 01:15, castironpi <[EMAIL PROTECTED]> wrote:
>
> > > On Jul 17, 5:37 pm, I V <[EMAIL PROTECTED]> wrote:
>
> > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote:
> > > > > The Python disassembly is baffling though.
>
> > > > >>>> y= 3
> > > > >>>> dis.dis('x=y+1')
>
> > > > You can't disassemble strings of python source (well, you can, but, as
> > > > you've seen, the results are not meaningful). You need to compile the
> > > > source first:
>
> > > > >>> code = compile('y=x+1','-', 'single')
> > > > >>> dis.dis(code)
>
> > > >   1   0 LOAD_NAME0 (x)
> > > >   3 LOAD_CONST   0 (1)
> > > >   6 BINARY_ADD
> > > >   7 STORE_NAME   1 (y)
> > > >  10 LOAD_CONST   1 (None)
> > > >  13 RETURN_VALUE
>
> > > > You may well find these byte codes more meaningful. Note that there is a
> > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html
>
> > > Oh.  How is the stack represented?
>
> > As a pointer to a pointer of PyObject structs.
>
> > > Does it keep track of which stack
> > > positions (TOS, TOS1, etc.) are in what registers?  Does stack
> > > manipulation consume processor cycles?
>
> > Python does not store values in registers. It stores locals in arrays
> > and accesses them by position ( you can see the positional index in
> > the disassembly right after the opcode name ) and globals / object
> > attributes in dicts.
>
> > For more information you might just download the source distribution
> > and look for src/Python/ceval.c. This file contains the main
> > interpreter loop.
>
> Ah, found it.  The parts that are making sense are:
>
> register PyObject **stack_pointer;
> #define TOP()   (stack_pointer[-1])
> #define BASIC_POP() (*--stack_pointer)
>
> ...(line 1159)...
> w = POP();
> v = TOP();
> if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
> /* INLINE: int + int */
> register long a, b, i;
> a = PyInt_AS_LONG(v);
> b = PyInt_AS_LONG(w);
> i = a + b;
> if ((i^a) < 0 && (i^b) < 0)
> goto slow_add;
> x = PyInt_FromLong(i);
>
> ... Which is more than I was picturing was involved.  I understand it
> is also specific to CPython.  Thanks for the pointer to the code.
>
> My basic question was, what is the difference between compilers and
> interpreters, and why are interpreters slow?  I'm looking at some of
> the answer right now in "case BINARY_ADD:".

The basic difference between a (traditional) compiler and an
interpreter is that a compiler emits (assembly) code for a specific
machine. Therefore it must know the specifics of the machine (how many
registers, memory addressing modes, etc), whereas interpreters
normally define themselves by their conceptual state, that is, a
virtual machine. The instructions (bytecode) of the virtual machine
are generally more high-level than real machine instructions, and the
semantics of the bytecode are implemented by the interpreter, usually
in a sort-of high level language like C. This means the interpreter
can run without detailed knowledge of the machine as long as a C
compiler exists. However, the trade off is that the interpreter
semantics are not optimized for that machine.

This all gets a little more hairy when you start talking about JITs,
runtime optimizations, and the like. For a real in-depth look at the
general topic of interpretation and virtual machines, I'd recommend
Virtual Machines by Smith and Nair (ISBN:1-55860910-5).

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


Regex on a huge text

2008-08-22 Thread Dan
I'm looking on how to apply a regex on a pretty huge input text (a file
that's a couple of gigabytes). I found finditer which would return results
iteratively which is good but it looks like I still need to send a string
which would be bigger than my RAM. Is there a way to apply a regex directly
on a file?

Any help would be appreciated.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python one-liner??

2008-08-22 Thread Dan
On Fri, Aug 22, 2008 at 4:13 PM, Wojtek Walczak <[EMAIL PROTECTED]> wrote:

> -c?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Yup. Stands for command

python -c "print 'Hello World!'"
Hello World!
--
http://mail.python.org/mailman/listinfo/python-list

Should Python raise a warning for mutable default arguments?

2008-08-22 Thread Dan
> Further, the tutorial is the first link on the python for programmers page,
> and on the non-programmers page it's the last link, so presumably any
> non-programmer continuing on is pointed to the next step.
>
> ... so as to emphasized enough, how more?
>
> Emile


In my experience, the problem is that usually, newbies upon reaching that
part of the tutorial do not understand it. I'd suggest that at the end of
the tutorial, when people have a better general idea of how Python works,
there would be a Python Gotchas section.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Is there no end to Python?

2006-03-18 Thread dan
Steve wrote:

"""No need for flames. I'll content myself with pointing out that most
1.5.2 programs will run unchanged in 2.5, so the backwards
compatibility
picture is very good. Nobody makes you use the new features!""

Nobody makes you use new features, true...unless you are relying on a
library or module that uses them...;-)

cheers,
   Dan

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


COM Client / Server creation?

2006-03-22 Thread Dan
New to python. Running under windows xp. Need help getting started
writing COM server and client. Want to basically have two interfaces on
the server, register() and fire_event1(). register registers a client
to receive the fire_event1() event. The client will then need an event
handler implemented to receive the events. Each new client that calls
register should be tracked in the server so that all of the clients
receive the event. I have done this very easiliy with traditional
programming languages but don't reall know where to start here. Dan

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


Re: COM Client / Server creation?

2006-03-22 Thread Dan
Ive got the chapter from the net on COM. It looks pretty old, 2000.
Also the very first example in the chapter on COM doesn't seem to work.
Is what I am wanting to do possible with Python?

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


Re: COM Client / Server creation?

2006-03-23 Thread Dan
>>What went wrong...
Operator Error. My appologies. If typed in correctly the example works
perfectly. I was using the PythonWin shell and when I started to type
in it suggested CDispatch and I typed that in. I will be looking to
pick up a copy of the book if I continue to use Python. I still do not
know if it will be sufficient to my purposes. It looks like a very
powerful scripting language. Dan

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


  1   2   3   4   5   6   7   8   9   10   >