Re: Python critique

2010-12-11 Thread Octavian Rasnita
From: "Steven D'Aprano" 
...
>> Can you please tell me how to write the following program in Python?
>> 
>> my $n = 1;
>> 
>> {
>>   my $n = 2;
>>   print "$n\n";
>> }
>> 
>> print "$n\n";
>> 
>> If this program if ran in Perl, it prints: 
>> 2
>> 1
> 
> Lots of ways. Here's one:
> 
> 
> n = 1
> 
> class Scope:
>n = 2
>print n
> 
> print n
> 
> 
> 
> Here's another:
> 
> n = 1
> print (lambda n=2: n)()
> print n
> 
> 
> 
> Here's a third:
> 
> n = 1
> 
> def scope():
>n = 2
>print n
> 
> scope()
> print n
> 
> 
> Here's a fourth:
> 
> import sys
> n = 1
> (sys.stdout.write("%d\n" % n) for n in (2,)).next()
> print n
> 
> 
> In Python 3, this can be written more simply:
> 
> n = 1
> [print(n) for n in (2,)]
> print n
> 
> 
> 
>> I have tried to write it, but I don't know how I can create that block
>> because it tells that there is an unexpected indent.
> 
> Functions, closures, classes and modules are scopes in Python. If you 
> want a new scope, create one of those.
> 
> 
> 
> -- 
> Steven


Hi Steven,

Thank you for your message. It is very helpful for me.
I don't fully understand the syntax of all these variants yet, but I can see 
that there are more scopes in Python than I thought, and this is very good.

Octavian

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


Re: run a function in another processor in python

2010-12-11 Thread Peter Otten
Astan Chee wrote:

> Sorry about that, here is a summary of my complete code. I haven't cleaned
> it up much or anything, but this is what it does:
> 
> import time
> import multiprocessing
> 
> test_constx =0
> test_consty =0
> 
> def functionTester(x):
>   global test_constx

You don't need to declare a variable as global unless you want to rebind 
(assign to) it.

>   global test_consty
>   print "constx " + str(test_constx)
>   print "consty " + str(test_consty)
>   return (test_constx*x[0]-x[1]+test_consty*x[0]+x[2])
> 
> def functionTesterMain(constx,consty):
>   global test_constx
>   global test_consty
>   test_constx = constx
>   test_consty = consty
>   num_args =
> [(61,12,1),(61,12,2),(61,12,3),(61,11,4),(61,12,4),(62,33,4),(7,12,4),
(16,19,4),(35,36,4),(37,38,3),(55,56,3),(57,63,3)]
>   num_processes = multiprocessing.cpu_count()
>   pool = multiprocessing.Pool(num_processes)

I think you need to create the pool outside the function; in the current 
configuration you get three not one Pool instance.

>   rs = []
>   start = time.time()
>   rs = pool.map(functionTester,num_args)
>   end = time.time()
>   elapsed= end - start
>   min = elapsed/60
>   print "Took", elapsed, "seconds to run, which is the same as", min,
> "minutes"
>   pos = 0
>   high = 0
>   n = None
>   for r in rs:
> if r > high:
>   n = num_args[pos]
>   high = r
> pos+=1
>   print "high " + str(high)
>   print "n " + str(n)
> 
>   return high,n
> 
> if __name__ == '__main__':
>   for i in range(1,4):
> a,b = functionTesterMain(i,7)
> print "---"
> print "a " + str(a)
> print "b " + str(a)
> 
> 
>   Which doesn't seem to work because the functionTester() needs to be
> simpler and not use global variables.
> I'm using global variables because I'm also trying to pass a few other
> variables and I tried using a class but that just gave me a unpickleable
> error. I tried using zip but I'm confused with how I can get to pass the
> data.

A simple approach would be to pass an index into a list

const_data = zip(range(1, 4), [7]*3)

> I know I can probably combine the data into tuples but that means that
> there is alot of data duplication, especially if the constx and consty are
> large dictionaries (or even custom objects), which might happen later.
> So it seems that map doesn't quite like functions like these. Anyway, I'll
> try and see if threads or something can substitute. I'd appriciate any 
help. Thanks

Your code, slightly modified and cleaned up (yes, four-space indent improves 
readability):

import time
import multiprocessing

const_data = zip(range(1, 4), [7]*3)
num_args = [(61, 12, 1), (61, 12, 2), (61, 12, 3), (61, 11, 4), 
(61, 12, 4), (62, 33, 4), (7, 12, 4), (16, 19, 4), 
(35, 36, 4), (37, 38, 3), (55, 56, 3), (57, 63, 3)]

def functionTester(args):
i, x, y, z = args
constx, consty = const_data[i]

print "constx", constx
print "consty", consty
return constx*x - y + consty*x + z

def functionTesterMain(pool, index):
start = time.time()
rs = pool.map(functionTester, (((index, ) + x) for x in num_args))
end = time.time()
elapsed = end - start
min = elapsed/60
print "Took", elapsed, 
print "seconds to run, which is the same as", min, "minutes"
return max(zip(rs, num_args))

if __name__ == '__main__':
num_processes = multiprocessing.cpu_count()
pool = multiprocessing.Pool(num_processes)
for i, _ in enumerate(const_data):
a, b = functionTesterMain(pool, i)
print "---"
print "a", a
print "b", b


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


how to read o/p of telenet (python) ?!

2010-12-11 Thread Darshak Bavishi
hi experts ,

i have code to telnet remote machine (unix)
i am using port 5400 to telnet but o/p is not in visible format when i run
random commands or run

when i give as read_some() it displays some lines but in case of read_all()
it gets hang !!

In actual i want to get some string from o/p and process pls help


[code]

import getpass
import sys
import telnetlib
import time
HOST = "hostname"
#user = raw_input("Enter your remote account: ")
#password = getpass.getpass()


user = "hostname"
password = "ABC"


tn = telnetlib.Telnet(HOST , 5400)
print "1"

print "2"
tn.write(user + "\n")
print "3"
if password:
tn.read_until("Password: ")
tn.write(password + "\n")

print "4"
tn.write("set alarm = off" + "\n")
tn.write("set event = off" + "\n")

print "5"
tn.write("Cd /Office-Parameters/" + "\n")

print "6"

tn.write("\n")
tn.write("\n")

tn.write("vlrsubquery msisdn=***" + "\n")
tn.write("\n")

print tn.read_all()

tn.write("exit" + "\n")

tn.close()
-- 
BR
Darshak Bavishi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python critique

2010-12-11 Thread Lie Ryan
On 12/11/10 11:37, Dan Stromberg wrote:
> On Fri, Dec 10, 2010 at 3:51 PM, John Nagle  wrote:
>> On 12/10/2010 3:25 PM, Stefan Behnel wrote:
>>> Benjamin Kaplan, 11.12.2010 00:13:
 On Fri, Dec 10, 2010 at 5:46 PM, Octavian Rasnita wrote:
 The only scopes Python has are module and function.
>>
>> There's more.  Both a lambda, and in Python 3.x,
>> list comprehensions, introduce a new scope.
> 
> And classes and methods.

Also, class scope and instance scope, though similar, are distinct
scopes. Python also have the hidden interpreter-level scope (the
__builtins__).
-- 
http://mail.python.org/mailman/listinfo/python-list


Python distribution recommendation?

2010-12-11 Thread Octavian Rasnita
Hi,

Is there a "recommended" Python distribution for Windows XP?

I know about the one that can be downloaded from python.org (which I am using 
for the moment) and the one offered by ActiveState but I don't know which one 
is better for a beginner nor if there are other distributions available.

I am especially interested in creating MS Windows apps with Python.

Thanks.

Octavian

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


Re: Python distribution recommendation?

2010-12-11 Thread Katie T
On Sat, Dec 11, 2010 at 12:43 PM, Octavian Rasnita  wrote:
> Hi,
>
> Is there a "recommended" Python distribution for Windows XP?

Either will work, although the python.org one is the more popular and
is likely the one used by most tutorials and beginners guides. The
ActiveState one bundles PyQT if  you want to build apps with GUIs
using QT (although it's fairly trivial to install with the regular
Python as well).

Katie
--
CoderStack
http://www.coderstack.co.uk
The Software Developer Job Board
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python distribution recommendation?

2010-12-11 Thread Lie Ryan
On 12/11/10 23:43, Octavian Rasnita wrote:
> Hi,
> 
> Is there a "recommended" Python distribution for Windows XP?
> 
> I know about the one that can be downloaded from python.org (which I am using 
> for the moment) and the one offered by ActiveState but I don't know which one 
> is better for a beginner nor if there are other distributions available.
> 
> I am especially interested in creating MS Windows apps with Python.
> 

ActiveState comes with more third party libraries, if you're developing
python and do not want to install those libraries yourself, they're the
way to go to. However, if you only need to use standard libraries, or
want to target the broadest possible platforms with very little
dependencies, then you should use python.org's version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python distribution recommendation?

2010-12-11 Thread Godson Gera
On Sat, Dec 11, 2010 at 6:13 PM, Octavian Rasnita wrote:

>
>
> I am especially interested in creating MS Windows apps with Python.
>

If you want to access win32api and do some COM programming then ActiveState
comes bundled with pywin32. Where in vanilla python distro you have to
install those packages separately by downloading them.  ActiveState is the
same python with additional batteries included.

-- 
Python Consultant India 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance has no __call__ method

2010-12-11 Thread Steve Holden
On 12/10/2010 5:20 AM, frank cui wrote:
> Hi all,
> 
> I'm a novice learner of python and get caught in the following trouble
> and hope experienced users can help me solve it:)
> 
> Code:
> ---
> $ cat Muffle_ZeroDivision.py
> #!/usr/bin/env python
> 
> class MuffledCalculator:
> muffled = False
> def clac(self,expr):
> try:
> return eval(expr)
> except:
> if self.muffled:
> print 'Division by zero is illegal'
> else:
> raise
> --
> 
> $ python
> Python 2.7 (r27:82500, Sep 16 2010, 18:03:06)
> [GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import Muffle_ZeroDivision
 calc = Muffle_ZeroDivision.MuffledCalculator()
 calc = ('10/2')
 calc = Muffle_ZeroDivision.MuffledCalculator()
 calc('10/2')
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: MuffledCalculator instance has no __call__ method
> 
> 
> 
> There is an AttributeError that this instance doesn't have the __call__
> method, so how to add this kind of method to my instance?
> 
> Thanks a lot in advance.
> 
> Regards
> Frank.Cui
> 
Try renaming your .calc() method to .__call__(). That way the method
will be called when you perform a function call on an instance.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python distribution recommendation?

2010-12-11 Thread Octavian Rasnita
Ok, thank you all for your recommendations.

I think I will install ActivePython because it seems that it offers more 
features for Windows programming than the other distro (by default, which is 
important for a beginner).

I will use WxPython and not other GUIS like QT, Tk or GTK because they are not 
accessible for screen readers, so I will also need to install WxPython if 
ActiveState's Python doesn't include it.

Octavian

- Original Message - 
From: "Godson Gera" 
To: "Octavian Rasnita" 
Cc: 
Sent: Saturday, December 11, 2010 4:02 PM
Subject: Re: Python distribution recommendation?


> On Sat, Dec 11, 2010 at 6:13 PM, Octavian Rasnita wrote:
> 
>>
>>
>> I am especially interested in creating MS Windows apps with Python.
>>
> 
> If you want to access win32api and do some COM programming then ActiveState
> comes bundled with pywin32. Where in vanilla python distro you have to
> install those packages separately by downloading them.  ActiveState is the
> same python with additional batteries included.
> 
> -- 
> Python Consultant India 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 64 bit memory usage

2010-12-11 Thread Steve Holden
On 12/10/2010 2:03 PM, Rob Randall wrote:
> I manged to get my python app past 3GB on a smaller 64 bit machine.
> On a test to check memory usage with gc disabled only an extra 6MB was
> used.
> The figures were 1693MB to 1687MB.
> 
> This is great.
> 
> Thanks again for the help.

Do remember, though, that with the GC turned off you will "lose" memory
if you accidentally create cyclic data structures, since they will never
be reclaimed. It doesn't sound like this is an issue, but I wanted this
to act as a warning to others who might come across your solution but
have programmed less carefully.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Integrating doctest with unittest

2010-12-11 Thread Steven D'Aprano
I have a module with doctests, and a module that performs unit testing 
for it. The test module looks like this:


import doctest
import unittest

import module_to_test

# ...
# many test suites
# ...

if __name__ == '__main__':
doctest.testmod(module_to_test)
unittest.main()



but now I'd like to integrate the doctests with the unittests. I thought 
I could follow the instructions here:

http://docs.python.org/py3k/library/doctest.html#unittest-api


so I added a line:


doc_test_suite = doctest.DocTestSuite(module=module_to_test)


expecting that it would be found by unittest.main(), but it is not. I 
imagine this is because DocTestSuite returns a TestSuite instance, while 
the unittest test finder only looks for classes.

I realise that I could manually run the doc_test_suite with this:

unittest.TextTestRunner().run(doc_test_suite)

but this leads to two test outputs:

Ran 100 tests in 3.037s
OK

Ran 10 tests in 0.012s
OK


instead of combining them:

Ran 110 tests in 3.049s
OK


Is there a way to have unittest.main() find and run doc_test_suite 
together with the other test suites?



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


python-parser running Beautiful Soup needs to be reviewed

2010-12-11 Thread Martin Kaspar
Hello commnity

i am new to Python and to Beatiful Soup also!
It is told to be a great tool to parse and extract content. So here i
am...:

I want to take the content of a -tag of a table in a html
document. For example, i have this table




 This is a sample text



 This is the second sample text




How can i use beautifulsoup to take the text "This is a sample text"?

Should i make use
soup.findAll('table' ,attrs={'class':'bp_ergebnis_tab_info'}) to get
the whole table.

See the target 
http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=799.601437941842&SchulAdresseMapDO=142323

Well - what have we to do first:

The first thing is t o find the table:

i do this with Using find rather than findall returns the first item
in the list
(rather than returning a list of all finds - in which case we'd have
to add an extra [0]
to take the first element of the list):


table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})

Then use find again to find the first td:

first_td = soup.find('td')

Then we have to use renderContents() to extract the textual contents:

text = first_td.renderContents()

... and the job is done (though we may also want to use strip() to
remove leading and trailing spaces:

trimmed_text = text.strip()

This should give us:


print trimmed_text
This is a sample text

as desired.


What do you think about the code? I love to hear from you!?

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


Re: python-parser running Beautiful Soup needs to be reviewed

2010-12-11 Thread Nitin Pawar
try using lxml ... its very useful

On Sat, Dec 11, 2010 at 11:24 AM, Martin Kaspar  wrote:

> Hello commnity
>
> i am new to Python and to Beatiful Soup also!
> It is told to be a great tool to parse and extract content. So here i
> am...:
>
> I want to take the content of a -tag of a table in a html
> document. For example, i have this table
>
> 
>
>
> This is a sample text
>
>
>
> This is the second sample text
>
>
> 
>
> How can i use beautifulsoup to take the text "This is a sample text"?
>
> Should i make use
> soup.findAll('table' ,attrs={'class':'bp_ergebnis_tab_info'}) to get
> the whole table.
>
> See the target
> http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=799.601437941842&SchulAdresseMapDO=142323
>
> Well - what have we to do first:
>
> The first thing is t o find the table:
>
> i do this with Using find rather than findall returns the first item
> in the list
> (rather than returning a list of all finds - in which case we'd have
> to add an extra [0]
> to take the first element of the list):
>
>
> table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})
>
> Then use find again to find the first td:
>
> first_td = soup.find('td')
>
> Then we have to use renderContents() to extract the textual contents:
>
> text = first_td.renderContents()
>
> ... and the job is done (though we may also want to use strip() to
> remove leading and trailing spaces:
>
> trimmed_text = text.strip()
>
> This should give us:
>
>
> print trimmed_text
> This is a sample text
>
> as desired.
>
>
> What do you think about the code? I love to hear from you!?
>
> greetings
> matze
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Making os.unlink() act like "rm -f"

2010-12-11 Thread Roy Smith
I just wrote an annoying little piece of code:

try:
os.unlink("file")
except OSError:
   pass

The point being I want to make sure the file is gone, but am not sure if 
it exists currently.  Essentially, I want to do what "rm -f" does in the 
unix shell.

In fact, what I did doesn't even do that.  By catching OSError, I catch 
"No such file or directory" (which is what I want), but I also catch 
lots of things I want to know about, like "Permission denied".  I could 
do:

if os.access("file", os.F_OK):
   os.unlink("file")

but that's annoying too.  What would people think about a patch to 
os.unlink() to add an optional second parameter which says to ignore 
attempts to remove non-existent files (just like "rm -f")?  Then you 
could do:

os.unlink("file", ignore=True)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making os.unlink() act like "rm -f"

2010-12-11 Thread Christian Heimes
Am 11.12.2010 18:04, schrieb Roy Smith:
> if os.access("file", os.F_OK):
>os.unlink("file")
> 
> but that's annoying too.  What would people think about a patch to 
> os.unlink() to add an optional second parameter which says to ignore 
> attempts to remove non-existent files (just like "rm -f")?  Then you 
> could do:

-1

os.unlink is a small wrapper around the unlink(2) function.

You want to ignore the ENOENT error number and re-raise the exception
for other errors:

try:
   os.unlink("file")
except OSError, e:
   if e.errno != errno.ENOENT:
  raise

You may be interested in EISDIR, too. unlink() doesn't remove directories.

Christian

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


Re: Making os.unlink() act like "rm -f"

2010-12-11 Thread Nobody
On Sat, 11 Dec 2010 12:04:01 -0500, Roy Smith wrote:

> I just wrote an annoying little piece of code:
> 
> try:
> os.unlink("file")
> except OSError:
>pass
> 
> The point being I want to make sure the file is gone, but am not sure if
> it exists currently.  Essentially, I want to do what "rm -f" does in the
> unix shell.
> 
> In fact, what I did doesn't even do that.  By catching OSError, I catch
> "No such file or directory" (which is what I want), but I also catch lots
> of things I want to know about, like "Permission denied".

import errno
try:
os.unlink("file")
except OSError as e:
if e.errno != errno.ENOENT:
raise

> I could do:
> 
> if os.access("file", os.F_OK):
>os.unlink("file")
> 
> but that's annoying too.

It also has a race condition. EAFP is the right approach here.

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


Re: Making os.unlink() act like "rm -f"

2010-12-11 Thread Godson Gera
On Sat, Dec 11, 2010 at 10:34 PM, Roy Smith  wrote:

> os.unlink("file", ignore=True)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Take a look at shutil.rmtree
http://docs.python.org/library/shutil.html?highlight=shutil#shutil.rmtree


-- 
Thanks & Regards,
Godson Gera
Python Consultant India 
-- 
http://mail.python.org/mailman/listinfo/python-list


Enabling the use of POSIX character classes in Python

2010-12-11 Thread Perry Johnson
Python's re module does not support POSIX character classes, for
example [:alpha:]. It is, of course, trivial to simulate them using
character ranges when the text to be matched uses the ASCII character
set. Sadly, my problem is that I need to process Unicode text. The re
module has its own character classes that do support Unicode, however
they are not sufficient.

I would find it extremely useful if there was information on the
Unicode code points that map to each of the POSIX character classes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to read o/p of telenet (python) ?!

2010-12-11 Thread Ian Kelly

On 12/11/2010 4:20 AM, Darshak Bavishi wrote:

i have code to telnet remote machine (unix)
i am using port 5400 to telnet but o/p is not in visible format when i
run random commands or run


What is "o/p"?


when i give as read_some() it displays some lines but in case of
read_all() it gets hang !!


read_all() blocks until the server closes the connection.  If the server 
is waiting for a command, then it will be blocking for a long time.


Try sending the "exit" command before you call read_all().  The server 
should finish processing the previous command before exiting, so you 
will still receive all of the requested data.


Cheers,
Ian

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


Re: Enabling the use of POSIX character classes in Python

2010-12-11 Thread MRAB

On 11/12/2010 17:33, Perry Johnson wrote:

Python's re module does not support POSIX character classes, for
example [:alpha:]. It is, of course, trivial to simulate them using
character ranges when the text to be matched uses the ASCII character
set. Sadly, my problem is that I need to process Unicode text. The re
module has its own character classes that do support Unicode, however
they are not sufficient.

I would find it extremely useful if there was information on the
Unicode code points that map to each of the POSIX character classes.


Have a look at the new regex implementation on PyPI:

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


Re: Enabling the use of POSIX character classes in Python

2010-12-11 Thread Martin v. Loewis
Am 11.12.2010 18:33, schrieb Perry Johnson:
> Python's re module does not support POSIX character classes, for
> example [:alpha:]. It is, of course, trivial to simulate them using
> character ranges when the text to be matched uses the ASCII character
> set. Sadly, my problem is that I need to process Unicode text. The re
> module has its own character classes that do support Unicode, however
> they are not sufficient.
> 
> I would find it extremely useful if there was information on the
> Unicode code points that map to each of the POSIX character classes.

By definition, this is not possible. The POSIX character classes are
locale-dependent, whereas the recommendation for Unicode regular
expressions is that they are not (i.e. a Unicode regex character class
should refer to the same characters independent from the locale).

If you want to construct locale-dependent Unicode character classes,
you should use this procedure:
- iterate over all byte values (0..255)
- perform the relevant locale-specific tests
- decode each byte into Unicode, using the locale's encoding
- construct a character class out of that

Unfortunately, that will work only for single-byte encodings.
I'm not aware of a procedure that does that for multi-byte strings.

But perhaps you didn't mean "POSIX character class" in this literal
way.

Regards,
Martin

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


Re: how to read o/p of telenet (python) ?!

2010-12-11 Thread MRAB

On 11/12/2010 17:44, Ian Kelly wrote:

On 12/11/2010 4:20 AM, Darshak Bavishi wrote:

i have code to telnet remote machine (unix)
i am using port 5400 to telnet but o/p is not in visible format when i
run random commands or run


What is "o/p"?


[snip]

"o/p" is an abbreviation for "output" (and "i/p" is abbreviation for
"input").
--
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes question

2010-12-11 Thread MrJean1
It is not entirely clear what the functions and especially what their
signatures are in that C library clibsmi.

In general, for shared libraries, you need to define those first as
prototype using ctypes.CFUNCTYPE() and then instantiate each prototype
once supplying the necessary parameter flags using
prototype(func_spec, tuple_of_param_flags).  See sections 15.16.2.3
and 4 of the ctypes docs*.

Take a look the Python bindings** for the VLC library, the file called
vlc.py***.  The function _Cfunction is used to create the Python
callable for each C function in that VLC library.  All the Python
callables are in the second half of the vlc.py file, starting at line
2600.

Hope this helps,

/Jean

*) 

**) 

***) 


On Dec 10, 3:32 pm, News Wombat  wrote:
> Hi everyone,
>
> I've been experimenting with the ctypes module and think it's great.
> I'm hitting a few snags though with seg faults.  I attached two links
> that holds the code.  The line i'm having problems with is this,
>
> sn=clibsmi.smiGetNextNode(pointer(sno),SMI_NODEKIND_ANY)
>
> It will work one time, and if I call it again with the result of the
> previous, even though the result (a c struct) looks ok, it will
> segfault.  I think it's a problem with pointers or maybe the function
> in the c library trying to change a string that python won't let it
> change.  I'm stuck, any tips would be appreciated.  Thanks, and Merry
> Christmas!
>
> constants.py:http://pastebin.com/HvngjzZN
> libsmi.py:http://pastebin.com/19C9kYEa

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


Re: Catching user switching and getting current active user from root on linux

2010-12-11 Thread mpnordland
sorry, I've been busy, it's on linux, and current active user is the
user currently using the computer. My program needs to switch log
files when a different user starts using the computer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catching user switching and getting current active user from root on linux

2010-12-11 Thread mpnordland
about the pyutmp, is the most recent entry at the top or bottom of the
file?

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


Re: Python critique

2010-12-11 Thread Steve Holden
On 12/11/2010 6:46 AM, Lie Ryan wrote:
> On 12/11/10 11:37, Dan Stromberg wrote:
>> On Fri, Dec 10, 2010 at 3:51 PM, John Nagle  wrote:
>>> On 12/10/2010 3:25 PM, Stefan Behnel wrote:
 Benjamin Kaplan, 11.12.2010 00:13:
> On Fri, Dec 10, 2010 at 5:46 PM, Octavian Rasnita wrote:
> The only scopes Python has are module and function.
>>>
>>> There's more.  Both a lambda, and in Python 3.x,
>>> list comprehensions, introduce a new scope.
>>
>> And classes and methods.
> 
> Also, class scope and instance scope, though similar, are distinct
> scopes. Python also have the hidden interpreter-level scope (the
> __builtins__).

But classes and instances don't have scopes. They have namespaces.

That is, if we are talking about lexical scoping.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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


Re: Python critique

2010-12-11 Thread Steve Holden
On 12/11/2010 6:46 AM, Lie Ryan wrote:
> Also, class scope and instance scope, though similar, are distinct
> scopes. Python also have the hidden interpreter-level scope (the
> __builtins__).

Kindly ignore my last post. Class scopes are lexical, instance scopes
are not.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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


Re: Python distribution recommendation?

2010-12-11 Thread Steve Holden
On 12/11/2010 9:31 AM, Octavian Rasnita wrote:
> Ok, thank you all for your recommendations.
> 
> I think I will install ActivePython because it seems that it offers more 
> features for Windows programming than the other distro (by default, which is 
> important for a beginner).
> 
> I will use WxPython and not other GUIS like QT, Tk or GTK because they are 
> not accessible for screen readers, so I will also need to install WxPython if 
> ActiveState's Python doesn't include it.
> 
I must say that wxPython has been one of the most consistently easy
packages to install over the last ten years.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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


Re: Making os.unlink() act like "rm -f"

2010-12-11 Thread Roy Smith
In article ,
 Christian Heimes  wrote:

> Am 11.12.2010 18:04, schrieb Roy Smith:
> > if os.access("file", os.F_OK):
> >os.unlink("file")
> > 
> > but that's annoying too.  What would people think about a patch to 
> > os.unlink() to add an optional second parameter which says to ignore 
> > attempts to remove non-existent files (just like "rm -f")?  Then you 
> > could do:
> 
> -1
> 
> os.unlink is a small wrapper around the unlink(2) function.

OK, fair enough.  Perhaps a better place would be in a higher level 
module like shutil.

It was suggested I look at shutil.rmtree(), but that only works of path 
is a directory.  Also, the meaning of the ignore_errors flag is not 
quite what I'm looking for.  I don't want to ignore errors, I just want 
"if it doesn't exist, this is a no-op".  In short, exactly what "rm -r" 
does in the unix shell.

So, maybe a new function is shutils?

shutils.rm(path, force=False)
Delete the file at path.  If force is True, this is a no-op if path does 
not exist.  Raises OSError if the operation fails.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catching user switching and getting current active user from root on linux

2010-12-11 Thread Tim Chase

On 12/11/2010 01:43 PM, mpnordland wrote:

it's on linux, and current active user is the user currently
using the computer. My program needs to switch log files when
a different user starts using the computer.


The problem is that multiple users can be logged on at the same 
time.  You might be able to come up with a solution that works 
for a small set of use-cases, but I admin several Linux boxes 
where multiple people can be logged-in at the same time.  There 
are also some multi-head arrangements (multiple 
keyboards/mice/monitors and sometimes even sound-cards attached 
to the same motherboard) and people can log into each "terminal" 
(if you will) concurrently, all on the same box.  So if I'm using 
the computer, and a co-worker logs in, I'm still using it at the 
same time you might catch the "new user logged in" event.


Watching wtmp (or possibly /var/log/auth) can capture the "hey, 
somebody logged in" event, but that doesn't mean that other 
previous users are done with their sessions.



-tkc



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


Re: python-parser running Beautiful Soup needs to be reviewed

2010-12-11 Thread Stef Mientki
On 11-12-2010 17:24, Martin Kaspar wrote:
> Hello commnity
>
> i am new to Python and to Beatiful Soup also!
> It is told to be a great tool to parse and extract content. So here i
> am...:
>
> I want to take the content of a -tag of a table in a html
> document. For example, i have this table
>
> 
> 
> 
>  This is a sample text
> 
>
> 
>  This is the second sample text
> 
> 
> 
>
> How can i use beautifulsoup to take the text "This is a sample text"?
>
> Should i make use
> soup.findAll('table' ,attrs={'class':'bp_ergebnis_tab_info'}) to get
> the whole table.
>
> See the target 
> http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=799.601437941842&SchulAdresseMapDO=142323
>
> Well - what have we to do first:
>
> The first thing is t o find the table:
>
> i do this with Using find rather than findall returns the first item
> in the list
> (rather than returning a list of all finds - in which case we'd have
> to add an extra [0]
> to take the first element of the list):
>
>
> table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})
>
> Then use find again to find the first td:
>
> first_td = soup.find('td')
>
> Then we have to use renderContents() to extract the textual contents:
>
> text = first_td.renderContents()
>
> ... and the job is done (though we may also want to use strip() to
> remove leading and trailing spaces:
>
> trimmed_text = text.strip()
>
> This should give us:
>
>
> print trimmed_text
> This is a sample text
>
> as desired.
>
>
> What do you think about the code? I love to hear from you!?
I've no opinion.
I'm just struggling with BeautifulSoup myself, finding it one of the toughest 
libs I've seen ;-)

So the simplest solution I came up with:

Text = """



 This is a sample text



 This is the second sample text



"""
Content = BeautifulSoup ( Text )
print Content.find('td').contents[0].strip()
>>> This is a sample text

And now I wonder how to get the next contents !!

cheers,
Stef
> greetings
> matze

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


Re: python-parser running Beautiful Soup needs to be reviewed

2010-12-11 Thread Peter Pearson
On Sat, 11 Dec 2010 22:38:43 +0100, Stef Mientki wrote:
[snip]
> So the simplest solution I came up with:
>
> Text = """
>
> 
> 
>  This is a sample text
> 
>
> 
>  This is the second sample text
> 
> 
>
> """
> Content = BeautifulSoup ( Text )
> print Content.find('td').contents[0].strip()
 This is a sample text
>
> And now I wonder how to get the next contents !!

Here's a suggestion:

pe...@eleodes:~$ python
Python 2.5.2 (r252:60911, Jul 22 2009, 15:35:03) 
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from BeautifulSoup import BeautifulSoup
>>> Text = """
... 
... 
... 
...  This is a sample text
... 
... 
... 
...  This is the second sample text
... 
... 
... 
... """
>>> Content = BeautifulSoup ( Text )
>>> for xx in Content.findAll('td'):
...   print xx.contents[0].strip()
... 
This is a sample text
This is the second sample text
>>> 

-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-parser running Beautiful Soup needs to be reviewed

2010-12-11 Thread Alexander Kapps

On 11.12.2010 22:38, Stef Mientki wrote:

On 11-12-2010 17:24, Martin Kaspar wrote:

Hello commnity

i am new to Python and to Beatiful Soup also!
It is told to be a great tool to parse and extract content. So here i
am...:

I want to take the content of a-tag of a table in a html
document. For example, i have this table


 
 
  This is a sample text
 

 
  This is the second sample text
 
 


How can i use beautifulsoup to take the text "This is a sample text"?

Should i make use
soup.findAll('table' ,attrs={'class':'bp_ergebnis_tab_info'}) to get
the whole table.

See the target 
http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=799.601437941842&SchulAdresseMapDO=142323

Well - what have we to do first:

The first thing is t o find the table:

i do this with Using find rather than findall returns the first item
in the list
(rather than returning a list of all finds - in which case we'd have
to add an extra [0]
to take the first element of the list):


table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})

Then use find again to find the first td:

first_td = soup.find('td')

Then we have to use renderContents() to extract the textual contents:

text = first_td.renderContents()

... and the job is done (though we may also want to use strip() to
remove leading and trailing spaces:

trimmed_text = text.strip()

This should give us:


print trimmed_text
This is a sample text

as desired.


What do you think about the code? I love to hear from you!?

I've no opinion.
I'm just struggling with BeautifulSoup myself, finding it one of the toughest 
libs I've seen ;-)


Really? While I'm by no means an expert, I find it very easy to work 
with. It's very well structured IMHO.



So the simplest solution I came up with:

Text = """

 
 
  This is a sample text
 

 
  This is the second sample text
 
 

"""
Content = BeautifulSoup ( Text )
print Content.find('td').contents[0].strip()

This is a sample text


And now I wonder how to get the next contents !!


Content = BeautifulSoup ( Text )
for td in Content.findAll('td'):
print td.string.strip() # or td.renderContents().strip()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Catching user switching and getting current active user from root on linux

2010-12-11 Thread Tim Harig
Mr. Chase, I really wouldn't even bother wasting my time on this one.
He asked an incomplete question to start with; so, the replies that
he received were insufficient to solve his problem.  He still has not
provided enough information to know how to answer his question propery.
He doesn't understand a sacastic reply when he hears one, he doesn't
understand the concept of a multi-user operating system, and he doesn't
understand the concept of how usenet threads work.  Until he demonstrates
some intelligence, I would say that he has flunked the Turing test.
-- 
http://mail.python.org/mailman/listinfo/python-list


Bind C++ program for use with both Python 2.x and 3.x

2010-12-11 Thread Peter C.
Hello, I am looking at the possibility of making a program in C++. The
catch is it will require the ability to work with binding for use with
scripting in both Python 2.x and 3.x for various tool plugins. Is
there any way to bind a C++ app to work with both Python 2.x and 3.x
using the Python C API? Note if I could I'd just do Python 3, however
I need Python 2 support to allow for the use of this application as a
plugin in apps that use Python 2 as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bind C++ program for use with both Python 2.x and 3.x

2010-12-11 Thread Martin v. Loewis
Am 11.12.2010 23:41, schrieb Peter C.:
> Hello, I am looking at the possibility of making a program in C++. The
> catch is it will require the ability to work with binding for use with
> scripting in both Python 2.x and 3.x for various tool plugins. Is
> there any way to bind a C++ app to work with both Python 2.x and 3.x
> using the Python C API? Note if I could I'd just do Python 3, however
> I need Python 2 support to allow for the use of this application as a
> plugin in apps that use Python 2 as well.

Notice that binding to Python 2 may not be enough: you also need to
specify the Python 2 version (i.e. different bindings for 2.5, 2.6, and
2.7, say). You will have to ship different copies of the binding. Of
course, you can ship them in a single distribution (zip file, or
whatever your distribution format is).

If you are creating different copies of the binding, supporting both
2.x and 3.x simultaneously will be straight-forward.

Regards,
Martin

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


Re: Enabling the use of POSIX character classes in Python

2010-12-11 Thread Perry Johnson
On 2010-12-11, MRAB wrote:

> On 11/12/2010 17:33, Perry Johnson wrote:
>> Python's re module does not support POSIX character classes, for
>> example [:alpha:]. It is, of course, trivial to simulate them using
>> character ranges when the text to be matched uses the ASCII character
>> set. Sadly, my problem is that I need to process Unicode text. The re
>> module has its own character classes that do support Unicode, however
>> they are not sufficient.
>>
>> I would find it extremely useful if there was information on the
>> Unicode code points that map to each of the POSIX character classes.
>
> Have a look at the new regex implementation on PyPI:
>
>  http://pypi.python.org/pypi/regex

This is exactly what I needed! Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ways of accessing this mailing list?

2010-12-11 Thread Martin Schoeoen
On 2010-11-04, Mark Wooding  wrote:
> John Bond  writes:
>
>> Hope this isn't too O/T - I was just wondering how people read/send to
>> this mailing list, eg. normal email client, gmane, some other software
>> or online service?
>>
>> My normal inbox is getting unmanageable, and I think I need to find a
>> new way of following this and other lists.
>
> I read and post to it as comp.lang.python.  I maintain a local NNTP
> server, which interacts with my ISP's news server.  I read and post news
> (and mail) using GNU Emacs and Gnus.
>
> (Interestingly, if enormous folders are your problem, Gnus can apply
> news-like expiry rules to email folders.)
>
Same here: comp.lang.python and gnus. Well, right now I am actually trying 
out slrn -- a bit of a dejavu experience since I used slrn a bit in the
early 1990s (and I have not used vi in many, many years).

I have tried out other programs such as traditional email clients and
mainstream gui programs such as Pan but find that user interface paradigm
does not work well for usenet news and me.

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


Re: Catching user switching and getting current active user from root on linux

2010-12-11 Thread Steven D'Aprano
On Sat, 11 Dec 2010 11:43:13 -0800, mpnordland wrote:

> sorry, I've been busy, it's on linux, and current active user is the
> user currently using the computer. My program needs to switch log files
> when a different user starts using the computer.

I think you have missed what people are trying to tell you: if you're 
running Linux, you may have more than one human being logged into and 
using the computer AT THE SAME TIME. You can also have a single human 
being logged into the computer as more than one user, and one user being 
used by multiple human beings.

As we speak, I am logged into my Linux computer eight times, five times 
as myself (two GUI sessions, just to prove I can do it, plus three 
terminals), two times as root, and one time as another user; my wife's 
computer has two people logged in simultaneously (me and her); I'm also 
logged into a server at work, which currently lists eight people logged 
in twenty-one times between them.

Perhaps you should explain what problem you are trying to solve, rather 
than how you think you should solve it ("catch the user switching").



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


array and strings in Python 3

2010-12-11 Thread wander.lairson
Hello,

This is my first post on python mailing list. I've working in code
which must run on python 2 and python 3. I am using array.array as
data buffers. I am stuck with the following code line, which works on
Python 2, but not on Python 3.1.2:

>>> import array
>>> array.array('B', 'test')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: an integer is required

According to Python 3 documentation (as far as I understood it), it
should work. Again, no problem on Python 2. I've googled for people
with similar problems, but got nothing. Does anyone have an idea what
could I be doing wrong?

Thanks in advance.

-- 
Best Regards,
Wander Lairson Costa
LCoN - Laboratório de Computação Natural - Natural Computing Laboratory
(http://www.mackenzie.com.br/lcon.html)
Programa de Pós-Graduação em Engenharia Elétrica (PPGEE)
Faculdade de Computação e Informática (FCI)
Universidade Presbiteriana Mackenzie - SP - Brazil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array and strings in Python 3

2010-12-11 Thread Chris Rebert
On Sat, Dec 11, 2010 at 5:32 PM, wander.lairson
 wrote:
> Hello,
>
> This is my first post on python mailing list. I've working in code
> which must run on python 2 and python 3. I am using array.array as
> data buffers. I am stuck with the following code line, which works on
> Python 2, but not on Python 3.1.2:
>
 import array
 array.array('B', 'test')
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: an integer is required
>
> According to Python 3 documentation (as far as I understood it), it
> should work.

I think you forgot to keep in mind the changes in bytes vs. unicode in
Python 3 when reading the docs.

> Again, no problem on Python 2. I've googled for people
> with similar problems, but got nothing. Does anyone have an idea what
> could I be doing wrong?

Recall that string handling changed incompatibly between Python 2 and
Python 3. Your 'test' was a bytestring in Python 2 but is now a
*Unicode string* in Python 3.

The `array` module's handling of strings changed as well. Reading the
Python 3 docs @ http://docs.python.org/dev/library/array.html , we
find (all emphases added):
class array.array(typecode[, initializer])
[...]
If given a list or string, the initializer is passed to the new
array’s fromlist(), frombytes(), or **fromunicode()** method (see
below) to add initial items to the array. Otherwise, the iterable
initializer is passed to the extend() method.
[...]
array.fromunicode(s)
Extends this array with data from the given unicode string. The
array **must be a type 'u' array**; **otherwise a ValueError is
raised**. Use array.frombytes(unicodestring.encode(enc)) to append
Unicode data to an array of some other type.

Since your array's typecode is not 'u', you're getting a ValueError
just like the docs say.

Try using a bytestring instead:
array.array('B', b"test") # Note the b prefix

Incidentally, if you ran 2to3 over your code and weren't warned about
this change in the array module, then that's probably a bug in 2to3
which ought to be reported: http://bugs.python.org

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


Re: array and strings in Python 3

2010-12-11 Thread wander.lairson
> The `array` module's handling of strings changed as well. Reading the
> Python 3 docs @ http://docs.python.org/dev/library/array.html , we
> find (all emphases added):
> class array.array(typecode[, initializer])
>    [...]
>    If given a list or string, the initializer is passed to the new
> array’s fromlist(), frombytes(), or **fromunicode()** method (see
> below) to add initial items to the array. Otherwise, the iterable
> initializer is passed to the extend() method.
> [...]
> array.fromunicode(s)
>    Extends this array with data from the given unicode string. The
> array **must be a type 'u' array**; **otherwise a ValueError is
> raised**. Use array.frombytes(unicodestring.encode(enc)) to append
> Unicode data to an array of some other type.
>
Actually I was using the 3.1 docs as reference, as it is the stable
one. After your comments,
I dug a bit more in the documentation and in the code, and I figured
out that for unicode strings,
you must pass 'u' as the first constructor parameter.

> Incidentally, if you ran 2to3 over your code and weren't warned about
> this change in the array module, then that's probably a bug in 2to3
> which ought to be reported: http://bugs.python.org
>
I am not using 2to3 because I am not converting Python 2 code to
Python 3, I am writing
code that must run on Python 2 and Python 3.

Thank you for your help :)


-- 
Best Regards,
Wander Lairson Costa
LCoN - Laboratório de Computação Natural - Natural Computing Laboratory
(http://www.mackenzie.com.br/lcon.html)
Programa de Pós-Graduação em Engenharia Elétrica (PPGEE)
Faculdade de Computação e Informática (FCI)
Universidade Presbiteriana Mackenzie - SP - Brazil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ways of accessing this mailing list?

2010-12-11 Thread Monte Milanuk

On 12/11/10 3:32 PM, Martin Schoeoen wrote:

On 2010-11-04, Mark Wooding  wrote:

John Bond  writes:


Hope this isn't too O/T - I was just wondering how people read/send to
this mailing list, eg. normal email client, gmane, some other software
or online service?


Thunderbird + gmane works for me.


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


Re: Ways of accessing this mailing list?

2010-12-11 Thread Harishankar
On Sat, 11 Dec 2010 21:15:13 -0800, Monte Milanuk wrote:
> Thunderbird + gmane works for me.

I myself post using Pan Usenet client accessing this mailing list from 
gmane.

The advantage of a proper newsreader software is that it quotes correctly 
(i.e. quote at top, reply below). Many Usenet and mailing list users get 
angry if you top post (i.e. quote below the reply)


-- 
Harishankar (http://harishankar.org http://lawstudentscommunity.com)

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