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
--
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
--
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
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
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
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
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,
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
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
--
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
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
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
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
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
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
[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.
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
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
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:
#
[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':
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.
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
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
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
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
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
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
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
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
[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,
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
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
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']
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
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
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
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()
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
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
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
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,
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
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
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:
...
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
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):
...
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,
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.
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
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
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
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 =
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
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
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
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
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
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 = []
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
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
--
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
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:
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()
63 matches
Mail list logo