Re: 'if name is not None:' v. 'if name:'

2008-07-15 Thread Jeffrey Froman
Victor Noagbodji wrote: Why do people use if name is not None: instead of simply writing if not name? To differentiate from the case where name == '', or some other non-None false value. So the question is, do you want to test for identity with None, or for truth in general? Jeffrey --

Re: while var, but var ==16 != true

2008-07-14 Thread Jeffrey Froman
Tim Roberts wrote: Everything has a boolean value in Python.  0, None, False, '' (empty string), [] (empty list), () (empty tuple), and {} (empty dictionary) all have a False value.  Everything else has a True value. Empty set objects also evaluate as false in a boolean context. Jeffrey --

Re: MySQLdb will only import for root

2008-07-11 Thread Jeffrey Froman
Diez B. Roggisch wrote: Is it possible the module was installed with priviledges set too strict?  Perhaps the interpreter cannot see the module when it is run from a normal user account. Possible - certainly. Yet unrealistic, because usually root access is required to system-wide install a

Re: read file into list of lists

2008-07-11 Thread Jeffrey Froman
Laurent Rahuel wrote that antar2 wrote: following text for example should be considered as a list of lists (3 columns and 3 rows), so that when I make the print statement list[0] [0], that the word pear appears pear noun singular books nouns plural table noun singular File objects are

Re: python scalability

2008-07-10 Thread Jeffrey Froman
Tim Mitchell wrote: One of my project managers questions is: Are we the only company in the world with this kind and size of project? I can't provide a bigger success story personally (my largest project is currently about 15k lines of code, eminently manageable by one person.) But Google

Re: automatically import modules upon interpreter invocation

2008-06-26 Thread Jeffrey Froman
Daniel Fetchinson wrote: Is there a way of making python execute the above whenever it starts up so that I don't have to type it all the time? Create a script containing these statements, and specify its location with the PYTHONSTARTUP environment variable. Your script will run whenever python

Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Jeffrey Froman
John Salerno wrote: Generally speaking, what tools would I use to do this? Is there a built-in module for it? I've had a very nice experience using the 3rd-party package paramiko for ssh communication. There's nothing in the standard library that I know of. I looked at the telnetlib module,

Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Jeffrey Froman
John Salerno wrote: I guess a blanket process might be a tad risky, but don't you want all CGI files to be executable by all? Typically, I prefer CGI scripts to be executable only the owner. If the web server runs those scripts as a different user, then that user must also be permitted to

Re: Ternary operator alternative in Ptyhon

2008-06-18 Thread Jeffrey Froman
jeremie fouche wrote: You can also use : self.SomeField = params.has_key(mykey) and params[mykey] or None Have caution with this solution: it may not provide the desired result in the case where params[mykey] is a false value, such as 0, or [] Jeffrey --

Re: Who is using python-ldap with Python 1.5.x and 2.0-2.2?

2008-06-18 Thread Jeffrey Froman
Michael Ströder wrote: Please tell me which Python version you're using We do have one venerable machine here at work using python2.2 with python-ldap2.0.0pre04. As you can see, we haven't bothered to update either in quite a while ;-) and why it'd be important for you to have python-ldap

Re: php vs python

2008-05-21 Thread Jeffrey Froman
notbob wrote: I persevere because it's more fun/challenging than video games This is the crux of the matter from where I'm sitting. If the purpose of learning a programming language is fun, then the primary relevant question is: Is it more fun to code in Python or PHP? The answer is

Re: Are rank noobs tolerated, here?

2008-05-06 Thread Jeffrey Froman
notbob wrote: I'm running vers 2.5.1 on slackware 12. Nice to see another Slackware user around here! Here is an example of a user-defined function that has a parameter: def print_twice(bruce): print bruce, bruce snip is this just an example of how the def should be written and

Re: Are rank noobs tolerated, here?

2008-05-06 Thread Jeffrey Froman
notbob wrote: Do python scripts require the: #!/usr/bin/env python An appropriate shebang is required if you intend to use the module itself as a script, from the command line, like: $ ./my_module.py argument argument ... It is not required merely to import the module into a python

Re: Recurring patterns: Am I missing it, or can we get these added to the language?

2008-04-15 Thread Jeffrey Froman
Tim Chase wrote: def nsplit(s, delim=None, maxsplit=None): if maxsplit: results = s.split(delim, maxsplit) result_len = len(results) if result_len maxsplit: results.extend([''] * (maxsplit - result_len) return results else: return

Re: Recurring patterns: Am I missing it, or can we get these added to the language?

2008-04-15 Thread Jeffrey Froman
Erich wrote: def iterable(item, count_str=False): if not count_str and isinstance(item, str): return False try: iter(item) except: return False return True Beware the except clause here, as it catches *all* errors. Thus, if you happen to have an

Re: Adding classes to modules at runtime from outside that module

2008-04-10 Thread Jeffrey Froman
[EMAIL PROTECTED] wrote: In Python, is it possible to add classes to a module at run-time? Say I have a module foo and a module bar. Foo has class A and B, and bar has class C. I want to add class C to foo so I can access it as foo.C, but i want to do it without modifying foo's source.

Re: Trouble with list comprehension

2008-04-09 Thread Jeffrey Froman
Shane Lillie wrote: goats = [ x for x in range(2) if doors[x] == 'G' ] but for some reason the list comprehension is not always returning a list with 2 elements in it (sometimes it will be just 1 element). The problem here is with your usage of the range() function. You provide an endpoint

Re: list.sort(): heaviest item?

2008-04-08 Thread Jeffrey Froman
Steven Clark wrote: If I have a list of items of mixed type, can I put something into it such that after a list.sort(), is guaranteed to be at the end of the list? snip doc excerpt It looks like None always ends up at the start (lightest), but I want the opposite (heaviest). I don't know

Re: Coping with cyclic imports

2008-04-08 Thread Jeffrey Froman
Torsten Bronger wrote: I know that cyclic imports work in Python under certain circumstances.  Can anyone refer me to a page which explains when this works? I don't know of a specific URL offhand. Cyclic imports are not a problem by themselves, but cyclic definitions are. Thus: #

Re: reading dictionary's (key,value) from file

2008-04-07 Thread Jeffrey Froman
[EMAIL PROTECTED] wrote: so this is what my option files look like: 1opt.txt { '-cc': '12', '-I': r'/my/path/work/'} You can turn these strings read from text files into actual dictionaries using eval: d = eval({ '-cc': '12', '-I': r'/my/path/work/'}) d {'-I': '/my/path/work/', '-cc':

Re: Tips for load balancing multiple Python apps on dual/quad core processors?

2008-04-07 Thread Jeffrey Froman
Malcolm Greene wrote: I'm looking for tips on how to load balance running multiple Python applications in multi-CPU environments. My understanding is that Python applications and their threads are limited to a specific CPU. Background: I have a Python utility that processes email messages.

Re: Python2.5 and MySQLdb

2008-04-04 Thread Jeffrey Froman
writeson wrote: I'm running a CentOS 4 server and have installed Python2.5 on there (it's our development machine) in preparation of moving to Python2.5 everywhere. All looks good with our code and 2.5, except where it comes to MySQLdb, I can't get that to install on the machine. It

Re: Is subprocess.Popen completely broken?

2008-03-27 Thread Jeffrey Froman
Skip Montanaro wrote: I am trying to replace os.system calls with subprocess.Popen.  This simple example fails miserably: proc = subprocess.Popen (ls /tmp) Popen expects a list of program arguments. When passed a single string instead of a list, as in your example, it assumes that the

Re: Signal problem

2008-03-27 Thread Jeffrey Froman
Fabio Durieux Lopes wrote: def signalHandler(signum, frame): terminate = True This creates a new variable named terminate inside the signalHandler function's local scope. To adjust the value of a module-level global from inside a function, use the global keyword: def

Re: subprocess.popen function with quotes

2008-03-26 Thread Jeffrey Froman
skunkwerk wrote: p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] i change to print p.communicate()[1] in case the output is blank the first time this is the output: *.htm renamed as

Re: New to group

2008-03-24 Thread Jeffrey Froman
pythonnubie wrote: The exeption is no such  attribute in  module random Is your own source file named random.py by chance? If so, rename it, and be sure to remove the leftover random.pyc file as well. Jeffrey -- http://mail.python.org/mailman/listinfo/python-list

Re: Change user on UNIX

2008-03-20 Thread Jeffrey Froman
Giampaolo Rodola' wrote: I mainly need to temporarily impersonate another user to execute a command and then come back to the original user. If the script is run as root, you can freely impersonate other users with the os.seteuid() and os.setegid() methods. If the script is not run as root

Re: Import a file to namespace

2008-03-20 Thread Jeffrey Froman
Pedro Machado Santa wrote: import testpackage class testClass(): #... testpackage.testClass =  testClass This method should work fine. Modules are effectively singletons, so running this code one time anywhere in your application will cause the changes to appear in all references to the

Re: Decode email subjects into unicode

2008-03-18 Thread Jeffrey Froman
Laszlo Nagy wrote: I know that =?UTF-8?B means UTF-8 + base64 encoding, but I wonder if there is a standard method in the email package to decode these subjects? The standard library function email.Header.decode_header will parse these headers into an encoded bytestring paired with the

Re: Intelligent Date Time parsing

2008-03-07 Thread Jeffrey Froman
[EMAIL PROTECTED] wrote: I need something to parse user input for a django app, and it's awesome to be able to write last monday, a year ago, or 10pm tuesday like PHP's strtotime. Django comes with some pretty handy filters for doing this sort of formatting. Check out the date, now,

Re: for-else

2008-03-04 Thread Jeffrey Froman
Carl Banks wrote: there is a rationale behind the name else.  If you consider a for loop to be a rolled-up if...elif...else statement This is an interesting angle. I've always considered for/else to be unintuitive, not because of else, but because of the coupling with for. Instead, I think of

Re: Odd behaviour with list comprehension

2008-02-29 Thread Jeffrey Froman
Ken Pu wrote: So the list comprehension actually creates a variable x which is somewhat unexpected. Is there a way for me keep the iterating variable in list comprehension local to the list comprehension? Not with a list comprehension, but generator expressions do not leak their iterating

Re: string split without consumption

2008-02-02 Thread Jeffrey Froman
robert wrote: thanks. Yet this does not work naturally consistent in my line processing algorithm - the further buffering. Compare e.g. ss.split('\n')  .. 'owi\nweoifj\nfheu\n'.split('\n') ['owi', 'weoifj', 'fheu', ''] 'owi\nweoifj\nfheu\nxx'.split('\n') ['owi', 'weoifj', 'fheu', 'xx']

Re: Cannot catch _mysql_exceptions.OperationalError

2008-01-18 Thread Jeffrey Froman
Bob wrote: Here's the code that did not work: import _mysql_exceptions from _mysql_exceptions import OperationalError try: database_code() except (_mysql_exceptions.OperationalError, OperationalError), e: error_handling() Both of the above forms work fine here, as does using

Re: Running unmodified CGI scripts persistently under mod_wsgi.

2007-12-07 Thread Jeffrey Froman
Jeffrey Froman wrote: While recently considering whether to re-write a standalone mod_python application as CGI or WSGI, I was scared off by this paragraph from PEP333: snip scary warning about using WSGI as an application API As a followup, I did go ahead and convert my CGI handler to WSGI

Re: Running unmodified CGI scripts persistently under mod_wsgi.

2007-11-26 Thread Jeffrey Froman
Graham Dumpleton wrote: The other question is whether there is even a demand for this. Do people want to be able to take unmodified Python CGI scripts and try to run them persistently in this way, or would they be better off converting them to proper WSGI applications. I would personally be

Re: Populating a dictionary, fast [SOLVED SOLVED]

2007-11-16 Thread Jeffrey Froman
Steven D'Aprano wrote: Can you try it running in 64-bit mode? Here are my results using the following test.py: $ cat test.py #!/usr/bin/python import time print Starting: %s % time.ctime() v = {} for line in open('keys.txt'): v[long(line.strip())] = True print Finished: %s % time.ctime()

Re: Populating a dictionary, fast

2007-11-12 Thread Jeffrey Froman
Hrvoje Niksic wrote: Note that both machines are x86_64.  Please try your test on a 32-bit machine and report the results.  I suspect performance won't degrade there. This theory seems to be supported by my findings. Running the test on a 32-bit machine took 45 seconds, while the same test on

Re: unit testing

2007-10-04 Thread Jeffrey Froman
Chris Mellon wrote: Doctest is commonly given as the alternative to people who feel this way. Personally, I find that anything worth testing is worth having a test directory and independent unit tests for. I like keeping my tests separate as well, and doctest does allow this, using

Re: How to find script's directory

2007-08-19 Thread Jeffrey Froman
Papalagi Pakeha wrote: I guess I could do it with a little help of os.path.realpath() for all those cases where absolute or relative path was used. But how should I approach it when it's invoked as plain 'blah.py' because its directory name is in $PATH? Use the value of __file__ rather than

Re: Why PHP is so much more popular for web-development

2007-07-26 Thread Jeffrey Froman
walterbyrd wrote: The point is: PHP framework makers are very considerate of the realities of shared hosting. I think the opposite is true: PHP applications typically ignore the realities of shared hosting in order to be considerate to non-developers (that is to say, users). In particular,

Re: Python version changes, sys.executable does not

2007-07-22 Thread Jeffrey Froman
Jim Langston wrote: I think it's because your python directory is in the path before your python2.5 directory. Thanks for the tip. In fact, /usr/local/bin/python (2.5) is on my PATH before /usr/bin/python (2.3). I did find the problem however -- it turns out that caching the executable path

Python version changes, sys.executable does not

2007-07-19 Thread Jeffrey Froman
Hello All, I have two python versions installed, one in /usr/bin, and one in /usr/local/bin. However, when invoking python without a full path, I get the wrong executable with the right sys.executable string! [EMAIL

Re: Parameter lists

2007-02-04 Thread Jeffrey Froman
Mizipzor wrote: class Stats: def __init__(self, *li): self.speed = li[0] self.maxHp = li[1] (...) Or maybe there is an even niftier way that lets me iterate through them? Using keyword arguments instead of positional parameters makes this easy: class Stats: ...

Re: Subscribing to topics?

2007-02-04 Thread Jeffrey Froman
Mizipzor wrote: I discovered that Google has a free newsserver, so I joined this group from there. Sadly, I cant see a feature here that lets me subscribe to an individual topic, so if anyone else is using Google groups and know how to do something like this, please tell me. I don't know

Re: another newbie question: why should you use *args ?

2007-01-31 Thread Jeffrey Froman
stef wrote: And one note more. Just to be more pythonic you shouldn't use form range(len(blabla)). Instead use: for i in list: blabla... I would love that, but please tell me how (I need an integer counter for something else too): for index, item in enumerate(args): ...

Re: Iterate through list two items at a time

2007-01-02 Thread Jeffrey Froman
Dave Dean wrote: I'm looking for a way to iterate through a list, two (or more) items at a time. Here's a solution, from the iterools documentation. It may not be the /most/ beautiful, but it is short, and scales well for larger groupings: from itertools import izip def groupn(iterable,

Re: Unescaping URLs in Python

2006-12-25 Thread Jeffrey Froman
John Nagle wrote: What's the appropriate Python function to call to unescape a URL which might contain things like that? xml.sax.saxutils.unescape() Will this interfere with the usual % type escapes in URLs? Nope, and urllib.unquote() can be used to translate URL escapes manually.

Re: is mod_python borked?

2006-11-02 Thread Jeffrey Froman
walterbyrd wrote: Researching further, it looks to me like mod_python may only work well on apache 2.X. mod_python works splendidly with Apache 2.0.x as well as Apache 1.3.x. There is a different mod_python version for each Apache branch. The version for Apache 2.0.x has newer features, but

Re: New to Python: Do we have the concept of Hash in Python?

2006-06-01 Thread Jeffrey Froman
A.M wrote: I am asking this because I learned that DB-API in Python doesn't offer access to cursor columns by name. The only option is access by index. I hope that I've got it wrong! While it's not part of the DB-API as far as I know, the MySQLdb package (and perhaps other DB access modules

Re: Looking for a language/framework

2006-03-29 Thread Jeffrey Froman
Alex Martelli wrote: I've never seen an object-relational mapping (technical term for cruft that tries to avoid people having to learn and use SQL) which doesn't drive me into a murderous, foam-at-mouth rage in a very short time -- I WANT my SQL, I LOVE SQL, it's WAY more powerful and

Re: MySQLDB - return strange type of variable

2006-03-25 Thread Jeffrey Froman
Grzegorz Smith wrote: Hi all. I'm trying get data from text field in MySQl 5.0 with my National characters. Data are stored in utf8 encodings. Here is the script: import MySQLdb, MySQLdb.cursors conn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='profile_locale') c =

Re: Server.sendmail with no to_addrs parameter.

2006-03-22 Thread Jeffrey Froman
EdWhyatt wrote: I would like to have the ability to send a mail message with no-one email address in the To field. The to_addrs parameter is for the SMTP RCPT TO, which must contain at least one address. It has nothing to do with the To: header of the email. You can *also* add the recipient

Re: Server.sendmail with no to_addrs parameter.

2006-03-22 Thread Jeffrey Froman
EdWhyatt wrote: But are you serious about that RFC Compliant thing? RFC 2822 obsoletes RFC 822, and I don't know of any specification in RFC 2822 that requires an email address to be present in the To: header. My mail seems to generally work fine without a To: header. I haven't memorized RFC

Re: Quote-aware string splitting

2005-04-26 Thread Jeffrey Froman
Bengt Richter wrote: Oops, note some spaces inside quotes near ss and missing double quotes in result. And here I thought the main problem with my answer was that it didn't split unquoted segments into separate words at all! Clearly I missed the generalization being sought, and a more robust

Re: Quote-aware string splitting

2005-04-25 Thread Jeffrey Froman
J. W. McCall wrote: For example, given the string: 'spam the life of brian 42' I'd want it to return: ['spam', 'the life of brian', '42'] The .split() method of strings can take a substring, such as a quotation mark, as a delimiter. So a simple solution is: x = 'spam the life of

Decorator Syntax For Recursive Properties

2005-04-17 Thread Jeffrey Froman
Consider the following class: class Node(object): def __init__(self, name, parent=None): self.name = name self.parent = parent def _ancestors(self, ants=None): if ants is None: ants = [] else: ants.insert(0, self.name) if

Re: Decorator Syntax For Recursive Properties

2005-04-17 Thread Jeffrey Froman
Peter Otten wrote: something like this didn't work for me: snip But this will, I suppose: @property def ancestors(self): if self.parent: return self.parent.ancestors + [self.parent] return [] A non-recursive variant: @property def ancestors(self): result = []

Re: compound strip() string problem

2005-04-08 Thread Jeffrey Froman
Dylan Wilson wrote: Now i need to compond that string remove the whitespace if you will.Well i read up on strip(), lstrip() and rstrip() and all i could deduce was that they striped the whitespace from the start and/or end of the string.But I tried that anyway and failed.Is there an easier

Re: OT: why are LAMP sites slow?

2005-02-04 Thread Jeffrey Froman
M.E.Farmer wrote: Div is a block level tag and span isn't. You can also group them  together and nest them. One caveat here -- I don't believe you can (should) nest a div inside a span, or for that matter, nest any block-level element inside an inline element. Jeffrey --

Re: OT: why are LAMP sites slow?

2005-02-04 Thread Jeffrey Froman
Paul Rubin wrote: I don't know that the browser necessarily renders that faster than it renders a table, but there's surely less crap in the HTML, which is always good.  I may start using that method. Using tables for layout is also a cardinal faux pas if you care about accessibility, as such

Re: mod_python and xml.sax

2004-12-22 Thread Jeffrey Froman
Fredrik Lundh wrote: iirc, both apache and python uses the expat parser; if you don't make sure that both use the same expat version, you may get into trouble. Thank you very much Fredrik, this does seem to be the problem I was having. this poster claims to have a fix:

mod_python and xml.sax

2004-12-20 Thread Jeffrey Froman
I am having difficulty getting mod_python and xml.sax to play nicely with each other. I am using: Python 2.4 Mod_python 2.7.10 Apache 1.3.33 Using the mod_python.publisher handler to invoke the go function in the following script: from xml.sax import make_parser def go(): x = make_parser()