Logic Bank

2020-10-23 Thread gMail
Hello, All

I am pleased to announce the release of Logic Bank.

Logic Bank introduces spreadsheet-like rules for multi-table derivation and 
constraint logic for SQLAchemy databases - 40X more concise than legacy code, 
extensible and manageable using Python.  Described in this article 
, open 
source on git. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Making Python the Best App Dev Platform

2020-09-18 Thread gMail
Hello, All

We all know Python is a wonderful environment, with fantastic packages for App 
Dev like Flask, SQLAlchemy and Django.  Now let’s make it the only reasonable 
choice for building database-oriented systems.

I’d like to introduce 2 new capabilities:

Build a web app in 10 minutes: this generator 
 builds basic multi-page, 
multi-table apps based on Flask AppBuilder and SQLAlchemy; here’s an article 


40x reduction in backend code: this rules engine 
 uses spreadsheet-like rules to 
automate SQLAlchemy multi-table derivation and constraint logic.  The readme 
and samples show how 5 rules equate to 200 lines of code.

The potential value is substantial: a 40X is reduction is not only helpful for 
our projects, but has the potential to expand our community.

The second project is in-progress.  If you have feedback on the general value 
or particular features, I’d love to hear from you.  And if you’d like to help, 
super!

Best,
Val

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


Document Entire Apps

2019-09-14 Thread Sinardy Gmail
Hi Python Gurus,

I am in earlier stage in my apps development,

What tools or how is the Python community standard good practice in documenting 
the apps especially the packages that import another packages.

I understand that we can use pydoc to document procedures how about the 
relationship between packages and dependencies ?

Thanks
Sin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Community Involvement

2011-08-04 Thread sparky gmail

On 8/3/2011 8:14 PM, Steve Holden wrote:

[Ccs appreciated]

After some three years labor I (@holdenweb) at last find myself 
approaching the completion of the Python Certificate Series with 
O'Reilly School of Technology (@OReillySchool).


At OSCON last week the team fell to talking about the final assignment 
(although the Certificate is not a certification, students only 
progress by answering real quiz questions, not the usual 
multiple-choice task). Success also requires that they complete a 
project at the end of each (of the ~60) lesson(s).


We would ideally like the last project to to be something that 
demonstrates at least some minimal involvement with the Python 
community. Something like "get a Python answer upvoted on 
StackOverflow", for example, or getting a question answered on c.l.p. 
At the same time it shouldn't be anything that places a burden on the 
community (otherwise the hundredth student would be abused and the 
thousandth murdered).


So I wondered if anyone had any good ideas.

regards
 Steve
--
Steve Holden
st...@holdenweb.com 




Just a thought.

What about contributing code or documentation to an established project?

I dislike the idea of getting an answer up voted. First of all, for 
people trying to do it honestly you are putting
their completion into the hands of strangers, secondly, it would be very 
easy to cheat by having someone else,

or themselves with a puppet account, up vote the answer.

There are a metric grip of established projects that could use a little 
help with documentation, code examples, etc.

I think this is a better route to community participation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Selecting unique values

2011-07-26 Thread sparky gmail

On 7/25/2011 3:03 PM, Kumar Mainali wrote:

Greetings

I have a dataset with occurrence records of multiple species. I need 
to get rid of multiple listings of the same occurrence point for a 
species (as you see below in red and blue typeface). How do I create a 
dataset only with unique set of longitude and latitude for each 
species? Thanks in advance.


Species_nameLongitudeLatitude
Abies concolor-106.60135.868
Abies concolor-106.49335.9682
Abies concolor-106.48935.892
Abies concolor-106.49635.8542
Accipiter cooperi-119.68834.4339
Accipiter cooperi-119.79234.5069
Accipiter cooperi-118.79734.2581
Accipiter cooperi-77.389.68333
Accipiter cooperi-77.389.68333
Accipiter cooperi-75.9915340.65
Accipiter cooperi-75.9915340.65

- Kumar
It would seem to me that what you are wanting is a dictionary where the 
species name is the key and the value is a list of Long/Lat


So assuming your data is in a list like so (such as you might get from 
reading lines from a file) ['Abies concolor-106.60135.868', 'Abies 
concolor-106.49335.9682']


You could say

output = dict()
for record in my_long_list:
values = record.rsplit(' ', 2)
key = values[:1]
value = ' '.join(values[1:])
try:
 output[key].append(value)
 except KeyError:
 output[key] = [value]


Something like that should do.


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


Decorator behavior

2011-07-22 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I am just trying to wrap my head around decorators in Python, and I'm
confused about some behavior I'm seeing.  Run the code below (slightly
adapted from a Bruce Eckel article), and I get the following output:

inside myDecorator.__init__()
inside aFunction()
Finished decorating aFunction()
inside myDecorator.__call__()

My question: Why isn't the first print statement in "__main__" the
first line of code executed?  Is aFunction() not closed somehow?

#!/usr/bin/env python

class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
f() # Prove that function definition has completed

def __call__(self):
print "inside myDecorator.__call__()"

@myDecorator
def aFunction():
print "inside aFunction()"

if __name__ == '__main__':
print "Finished decorating aFunction()"
aFunction()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-22 Thread GMail Felipe


On 22/05/2011, at 10:41, TheSaint  wrote:

> Kushal Kumaran wrote:
> 
>> You could look for a way to make aria2c not become a daemon and use
>> subprocess.Popen to start it.  That gives you the PID and ways to see
>> if the process is still running
> 
> I see. It's a step that I've to get on my account. Unfortunately I'll have 
> to study it some more.
> 
> BTW. I removed grep from the command. Python does it with the *in* statement 
> :)
> 
> 
> -- 
> goto /dev/null
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Hi, 

For the "ps" command, have you seen the psuti module?

The link to it is: http://code.google.com/p/psutil/

Regards,
Felipe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess pipe question

2011-02-22 Thread GMail Felipe

On 22/02/2011, at 20:44, Rita  wrote:

> I have a process like this,
> 
> def run(cmd):
>   #cmd=a process which writes a lot of data. Binary/ASCII data
>   p=subprocess.Popen(cmd,stdout=subprocess.PIPE)
> 
> I would like to get cmd's return code so I am doing this,
> 
> def run(cmd):
>   p=subprocess.Popen(cmd,stdout=subprocess.PIPE)
>   rc=p.poll()
>   print rc # and I get 'None' regardless of what cmd gives me (0 thru 255 are 
> valid return codes)
>   return p.stdout
> 
> 
> When using wait() it works a bit better but not consistent
> def run(cmd):
>   p=subprocess.Popen(cmd,stdout=subprocess.PIPE)
>   rc=p.wait()
>   print rc
>   return p.stdout
> 
> When the output of cmd is a small ascii file it works perfectly fine, but 
> when the file is large (more than 2MB) the process just waits for ever (I am 
> guessing its blocking?).  When I use the communicate call it works perfectly 
> but my process is consuming way too much memory. 
> 
> Is there a better way to get my return code consistently efficiently and not 
> take up so much memory? 

Have you tried: p.return_code (or something like this? I don't remember now)-- 
http://mail.python.org/mailman/listinfo/python-list


returning all matching groups with re.search()

2011-02-03 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
Here's a scenario:

import re
m = re.search('e','fredbarneybettywilma')

Now, here's a stupid question:
why doesn't m.groups() return ('e','e','e').

I'm trying to figure out how to match ALL of the instances of a
pattern in one call - the group() and groups() return subgroups... how
do I get my search to get me all of the matching subgroups?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQT: QWebView with custom QNetworkAccessManager

2011-02-02 Thread Gelonida Gmail
Hi Phil,

On 02/02/2011 09:28 AM, Phil Thompson wrote:
> On Wed, 02 Feb 2011 02:37:06 +0100, Gelonida  wrote
>
> In fact my first experiments failed horribly due to a tiny PyQt detail.
>
> I expected that, the variable new_manager does not have to be
> persistent.
>> I naively assumed, that a call to setNetworkAccessManager() would keep a
>> reference to new_manager and thus avoid its destruction this does not
>> seem to be the case.
> It is the case in current versions.
>
> Phil

Thanks for the confirmation/


Was using PyQt: 4.7.2 263938

>From which release on is it fixed?



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


Re: float from numbers in text file

2010-06-21 Thread GMail Felipe


On 21/06/2010, at 20:26, davidgp  wrote:


On Jun 21, 4:18 pm, Stephen Hansen  wrote:

On 6/21/10 4:03 PM, davidgp wrote:




sorry :)


Okay, I should be more specific: include full tracebacks and some  
real

copied and pasted code :) Don't throw away nice debugging information
Python gave you, feed it to us.


invalid literal for long() with base 10: '51.9449702'
this is the error i'm getting when i use long(line)


Yes, "51.9449702" is an invalid literal for long. Long produces
integers: no decimal points.

However:


and this is the error for float(line)
invalid literal for float(): not found


Its a perfectly valid literal for float:>>> float('51.9449702')

51.9449702

So if you're getting that error, you're doing something else that  
you're

not telling us.

I suspect, somehow (I'd have to see your code to be sure), that your
"line" in the second case doesn't have that number. Try it in the
interactive interpreter. float('51.9449702') works fine. I suspect  
your

"line", for whatever reason, contains the string "not found", as in:


float('not found')


Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for float(): not found

--

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog:http://meh.ixokai.io/

 signature.asc
< 1KViewDownload


ah, i see :P
float("45.34") or whatever does work fine, but the problem is that i'm
reading it from a text file. so somehow it is not a real string or
whatever..
here's a part of the code:
f = open ('/home/david/out.txt', 'r')

for line in f:
if tel ==6:
   buf = line.replace('\n', '')
   lat = float(buf)
   if tel ==7:
   buf = line.replace('\n', '')
   lng = float(buf)

basically it goes wrong in the last part where i try to convert the
line to a float..
i'm 100% sure that it's getting a number, not a text string

cheers!

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


Ok! Just to be sure, execute the following in your  file:

egrep -in 'not found' 

If it finds something, it will return the line number and what was  
found!


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


Convert PyUnicodeObject to PyBytesObject in python3.x?

2010-05-18 Thread gmail
Hi All,

A variable whose data type is PyUnicodeObject needs to passed to a function as 
an argument whose data type should be PyBytesObject type 

example :

PyUnicodeObject *p = ...whatever...; 
function (PyByteObject* a); 

function((PyBytesObject *)p);

compiled and got a Bus Error.

Thanks for spending ur valuable time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Issue with PyUnicodeObject type variables

2010-05-17 Thread gmail
A variable whose data type is PyUnicodeObject checked whether it is a 
UnicodeObject type.
Got output as false

example :

PyUnicodeObject *p; 

if (PyUnicode_Check(path)) {
printf("\nTrue.\n");

}
else {
printf("\nfalse.\n");
}

output: false


Confused what went wrong.

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


file events using fsevents for mac

2010-04-10 Thread gmail
Hi Everyone,

I m using python3 for my application and i need to capture file events using 
fsevents.
Is ter anyone knows to access fsevents in python3.

thanks for help in advance
rgds
mathan
-- 
http://mail.python.org/mailman/listinfo/python-list


Appending to sys.path

2009-03-24 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I have an application where I would like to append to the python path
dynamically.  Below is a test script I wrote.  Here's what I thought
would happen:

1) I run this script in a folder that is NOT already in PYTHONPATH
2) The script creates a subfolder called foo.
3) The script creates a file called foo.py, with a foo() method
defined in it.
4) The script attempts to import this module, which fails because the
current folder is not in PYTHONPATH.
5) The script then adds the current folder to the end of sys.path
6) The script again attempts to import foo.foo, and succeeds.

#6 never happens, but I can't figure out why.  I'm running on Mac OS
10.5, with python 2.5.1.

Anybody have any tips?

Thanks,

Mike

Here's the script:
#!/usr/bin/python

import sys
import os.path

txt = 'def foo(): print "Hello world!"\n'
if not os.path.isdir('foo'):
os.mkdir('foo')
f = open('foo/foo.py','wt')
f.write(txt)
f.close()

try:
__import__('foo.foo')
except ImportError:
homedir = os.path.abspath(sys.path[0]) #where is this script?
print 'Adding %s to sys.path' % (homedir)
sys.path.append(homedir)
try:
__import__('foo.foo')
print 'Import now successful'
except ImportError:
print "Why didn't this work?"
sys.exit(1)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems building zlib module on RHEL

2008-03-18 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Mar 18, 8:42 am, "mhearne808[insert-at-sign-here]gmail[insert-dot-
here]com" <[EMAIL PROTECTED]> wrote:
> I can't seem to get the zlib module to build on an RHEL box.
>
> I did the following:
> 1) Download zlib 1.2.3
> 2) configure;make;make install
> 3) Download python 2.5.2
> 4) configure;make;make install
> 5) >>> import zlib => "ImportError: No module named zlib"
>
> In the make install step for python, I notice there are the following
> errors:
>
> building 'zlib' extension
> gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/
> Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
> lib.linux-x86_64-2.5/zlib.so
> /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32
> against `a local symbol' can not be used when making a shared object;
> recompile with -fPIC
> /usr/local/lib/libz.a: could not read symbols: Bad value
> collect2: ld returned 1 exit status
>
> Does anyone have any hints on how to get around this?
>
> system info:
> kernel : 2.6.9-67.0.1.ELsmp
> gcc : 3.4.6
>
> Thanks,
>
> Mike

I figured it out, although it wasn't obvious... You have to compile
zlib as a shared library by running "configure -s".
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems building zlib module on RHEL

2008-03-18 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I can't seem to get the zlib module to build on an RHEL box.

I did the following:
1) Download zlib 1.2.3
2) configure;make;make install
3) Download python 2.5.2
4) configure;make;make install
5) >>> import zlib => "ImportError: No module named zlib"

In the make install step for python, I notice there are the following
errors:

building 'zlib' extension
gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/
Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
lib.linux-x86_64-2.5/zlib.so
/usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32
against `a local symbol' can not be used when making a shared object;
recompile with -fPIC
/usr/local/lib/libz.a: could not read symbols: Bad value
collect2: ld returned 1 exit status

Does anyone have any hints on how to get around this?

system info:
kernel : 2.6.9-67.0.1.ELsmp
gcc : 3.4.6

Thanks,

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


Re: compiling python 2.5, missing zlib

2007-11-21 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Nov 19, 8:22 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Those headers are already installed, according to "up2date". Is there
> > a way to specify the header files used?
>
> It will automatically use them if they are good. What's the value of
> ZLIB_VERSION in /usr/include/zlib.h?
>
> Regards,
> Martin

I got my Python compile to work, by setting recompiling the zlib
source I downloaded with a --shared configure option.

Now I'm having trouble getting the Python MySQL module to install.
That'll be a separate post!

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


Re: compiling python 2.5, missing zlib

2007-11-19 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Nov 19, 2:19 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Neither seems to work.  What am I missing here?
>
> You forgot to install the zlib header files, which come in
> an RPM provided by Redhat (probably called zlib-dev or some
> such).
>
> Regards,
> Martin

Those headers are already installed, according to "up2date". Is there
a way to specify the header files used?

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


compiling python 2.5, missing zlib

2007-11-19 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I'm trying to compile Python 2.5 on a RHEL system, using "./
configure;make;make install".  The build seems to go alright, but the
zlib module is missing.

I've tried the following:
1) Download and build the zlib libraries myself
2) Specify '--without-system-zlib' to ./configure

Neither seems to work.  What am I missing here?

Thanks,

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


Getting file timestamp from url

2007-11-16 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
Is is possible to get the timestamp of a file on a web server if it
has a URL?

For example, let's say that I want to know when the following file was
created:

http://www.w3schools.com/xml/note.xml

I can get an HTTPMessage object using urllib2, like this:

---
#!/usr/bin/python
import urllib2
url = 'http://www.w3schools.com/xml/note.xml'
f = urllib2.urlopen(url)
finfo = f.info()
---

My finfo is an HTTPMessage object, which has getdate() and
getdate_tz() methods.  However, they both require a 'name' argument.
I can't figure out what this is...

Am I going down the wrong path?  Is there a path I can go down to get
what I want?

Thanks,

Mike

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


Creating installer with external extension modules

2007-11-09 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I'm creating a piece of software which will be used by in-house
users.  My code will all be written in pure Python; however, it
depends heavily on a number of third-party Python modules, many of
which have C/C++ dependencies (numpy, scipy, etc.)  Installing these
packages on my machine involved a morning of several serial "./
configure;make;sudo make install" steps.  I'd prefer to automate all
of this for my users, but I'm not clear how to do this - I'm in an
environment of mixed Mac (desktops) and Linux (servers) and I'll need
to install on both platforms, and would prefer not to run around to
each computer making sure the dependencies are met.

I've looked through the documentation for distutils and setuptools,
and it's not obvious to me that there are hooks in either one for
passing in configure and make calls.

The fallback, I suppose, presuming that the correct version of Python
is already installed, is to write a custom Python script that "knows"
about each dependency, and takes the appropriate action.  I should be
able to depend on everyone having gcc and make installed, I think.

Does anyone have any suggestions on the best way to approach this?

Thanks,

Mike

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


Re: PYTHONPATH on OS X

2007-10-11 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Oct 10, 4:59 pm, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On Oct 11, 8:00 am, "mhearne808[insert-at-sign-here]gmail[insert-dot-
>
>
>
> here]com" <[EMAIL PROTECTED]> wrote:
> > I'm missing something major here.  I'm trying to add a directory to my
> > python path using the PYTHONPATH environment variable, and it's being
> > ignored by the Python interactive shell.
>
> > Below is a capture of what I did.  Note that my newfolder appears
> > nowhere on the list of directories in sys.path.  How do I get Python
> > to pay attention to my shell variables?
>
> > Using bash on OS X 10.4.10.
>
> > %:~ user$ echo $PYTHONPATH
>
> > %:~ user$ PYTHONPATH=/Users/user/newfolder
> > %:~ user$ echo $PYTHONPATH
> > /Users/user/newfolder
> > %:~ user$ python
> > Python 2.5.1 (r251:54863, Aug 10 2007, 10:46:58)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > import sys
> > >>> sys.path
>
> > ['', '/usr/local/lib/python2.5/site-packages/
> > setuptools-0.7a1dev_r56320-py2.5.egg', '/usr/local/lib/python2.5/site-
> > packages/ipython1-0.9alpha2-py2.5.egg', '/usr/local/lib/python2.5/site-
> > packages/SQLAlchemy-0.4.0beta5-py2.5.egg', '/usr/local/lib/python2.5/
> > site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg', '/usr/
> > local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/
> > python2.5/plat-darwin', '/usr/local/lib/python2.5/plat-mac', '/usr/
> > local/lib/python2.5/plat-mac/lib-scriptpackages', '/usr/local/lib/
> > python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/
> > lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/
> > PIL']
>
> You need to export the environment variable.
>
>   export PYTHONPATH
>
> Graham

Thanks all - I'm recently back to using Unix (Mac) after 5 years of
being on a PC.  I guess I thought export was just another way of doing
assignment.  My bad.

--Mike

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


PYTHONPATH on OS X

2007-10-10 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I'm missing something major here.  I'm trying to add a directory to my
python path using the PYTHONPATH environment variable, and it's being
ignored by the Python interactive shell.

Below is a capture of what I did.  Note that my newfolder appears
nowhere on the list of directories in sys.path.  How do I get Python
to pay attention to my shell variables?

Using bash on OS X 10.4.10.

%:~ user$ echo $PYTHONPATH

%:~ user$ PYTHONPATH=/Users/user/newfolder
%:~ user$ echo $PYTHONPATH
/Users/user/newfolder
%:~ user$ python
Python 2.5.1 (r251:54863, Aug 10 2007, 10:46:58)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.5/site-packages/
setuptools-0.7a1dev_r56320-py2.5.egg', '/usr/local/lib/python2.5/site-
packages/ipython1-0.9alpha2-py2.5.egg', '/usr/local/lib/python2.5/site-
packages/SQLAlchemy-0.4.0beta5-py2.5.egg', '/usr/local/lib/python2.5/
site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg', '/usr/
local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/
python2.5/plat-darwin', '/usr/local/lib/python2.5/plat-mac', '/usr/
local/lib/python2.5/plat-mac/lib-scriptpackages', '/usr/local/lib/
python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/
lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/
PIL']

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


Don't understand module search path...

2007-10-04 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I think I don't understand how the module search path works...

Let's say I have a folders called 'test'.  Underneath it, I create two
more folders called 'foo' and 'bar'.

In 'foo', I create an empty '__init__.py' file, indicating that this
folder is a package 'foo'.  I then create a simple python script
'foo.py' consisting of the following code:


#!/usr/bin/python

def printhello():
print 'Hello world!'


Then in test/bar, I create 'bar.py' consisting of the following code:

#!/usr/bin/python
import sys
import os
(curpath,thisdir) = os.path.split(os.getcwd())
foopath = os.path.join(curpath,'foo')
sys.path.append(foopath)
print sys.path
os.chdir(os.path.join(os.getcwd(),'..'))
print os.getcwd()
from foo.foo import printhello


When I try to run bar.py, I get the following:


[sys.path search path, including full path to 'foo' folder]
path/to/test
Traceback (most recent call last):
  File "/path/to/test/bar/testfoo.py", line 16, in 
from foo.foo import printhello
ImportError: No module named foo


Why?  If 'foo' is in sys.path, shouldn't it appear when I try to
import the foo module from it?  Incidentally, when I move the script
up to 'test' and modify it so that it just says:

#!/usr/bin/python

from foo.foo import printhello


I get no errors.  I don't understand the difference...

Incidentally, my platform info:
Python 2.5.1
Darwin Kernel Version 8.10.1 (Mac OS X)

Help!

--Mike

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


Re: fcntl problems

2007-08-31 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Aug 31, 8:42 am, Miles <[EMAIL PROTECTED]> wrote:
> On 8/31/07, mhearne808 wrote:
> > I have a script that will be run from a cron job once a minute.  One
> > of the things this script will do is open a file to stash some
> > temporary results.  I expect that this script will always finish its
> > work in less than 15 seconds, but I didn't want to depend on that.
> > Thus I started to look into file locking, which I had hoped I could
> > use in the following fashion:
>
> > Process A opens file foo
> > Process A locks file foo
> > Process A takes more than a minute to do its work
> > Process B wakes up
> > Process B determines that file foo is locked
> > Process B quits in disgust
> > Process A finishes its work
>
> That would look like (untested):
>
> importfcntl, sys
> f = open('foo', 'w+')
> try:
>fcntl.flock(f.fileno(),fcntl.LOCK_EX |fcntl.LOCK_NB)
> except IOError, e:
> if e.args[0] == 35:
> sys.exit(1)
> else:
> raise
> f.seek(0, 2) # seek to end
> # do your thing with the file
> f.flush()fcntl.flock(f.fileno(),fcntl.LOCK_UN)
> f.close()
>
> -Miles

I tested that, and it works!  Thanks!

Looking at my flock(3) man page, I'm guessing that "35" is the error
code for EWOULDBLOCK.  Which system header file am I supposed to look
in to figure that magic number out?

I would make the argument that this module could be either more
pythonic, or simply documented more completely.  The open source
response, of course, would be "go for it!".

--Mike

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


Re: fcntl problems

2007-08-31 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Aug 31, 12:23 am, Miles <[EMAIL PROTECTED]> wrote:
> Sorry, that last quote-only reply was accidental. :)
>
> On 8/30/07, mhearne808 wrote:
> > I've been doing some experiments, and here are some specific examples
> > to try.
>
> [snipped examples]
>
> > From these last two experiments I can only conclude that file locking
> > isn't doing a durned thing.
>
> > What's going on?
>
> File locking isn't doing a durned thing in those cases because you're
> only obtaining the lock from a single process.
>
> > According to my Python Cookbook:
> > "Exclusive lock: This denies all _other_ processes both read and write
> > access to the file."
>
> This is only for mandatory locking; POSIX flock is advisory locking,
> which states: "Only one process may hold an exclusive lock for a given
> file at a given time."  Advisory locks don't have any effect on
> processes that don't use locks.  Mandatory locks are kernel enforced,
> but non-POSIX and not available in Mac OS X.
>
> -Miles

I think I'm still confused.  Maybe I should explain the behavior that
I want, and then figure out if it is possible.

I have a script that will be run from a cron job once a minute.  One
of the things this script will do is open a file to stash some
temporary results.  I expect that this script will always finish its
work in less than 15 seconds, but I didn't want to depend on that.
Thus I started to look into file locking, which I had hoped I could
use in the following fashion:

Process A opens file foo
Process A locks file foo
Process A takes more than a minute to do its work
Process B wakes up
Process B determines that file foo is locked
Process B quits in disgust
Process A finishes its work

Since I couldn't figure out file locking, I decided to just have
Process A create a "pid" file in the directory - analogous to the
"Occupied" sign on an airplane bathroom.  This works, but it seems a
little hacky.

--Mike

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


Re: fcntl problems

2007-08-30 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Aug 30, 4:19 pm, "mhearne808[insert-at-sign-here]gmail[insert-dot-
here]com" <[EMAIL PROTECTED]> wrote:
> I'm having a number of problems with the fcntl module.  First off, my
> system info:
>
> Mac OS X
> Darwin igskcicglthearn.cr.usgs.gov 8.10.1 Darwin Kernel Version
> 8.10.1: Wed May 23 16:33:00 PDT 2007; root:xnu-792.22.5~1/RELEASE_I386
> i386 i386
> Python 2.5.1 (built from source)
>
> OK, the weirdness:
>
> First of all, if I try this:
> file = open("counter.txt","w+")
> fcntl.flock(file.fileno(), fcntl.LOCK_NB)
>
> I get this:
> ---
>Traceback (most recent call
> last)
> /Users/mhearne/src/python/ in ()
> : [Errno 9] Bad file descriptor
>
> However, if I try this:
> fcntl.flock(file.fileno(), fcntl.LOCK_EX)
>
> I get no errors.
>
> Proceeding forward with the locked file, let's say I do the above in
> Python interactive Process A.  Then in python interactive Process B, I
> repeat the "open" function on the same file with the same
> permissions.  Then, in each process, I write some text to the file
> using the write() method.  After closing the file in both processes,
> the only text I see in the file is from Process B!
>
> According to my Python Cookbook:
> "Exclusive lock: This denies all _other_ processes both read and write
> access to the file."
>
> I seem to be experiencing the reverse of that description.  Is this my
> lack of understanding, or have I discovered a bug?
>
> Thanks,
>
> Mike

I've been doing some experiments, and here are some specific examples
to try.  I'll designate the two interactive python processes as PA and
PB.  Both processes were started in the same directory.  Here goes:
PA: import fcntl
PA: f = open("foo.txt","w+")
PA: fcntl.flock(f.fileno(),fcntl.LOCK_EX)
PA: f.write("text1\n")
PB: f = open("foo.txt","w+")
PB: f.write("text2\n")
PA: f.close()
PB: f.close()

contents of foo.txt are:
text2

Second experiment:

PA: f = open("foo.txt","w+")
PA: fcntl.flock(f.fileno(),fcntl.LOCK_EX)
PB: f = open("foo.txt","w+")
PA: f.write("text1\n")
PB: f.write("text2\n")
PA: f.write("text3\n")
PB: f.close()
PA: f.write("text4\n")
PA: f.close()

contents of foo.txt are:
text1
text3
text4

Third experiment:
PA: f = open("foo.txt","w+")
PA: fcntl.flock(f.fileno(),fcntl.LOCK_EX)
PA: f.write("text1\n")
PB: f = open("foo.txt","w+")
PB: f.write("text2\n")
PB: f.close()
PA: f.close()

contents of foo.txt are:
text1

Fourth experiment:
PA: f = open("foo.txt","w+")
PA: f.write("text1\n")
PB: f = open("foo.txt","w+")
PB: f.write("text2\n")
PB: f.close()
PA: f.close()

contents of foo.txt are:
text1

>From these last two experiments I can only conclude that file locking
isn't doing a durned thing.

What's going on?

--Mike

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


fcntl problems

2007-08-30 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I'm having a number of problems with the fcntl module.  First off, my
system info:

Mac OS X
Darwin igskcicglthearn.cr.usgs.gov 8.10.1 Darwin Kernel Version
8.10.1: Wed May 23 16:33:00 PDT 2007; root:xnu-792.22.5~1/RELEASE_I386
i386 i386
Python 2.5.1 (built from source)

OK, the weirdness:

First of all, if I try this:
file = open("counter.txt","w+")
fcntl.flock(file.fileno(), fcntl.LOCK_NB)

I get this:
---
   Traceback (most recent call
last)
/Users/mhearne/src/python/ in ()
: [Errno 9] Bad file descriptor

However, if I try this:
fcntl.flock(file.fileno(), fcntl.LOCK_EX)

I get no errors.

Proceeding forward with the locked file, let's say I do the above in
Python interactive Process A.  Then in python interactive Process B, I
repeat the "open" function on the same file with the same
permissions.  Then, in each process, I write some text to the file
using the write() method.  After closing the file in both processes,
the only text I see in the file is from Process B!

According to my Python Cookbook:
"Exclusive lock: This denies all _other_ processes both read and write
access to the file."

I seem to be experiencing the reverse of that description.  Is this my
lack of understanding, or have I discovered a bug?

Thanks,

Mike

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


Design philosophy of HTTPServer and BaseHTTPRequestHandler

2007-08-22 Thread tzuchien chiu gmail com
Hello, everyone.

Several instances of a same script, which accepts parameters and does
a lengthy job, are executed on a remote machine. I want to couple the
script with a tiny HTTP server so that I can connect to the machine
with a browser and monitor the progress of jobs. The HTTP server of
each instance will bind to different ports.

A BaseHTTPRequestHandler-derived class must somehow know the
parameters of each instance/job in order to return instance/job-
specific result back to the client in do_GET. However, there is no way
to pass parameters (of the lengthy job) because the constructor of
HTTPServer expects a BaseHTTPRequestHandler-derived "class", instead
of an "object".

I cannot (or should not) dynamically create a "BaseHTTPRequestHandler-
derived "class" for each instance of the script, right?

Do I misunderstand the design philosophy of HTTPServer and
BaseHTTPRequestHandler, and they should not be used in this way?

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


Re: accessing parts of large files with File.seek()

2007-08-08 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Aug 8, 7:37 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> On Aug 8, 11:46 am, "mhearne808[insert-at-sign-here]gmail[insert-dot-
>
>
>
> here]com" <[EMAIL PROTECTED]> wrote:
> > I'm having a problem with the File object's seek() method.
> > Specifically, I cannot use it to seek to a location in a binary file
> > that is greater than 2^31 (2147483648).  This seems unnecessarily
> > limiting, as it is common these days to have files larger than 2 GB.
>
> > Is there some LargeFile object out there that I can use to read my
> > file, which is approximately 3.3 GB in size?
>
> > Python version (freshly built from source this morning):
> > Python 2.5.1 (r251:54863, Aug  8 2007, 09:23:05)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
>
> > Thanks,
>
> > Mike
>
> I use large files quite a bit, but in Windows & Linux.  Here's a quick
> excerpt of a local ubuntu-linux session...
>
> [EMAIL PROTECTED]:/var/virtualbox/VDI$ ls -l
> total 1682536
> -rw-rwx--- 1 jaime vboxusers  40960 2007-07-20 21:41 windows
> xp.vdi
> -rw-rwx--- 1 jaime vboxusers 3591387136 2007-07-20 21:53 winxp.vdi
> [EMAIL PROTECTED]:/var/virtualbox/VDI$ ipython
> Python 2.5.1 (r251:54863, May  2 2007, 16:27:44)
> Type "copyright", "credits" or "license" for more information.
>
> IPython 0.7.3 -- An enhanced Interactive Python.
> ?   -> Introduction to IPython's features.
> %magic  -> Information about IPython's 'magic' % functions.
> help-> Python's own help system.
> object? -> Details about 'object'. ?object also works, ?? prints more.
>
> In [1]: f = file('winxp.vdi')
>
> In [2]: f.seek(3591387132)
>
> In [3]: f.read()
> Out[3]: '\x00\x00\x00\x00'
>
> In [4]:
>
> What exception are you receiving?  (Not that I can offer any advice,
> as I don't have a Mac to use for testing.)...
>
> jw

I think I've figured out what the problem must be (not at Mac anymore,
so will have to test tomorrow).  According to this link:
http://docs.python.org/lib/posix-large-files.html

I probably need to compile in large file support on my Mac.  I get it
for free on my Ubuntu linux box...

FYI, it was an OverFlow Error.

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


accessing parts of large files with File.seek()

2007-08-08 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I'm having a problem with the File object's seek() method.
Specifically, I cannot use it to seek to a location in a binary file
that is greater than 2^31 (2147483648).  This seems unnecessarily
limiting, as it is common these days to have files larger than 2 GB.

Is there some LargeFile object out there that I can use to read my
file, which is approximately 3.3 GB in size?

Python version (freshly built from source this morning):
Python 2.5.1 (r251:54863, Aug  8 2007, 09:23:05)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin

Thanks,

Mike

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


Re: Forms with multiple submit buttons vs 'form' objects with single 'submit' methods

2006-04-13 Thread Tim Williams (gmail)
On 13 Apr 2006 12:26:52 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:Hi all,  I'm using pywin to write a script that will commandeer internet
explorer to go to a certain website, where it will navigate menus, postforms, and eventually retrieve certain data.  Here's my question:  Suppose a form has more than one submit button.Now the COM 'form' object has a 'submit' method that doesn't take any
arguments, so how do I tell it which button I want to press?  I'll be *unbelievably* grateful, for the rest of my natural life, towhomever has the answer to this.
Have a look at ishy_browser,  its in 2 parts at

http://www.ishpeck.net/index.php?P=b1115239318ishpeck

http://www.ishpeck.net/index.php?P=b1115225809ishpeck
HTH :)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: New Karrigel page in Wikipedia

2006-04-13 Thread Tim Williams (gmail)
On 13/04/06, Tim Williams (gmail) <[EMAIL PROTECTED]> wrote:
In Karrigell you could write the host mappings into a karrigell script
(.ks) application, so you wouldn't  even need to use virtual-hosts
in the config file.  and of course, you could just write a single
..ks  that contains (at least the entry points to ) all your
applications

Hmm,  out of context this could be misleading so:

In Karrigell you simply put your application into its own
directory  and access it via the  http://domain/app-dirname
-  for however many applications you need.   

Managing different apps through a single .ks script  is just something I have experimented with, but don't use very often.

:)



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

Re: New Karrigel page in Wikipedia

2006-04-13 Thread Tim Williams (gmail)
On 13/04/06, Roel Schroeven <[EMAIL PROTECTED]> wrote:

Tim Williams (gmail) schreef:> Karrigell will happily run multiple karrigell "applications" on a single> server .  In your example simply by having different applications at
> http://foo.example.com/app1 and 
http://foo.example.com/app2 will do the> trick.But I still need to allocate a port for each one, right? And write
rewrite rules to rewrite the urls:  http://foo.example.com/app1 -> 
http://foo.example.com:port1  
http://foo.example.com/app2 -> http://foo.example.com:port2
:)    No  

it is a common misconception that you need seperate ports on a webserver for different "applications" and / or sites 

Generally (ie not karrigell specific),   for *your* example 
you can run them all on the same port - as http://foo.example.com/app1
and http://foo.example.com/app2 

Generally (ie not karrigell specific), even if you are using different
hostnames in the URLs ie  http://www.mydom1.com and
http://www.mydom2.com you still don't need different
ports,  just use virtual-host (or Host-Headers in IIS ) mappings.

In Karrigell you could write the host mappings into a karrigell script
(.ks) application, so you wouldn't  even need to use virtual-hosts
in the config file.  and of course, you could just write a single
.ks  that contains (at least the entry points to ) all your
applications
HTH :)














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

Re: New Karrigel page in Wikipedia

2006-04-13 Thread Tim Williams (gmail)
On 13/04/06, Roel Schroeven <

[EMAIL PROTECTED]> wrote:
There's something I don't quite get regarding the Karrigell- andCherryPy-style frameworks. With PHP or mod_python I can put any numberof different applications in different directories on a web server,


which is very convenient: [SNIP]How do other people do this? Only one application on each (virtual)
server? Or is there something I am missing?
Karrigell will happily run multiple karrigell "applications" on a
single server .  In your example simply by having
different applications at http://foo.example.com/app1 and 


http://foo.example.com/app2 will do the trick.

HTH :)

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

Re: Receiving emails with attachments

2006-04-09 Thread Tim Williams (gmail)

On 8 Apr 2006 13:24:20 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

want to develop a script which will receive emails with attachmentsfrom my POP3 account, perform certain actions on it and email it back
to someone else.However, I'm not familiar with any Python library which does it. Couldyou a guide me to a relevant library which can handle emails?

The poplib module has already been mentioned for downloading from a pop3 mailbox

For sending mail you will need the smtplib module.    

Depending on what actions you need to perform on each email,  the email module may also be useful.

HTH :)-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: raw_input

2006-03-23 Thread Tim Williams (gmail)
On 23/03/06, cm012b5105 <[EMAIL PROTECTED]> wrote:





















 


 

if
 s = raw_input
("hello what's your name? ")
if s=='carmel
 ':
print "Ahh the boss's
wife" 

What i would like to know is what if she doesn't write 
carmel
 she rights say carm
short of me writing if s=='carm': on a new line is
there a shorter way of doing this so i can cover all
angles on how she might write her name.
Thanks nigeps I appologise
for my earlier thread> if she doesn't write 
carmel
 she rights say carm


The following will accept any subset of "carmel" in upper, lower or mixed case   

EG   Carmel, carmel, Carm, mel etc


>>> if raw_input ("hello what's your name? ").lower() in 'carmel':

...     print "Ahh the boss's wife" 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: raw_input (was "no subject")

2006-03-23 Thread Tim Williams (gmail)
On 23/03/06, cm012b5105 <[EMAIL PROTECTED]> wrote:



















Hi there i am hoping some one could help me out with a small problem
i am in the process of learning python. I am trying
to write an interactive programme,
This is a short example.
if s = raw_input
("hello what's your name? ")
if s=='carmel
':
print "Ahh the boss's
wife"

What i would like to know is what if she dont write 
carmel she rights say carm
short of me writing if s=='carm': on a new line is
there a shorter way of doing this so i can cover all
angles on how she might write her name.
Thanks nige
>>> s = raw_input ("hello what's your name? ")
Traceback (  File "", line 1
    if s = raw_input ("hello what's your name? ")
 ^
SyntaxError: invalid syntax


>>> s = raw_input ("hello what's your name? ")  # carmel
>>> if s=='carmel':
...     print "Ahh the boss's wife"
...     
Ahh the boss's wife
>>>  

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

Re: Uploading files from IE

2006-03-22 Thread Tim Williams (gmail)
On 22/03/06, AB <[EMAIL PROTECTED]> wrote:
>> try something like this:> filename = os.path.basename(fullpathname)
I tried the following with the same result:myName = ulImage.filenamenewFile = file (os.path.join(upload_dir, os.path.basename(myName)), 'wb')Any other ideas?  Seems like it shouldn't be a browser issue though...


In Karrigell,  this upload script works in IE and firefox,   and the basics are similar to yours.

import os
f = _myfile.file # file-like object
dest_name = os.path.basename(_myfile.filename)
out = open('c:/WINNT/Profiles/tw/Desktop/webupload/'+dest_name,'wb')
# copy file
import shutil
shutil.copyfileobj(f,out)
out.close()
print "File Uploaded Succesfully" #print to browser

Maybe your cgi is returning something strange, have you tried some
print statements to see what's going on at various parts of the script ?

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

Re: Server.sendmail with no "to_addrs" parameter.

2006-03-22 Thread Tim Williams (gmail)
On 22 Mar 2006 08:31:16 -0800, EdWhyatt <[EMAIL PROTECTED]> wrote:
So it's a restriction of Python?What I am trying to simulate here is the sending of mail to addressessolely in the CC and/or BCC fields - both of which are possible throughOutlook.--
http://mail.python.org/mailman/listinfo/python-listPython will quite happily do this too.  The RFC issue is a red herring,  in practice there are very few SMTP servers that will refuse an email that is missing 1 or more of the required headers.  Whether the email passes spam filters is a different matter.
For fun,  try this. (add your own gmail address, or other address and mail server)>>> import smtplib>>> server = smtplib.SMTP('gsmtp163.google.com
')>>> server.sendmail('','addr [EMAIL PROTECTED]','hello') #  '' = 2x '  not 1x "and this is the email that appeared in my gmail account almost instantly.  :):)   It was sent with no SMTP-FROM address,  and has no subject field and no address fields.
X-Gmail-Received: a567a9150c14fda1ff4d6807593843ef2ffde3acDelivered-To: addr [EMAIL PROTECTED]Received: by 10.49.69.7 with SMTP id w7cs2971nfk;
Wed, 22 Mar 2006 10:19:04 -0800 (PST)Received: by 10.36.250.61 with SMTP id x61mr1847789nzh;Wed, 22 Mar 2006 10:19:03 -0800 (PST)Return-Path: 
Received: from TW-JVC.tdw (cpc1-rdng1-0-0-cust636.winn.cable.ntl.com [82.21.66.125])by 
mx.gmail.com with ESMTP id 34si1261330nza.2006.03.22.10.19.03;Wed, 22 Mar 2006 10:19:03 -0800 (PST)Received-SPF: neutral (gmail.com: 82.21.66.125
 is neither permitted nor denied by best guess record for domain of None)Date: Wed, 22 Mar 2006 10:19:03 -0800 (PST)Message-Id: <[EMAIL PROTECTED]
>hello
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: string.upto() and string.from()

2006-03-22 Thread Tim Williams (gmail)
On 22/03/06, Tim Williams (gmail) <[EMAIL PROTECTED]> wrote:


> if  u"h" in u"hello, world !" and u"hello, world !".from("h"):
>  return " u"hello, world !"
>else:   # not really required, used for demonstration only
>  return 

:)

OK,  python allows me to code faster than I can think ( not that
hard really!! )   Proof-reading is my next personal goal too.

 Try this instead.

> if  u"h" in u"hello, world !":
>   return u"hello, world !".from("h"):>else:   # not really required, used for demonstration only
>  return 

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

Re: string.upto() and string.from()

2006-03-22 Thread Tim Williams (gmail)
On 22 Mar 2006 06:41:32 -0800, [EMAIL PROTECTED]
 <[EMAIL PROTECTED]> wrote:
I often need to re-code for myself a small code snippet to definestring.upto() and 
string.from(), which are used like :
[snip] 
# if not found, return whole string> "hello, world !".upto("#")
"hello, world !"> u"hello, world !".from("#")u"hello, world !"
[snip]
Shouldn't  

> u"hello, world !".from("#")

u"hello, world !"

return None,  otherwise what would the difference be between it and

>u"hello, world !".from("h")
u"hello, world !"

If it returns the whole string how would you test that a returned value was a not-found rather than a true result?

> if  u"h" in u"hello, world !" and u"hello, world !".from("h"):
>  return " u"hello, world !"
>else:   # not really required, used for demonstration only
>  return 

:)





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

Re: Server.sendmail with no "to_addrs" parameter.

2006-03-22 Thread Tim Williams (gmail)
On 22 Mar 2006 03:18:41 -0800, EdWhyatt <
[EMAIL PROTECTED]> wrote:
Hi all, I have searched the group with no answer to this particularproblem.In my sendmail program, I would like to have the ability to send a mailmessage with no-one email address in the To field.
I do this by adding the mail to the CC field via a header. However, by
the time I get to the point of sending the mail, my recipient list isnow empty, so I get the "SMTPRecipientsRefused" error. You are making the common mistake of thinking that the header recipients are the same as the SMTP-
envelope recipients,   in reality they do not have to bear any
similarity or relationship :)
You need a single list containing *all* the recipients by email
address,  and strings containing the text representations of the
header From, To and Cc fields.


-
HOST = '127.0.0.1'
SENDER = "[EMAIL PROTECTED]"
RECIPS =  ["[EMAIL PROTECTED]","
[EMAIL PROTECTED]","[EMAIL PROTECTED]"]
FROM = '  "[EMAIL PROTECTED]" <
[EMAIL PROTECTED]> '
TO = " [EMAIL PROTECTED] "
CC = " Uknown recipients "


def send_email(HOST,SENDER, RECIPIENTS, FROM,TO,SUBJECT ,BODY,CC=None):

    import smtplib    import string, sys    body = string.join((    "From: %s" % FROM,    "To: %s" % TO,    "Subject: %s" % SUBJECT,    "CC: %s" % CC,
    "",    BODY), "\r\n")    server = smtplib.SMTP(HOST)   server.sendmail(SENDER, RECIPIENTS,body)    server.quit()





HTH :)



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

Re: IMAP Checking Folder Size

2006-03-20 Thread Tim Williams (gmail)
On 20/03/06, Kevin F <[EMAIL PROTECTED]> wrote:
Traceback (most recent call last):   File "/Life/School/
Homework/Spring 2006/OPIM 399/Tutorial/IMAP/mailboxsize.py", line 23, in -toplevel-
 number_of_messages_all += int(number_of_messages[0])ValueError: invalid literal for int(): The requested item could not be
found.
See the answer(s)  to your previous post.

> File "/Life/School/Homework/Spring 2006/OPIM

However,  seeing as this is homework, its unlikely you'll get the fix,  just pointers to where your mistakes are. :)

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

Re: IMAP Folder Size Information

2006-03-20 Thread Tim Williams (gmail)
On 20/03/06, Kevin F <[EMAIL PROTECTED]> wrote:
I'm trying to use the following code to get my remote server's foldersize information.  Unfortunately, i'm getting the error:Traceback (most recent call last):   File "/Life/School/Homework/Spring 2006/OPIM
399/Tutorial/IMAP/mailboxsize.py", line 23, in -toplevel- number_of_messages_all += int(number_of_messages[0])ValueError: invalid literal for int(): The requested item could not befound.
The error is on line 23,  so insert the following print statement at line 23

23    print "number_of_messages =", number_of_messages   #  For debugging
24    number_of_messages_all += int(number_of_messages[0])  # original line

and the reported error changes to:

number_of_messages =  ['Could not select box']
Traceback (most recent call last):
  File "C:\MXEXTRA\scripts\imapt1.py", line 24, in ?
    number_of_messages_all += int(number_of_messages[0])
ValueError: invalid literal for int(): Could not select box

HTH :)


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

Re: string stripping issues

2006-03-03 Thread Tim Williams (gmail)
On 3 Mar 2006 00:20:21 -0800, P Boy <[EMAIL PROTECTED]> wrote:
This seems like a web page parsing question. Another approach can be asfollows if you know the limiting token strings:a.split('SIZE=2>')[1].split('\r\n')[0]


As others have mentioned , you really need a an HTML parser.   But the following would work better than strip()

>>> a = '    Hughes. John\r\n'
>>> a.replace('    ', '' )  #  '' = 2 single quotes not 1 double quote
'Hughes. John\r\n'

HTH :)
-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: regular expresson for Unix and Dos Lineendings wanted

2006-02-24 Thread Tim Williams (gmail)
On 24/02/06, John Zenger <[EMAIL PROTECTED]> wrote:
Franz Steinhaeusler wrote:>> Thank you all for the replies.> But I still don't have a solution.>re.sub(r"\s+[\n\r]+", lambda x: x.expand("\g<0>"). \ lstrip(" \t\f\v"),text).rstrip()
But I think your code is a lot easier to read.  :)
How about:

>>> linesep = '\n'
>>> text = 'erewr  \t  \r\nafjdskl  \r\n  \r\npythonlist' 
>>> linesep.join([ x.rstrip() for x in text.replace('\r\n','\n').replace('\r','\n').split('\n') ])
'erewr\nafjdskl\n\npythonlist'

Which right-strips the line endings, tabs and spaces from the ends of
lines in a string derived from either Windows, Mac and Unix  or
mixed files 

HTH :)
-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: problem(s) with import from parent dir: "from ../brave.py import sir_robin"

2006-02-24 Thread Tim Williams (gmail)
On 24 Feb 2006 05:10:37 -0800, per9000 <[EMAIL PROTECTED]> wrote:
SHORT VERSION:I tried three variants of "from ../brave.py import sir_robin", oneworks. I want to use it in a py-file to execute command-line-style andthat does not work.Can someone please give me, not a bucket with the desert(s) on top, but
just the thin chocolate?
Add the absolute path to a file called python.pth in your c:\python2x directory 
using the format:  

C:\my\holy\py_scripts (newline)  
for *each* directory and subdirectory

Then simply import the module as normal

>>>from raw2nice_def import raw2nice

HTH :)

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

Re: Zope/Plone - Is it the right solution?

2006-02-21 Thread Tim Williams (gmail)
On 21 Feb 2006 08:00:03 -0800, Michele Simionato <[EMAIL PROTECTED]> wrote:
For easy of use nothing beats CherryPy, but I am not sure how stable itis.
If CherryPy is of interest then don't discount Karrigell,  it has
a smaller learning curve and appears stable.   Overall I
found it quicker to become productive than with CP.    

see   http://quentel.python-hosting.com/wiki/index.pih  and  http://karrigell.sourceforge.net/

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

Re: multiple email recipients

2006-02-20 Thread Tim Williams (gmail)
On 20/02/06, Rene Pijlman <[EMAIL PROTECTED]> wrote:
[EMAIL PROTECTED]:>was wondering how to modify the code so as i can send to multiple email
>recipients using "TO"? thanks.You add RFC 2822 headers.http://www.ietf.org/rfc/rfc2822.txt("3.6.3. Destination address fields")

RFC 2822 relates to the format of the message,  not the sending of
it.   Adding headers such as "Destination address
fields"  will not affect nor necessarilly be related in any way to
the actual recipients of the message

The correct RFC might be RFC 2821 , Simple Mail Transfer Protocol.
   But the OP doesn't need RFC help,  just help with the
smtplib module itself.  :)



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

Re: multiple email recipients

2006-02-20 Thread Tim Williams (gmail)
On 20 Feb 2006 01:01:38 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:hii currently am using this email function that can send single email
address[SNIP]was wondering how to modify the code so as i can send to multiple emailrecipients using "TO"? thanks.
You are making the common mistake of thinking that the header sender
and  recipients are the same as the SMTP-envelope sender and
recipients,   in reality they do not have to bear any
similarity or relationship :)

You need a single list containing all the recipients by email
address,  and strings containing the text representations of the
header From, To and Cc fields.

There is a module called email,  so beware of calling your
function the same name.  Also,  you may find the email module
becomes helpful for building emails as your function/requirements get
more complex.

-

SENDER = "[EMAIL PROTECTED]"
RECIPS =  ["[EMAIL PROTECTED]","[EMAIL PROTECTED]","[EMAIL PROTECTED]"]
FROM = '  "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> '
TO = " Undisclosed recipients "
CC = " Uknown recipients "

def email(HOST,SENDER, RECIPIENTS, FROM,TO,SUBJECT ,BODY,CC=None):
    import smtplib    import string, sys    body = string.join((    "From: %s" % FROM,    "To: %s" % TO,    "Subject: %s" % SUBJECT,    "CC: %s" % CC,
    "",    BODY), "\r\n")    server = smtplib.SMTP(HOST)   failed =  server.sendmail(SENDER, RECIPIENTS,body)    server.quit()



HTH :)-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python create mail

2006-01-12 Thread Tim Williams (gmail)
 on 1/12/06, Tim Williams (gmail) <
[EMAIL PROTECTED]> wrote:

On 12 Jan 2006 04:28:44 -0800, 

[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: 

hey I need help in sending email,It seems that while using  this set of commands

from smtplib import SMTPs = SMTP()s.set_debuglevel(1)s.connect('outmail.huji.ac.il')
I should be able to get a connection but what I get is this error
T:\Anya\work>mail1.pyconnect: ('outmail.huji.ac.il', 25)connect: ('

outmail.huji.ac.il', 25)connect fail: (' outmail.huji.ac.il', 25)Traceback (most recent call last):
File "C:\Python24\lib\smtplib.py", line 303, in connectraise socket.error, msgsocket.error: (10053, 'Software caused connection abort') Does any one have a clue ?

>>> from smtplib import SMTP>>> s = SMTP()>>> s.set_debuglevel(1)>>> s.connect('

outmail.huji.ac.il')connect: ('outmail.huji.ac.il', 25)connect: ('

outmail.huji.ac.il', 25)reply: '220 mail3.cc.huji.ac.il ESMTP Postfix\r\n'reply: retcode (220); Msg: 
mail3.cc.huji.ac.il ESMTP Postfixconnect: 

mail3.cc.huji.ac.il ESMTP Postfix(220, 'mail3.cc.huji.ac.il ESMTP Postfix')>>> s.quit

Suspect a local / network firewall or port 
block.    It might possibly be a DNS issue,  the
server's IP address is 
132.64.1.30 . You should try telnetting to the IP address on port 25 as a testHTH :)
> On 12/01/06, anya bondarev <[EMAIL PROTECTED]> wrote:
> First thanks for your answer..


>  

> I tried to open the connection using telnet and the connection couldnt be opened >  

> any advice ?

The problem isn't python.  Your pc(?) is not able to connect to
this mail server. If you have a firewall, 
turn it off very briefly while you retry the telnet test.  
If this doesn't help,  then you will need to contact your network
provider (eg: your IT dept, or your home ISP) and ask them if they are
blocking port 25 outbound.    Until you get telnet to
work,  your python will not work either.

HTH :)-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to remove subset from a file efficiently?

2006-01-12 Thread Tim Williams (gmail)
On 12/01/06, Tim Williams (gmail) <[EMAIL PROTECTED]> wrote:
On 12 Jan 2006 09:04:21 -0800, fynali <
[EMAIL PROTECTED]> wrote:

Hi all,I have two files:  - PSP320.dat (quite a large list of mobile numbers),  - CBR319.dat (a subset of the above, a list of barred bumbers)# head PSP320.dat CBR319.dat

==> PSP320.dat <==96653696338966537669969665460943196654722608966547380749665569704496655824738966561901179665625676296656263751
==> CBR319.dat <==96651131135966511311359665142041296651730095966523991179665239914296652399142966523991429665239916096652399271
Objective: to remove the numbers present in barred-list from thePSPfile.$ ls -lh PSP320.dat CBR319..dat...  56M Dec 28 19:41 PSP320.dat... 8.6M Dec 28 19:40 CBR319.dat

$ wc -l PSP320.dat CBR319.dat 4,462,603 PSP320.dat   693,585 CBR319.datI wrote the following in python to do it:#: c01:rmcommon.pybarredlist = open(r'/home/sjd/python/wip/CBR319.dat', 'r')
postlist = open(r'/home/sjd/python/wip/PSP320.dat', 'r')outfile = open(r'/home/sjd/python/wip/PSP-CBR.dat', 'w')# reading it all in one go, so as to avoid frequent disk accesses(assume machine has plenty memory)
barredlist.read()postlist.read()#for number in postlist:if number in barrlist:passelse:outfile.write(number)
barredlist.close(); postlist.close(); outfile.close()#:~The above code simply takes too long to complete.  If I were to do adiff -y PSP320.dat CBR319.dat, catch the '<' & clean it up with
sed -e 's/\([0-9]*\) * PSP-CBR.dat it takes <4 minutes tocomplete.

It should be quicker to do this

    #
    for number in postlist:
            if not number in barrlist:
                   outfile.write(number)


and quicker doing this

    #
numbers =  [number for number in postlist if not number in barrlist]c 
I forgot to add this one

for num in (number for number in postlist if not number in barrlist):
 outfile.write(number)




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

Re: How to remove subset from a file efficiently?

2006-01-12 Thread Tim Williams (gmail)
On 12 Jan 2006 09:04:21 -0800, fynali <[EMAIL PROTECTED]> wrote:
Hi all,I have two files:  - PSP320.dat (quite a large list of mobile numbers),  - CBR319.dat (a subset of the above, a list of barred bumbers)# head PSP320.dat CBR319.dat
==> PSP320.dat <==96653696338966537669969665460943196654722608966547380749665569704496655824738966561901179665625676296656263751
==> CBR319.dat <==96651131135966511311359665142041296651730095966523991179665239914296652399142966523991429665239916096652399271
Objective: to remove the numbers present in barred-list from thePSPfile.$ ls -lh PSP320.dat CBR319.dat...  56M Dec 28 19:41 PSP320.dat... 8.6M Dec 28 19:40 CBR319.dat
$ wc -l PSP320.dat CBR319.dat 4,462,603 PSP320.dat   693,585 CBR319.datI wrote the following in python to do it:#: c01:rmcommon.pybarredlist = open(r'/home/sjd/python/wip/CBR319.dat', 'r')
postlist = open(r'/home/sjd/python/wip/PSP320.dat', 'r')outfile = open(r'/home/sjd/python/wip/PSP-CBR.dat', 'w')# reading it all in one go, so as to avoid frequent disk accesses(assume machine has plenty memory)
barredlist.read()postlist.read()#for number in postlist:if number in barrlist:passelse:outfile.write(number)
barredlist.close(); postlist.close(); outfile.close()#:~The above code simply takes too long to complete.  If I were to do adiff -y PSP320.dat CBR319.dat, catch the '<' & clean it up with
sed -e 's/\([0-9]*\) * PSP-CBR.dat it takes <4 minutes tocomplete.

It should be quicker to do this

    #
    for number in postlist:
            if not number in barrlist:
                   outfile.write(number)


and quicker doing this

    #
numbers =  [number for number in postlist if not number in barrlist]
outfile.write(''.join(numbers)) 

HTH 

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

Re: how to improve this simple block of code

2006-01-12 Thread Tim Williams (gmail)
On 11/01/06, Mike Meyer <[EMAIL PROTECTED]> wrote:
"py" <[EMAIL PROTECTED]> writes:> Say I have...> x = "132.00"> but I'd like to display it to be "132" ...dropping the trailing
> zeros...I currently try this
Is it likely that  x might not have any decimal
places?    If so all the above solutions fail when x
=130 except Matt Hammond's offering which splits x at the decimal point
if one exists.

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

Re: python create mail

2006-01-12 Thread Tim Williams (gmail)
On 12 Jan 2006 04:28:44 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
hey I need help in sending email,It seems that while using  this set of commands
from smtplib import SMTP s = SMTP() s.set_debuglevel(1) s.connect('outmail.huji.ac.il')I should be able to get a connection but what I get is this error
T:\Anya\work>mail1.pyconnect: ('outmail.huji.ac.il', 25)connect: ('outmail.huji.ac.il', 25)connect fail: ('
outmail.huji.ac.il', 25)Traceback (most recent call last):File "C:\Python24\lib\smtplib.py", line 303, in connectraise socket.error, msgsocket.error: (10053, 'Software caused connection abort')
Does any one have a clue ?
>>> from smtplib import SMTP
>>> s = SMTP()
>>> s.set_debuglevel(1)
>>> s.connect('outmail.huji.ac.il')
connect: ('outmail.huji.ac.il', 25)
connect: ('outmail.huji.ac.il', 25)
reply: '220 mail3.cc.huji.ac.il ESMTP Postfix\r\n'
reply: retcode (220); Msg: mail3.cc.huji.ac.il ESMTP Postfix
connect: mail3.cc.huji.ac.il ESMTP Postfix
(220, 'mail3.cc.huji.ac.il ESMTP Postfix')
>>> s.quit

Suspect a local / network firewall or port 
block.    It might possibly be a DNS issue,  the
server's IP address is 132.64.1.30 . You should
try telnetting to the IP address on port 25 as a test

HTH :)


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

Re: smtplib error('Connection reset by peer')

2006-01-05 Thread Tim Williams (gmail)
On 4 Jan 2006 15:47:34 -0800, Van_Gogh <[EMAIL PROTECTED]> wrote:
Hi,I am learning how to use the smtplib module, but am having some veryearly problems, maybe because I don't understand it.So, am I correct that by following the example in the Python:

[snip] 
 When I try to create the server(the line 'server =smtplib.SMTP('localhost')) I get the following error message:

[snip] 
error: (10054, 'Connection reset by peer')Anyone got a pointer as to what I could do?

Try turning off your XP firewall . If this doesn't help,  try this from a command prompt

c:\> telnet localhost 25  (return)

you should get some response from your server beginning with "220", if not then Python isn't the problem.

in the telnet session,  type "quit "  + return  to end the session.

HTH :)
-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: compare dictionary values

2006-01-03 Thread Tim Williams (gmail)
On 30/12/05, rbt <[EMAIL PROTECTED]> wrote:
What's a good way to compare values in dictionaries? I want to find[snip]My key-values pairs are filepaths and their modify times. I want toidentify files that have been updated or added since the script last ran.

You don't need to store each file's updated time, you only need to
store the last time you ran the script and to compare each file's
modified time against that last-run time.   Dictionaries
aren't required

eg:

 #    to get files changed (added/modified) since a given date
import time, os
last_run = time.time() - (60*60*24*30*12)   # for testing, set to one year ago
changed = [x for x in  os.listdir('c:/python24') if os.path.getmtime(os.path.join('c:/python24' , x)) > last_run]
# script end

>From your previous posts, I believe you are storing details of *every*
file  within a dictionary that is pickled to your hard disk, 
then periodically creating a new dict  of *every* file and
comparing it against the original dict.   Then you must be
updating the original dict with the new times and storing it back to
disk.   The above list comprehension will give the same
result for files/dirs in a single directory,  you just need to
store the time of the last script run to disk instead.

if you are walking several directories, the principle is the same,

>>> last_run = time.time() - (60*60*24*30)  # 1 month ago
>>> for root, dirs, files in os.walk('c:/python24'):
...     for name in files:
...         if os.path.getmtime(os.path.join(root , name)) > last_run:
...             print os.path.join(root , name)
...             
c:/python24\Lib\asynchat.pyc
c:/python24\Lib\calendar.pyc
c:/python24\Lib\gzip.pyc
c:/python24\Lib\imghdr.pyc
c:/python24\Lib\SimpleHTTPServer.pyc
c:/python24\Lib\sndhdr.pyc
c:/python24\Lib\webbrowser.pyc
c:/python24\Lib\_strptime.pyc
c:/python24\Lib\email\MIMEAudio.pyc
c:/python24\Lib\email\MIMEImage.pyc
c:/python24\Lib\email\MIMEMessage.pyc
c:/python24\Lib\email\MIMEMultipart.pyc
>>>




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

Re: compare dictionary values

2005-12-30 Thread Tim Williams (gmail)
In <[EMAIL PROTECTED]>, rbt wrote:
> What's a good way to compare values in dictionaries?
Do you need to compare dictionaries, if its an option it would be
simpler/cheaper  to compare  each entry from your file
listing with entries in a single dict and act accordingly, mainly
because you will already have built your path/date pairs from your dir
listing,  adding them to a dict purely for comparison is an extra
step.

import os

new_files = [ ]
changed = [ ]

listing = os.listdir('c:/python24')
for a_file in listing:
    f_date = os.path.getmtime(os.path.join('c:/python24' , a_file))
    try
    if mydict[a_file] != f_date:
    changed.append(a_file)
    except:
    new_files.append(a_file)
    mydict[a_file] = f_date

deleted = [ key for key in mydict if not key in listing ]

for x in deleted:
    del mydict[x]

print changed
print new_files
print deleted

HTH :)






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

Re: reading files into dicts

2005-12-30 Thread Tim Williams (gmail)
On 30/12/05, Chris F.A. Johnson <[EMAIL PROTECTED]> wrote:
On 2005-12-30, Tim Williams (gmail) wrote:> Apologies for the top post, it was my first attempt at using gmail's> pda-enabled web interface. There is no option to bottom post.Can you not move the cursor?

Nope,  there is a checkbox option to include the original post, if you include it, it appears under your new text. :-) 

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

Re: reading files into dicts

2005-12-29 Thread Tim Williams (gmail)
Apologies for the top post, it was my first attempt at using gmail's
pda-enabled web interface. There is no option to bottom post.

Apart from the mistake in my previous reply, when I meant to suggest
using import instead of eval() not repr(). I also omitted an example.
So here goes -but I don't know how gmail-CE will format this!!

Save your dict to a file  with a .PY extension using

outdata = 'mydict =' + repr(dict) # or somesuch
 similar

dictfile.py
---
mydict = {'key1':'a', 'key2':'b'}
---

Then:

import dictfile
print dictfile.mydict.keys()
>>>['key1','key2']
reload(dictfile)

HTH :-)

--

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


Re: reading files into dicts

2005-12-29 Thread Tim Williams (gmail)
A further thought, if you write the data to a file in the correct
format, you can use import and reload to access the data later instead
of repr.





On 12/29/05, Tim Williams (gmail) <[EMAIL PROTECTED]> wrote:
> On 30/12/05, Giovanni Bajo <[EMAIL PROTECTED]> wrote:
> >
> >
> > >>> d = {'.\\sync_pics.py': 1135900993, '.\\file_history.txt':
> 1135900994,
> >  '.\\New Text Document.txt': 1135900552}
> > >>> file("foo", "w").write(repr(d))
> > >>> data = file("foo").read()
> > >>> data
> > "{'.sync_pics.py': 1135900993, '.file_history.txt': 1135900994,
> > '.New Text Document.txt': 1135900552}"
> > >>> d = eval(data)
> > >>> d
> > {'.\\sync_pics.py': 1135900993, '.\\file_history.txt': 1135900994,
> '.\\New
> > Text
> > Document.txt': 1135900552}
> >
> > eval() is risky if you can't control the contents of the file  :)
>
>


--

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


Re: reading files into dicts

2005-12-29 Thread Tim Williams (gmail)
On 30/12/05, Giovanni Bajo <[EMAIL PROTECTED]> wrote:
>>> d = {'.\\sync_pics.py': 1135900993, '.\\file_history.txt': 1135900994, '.\\New Text Document.txt': 1135900552}>>> file("foo", "w").write(repr(d))>>> data = ""
>>> data"{'.sync_pics.py': 1135900993, '.file_history.txt': 1135900994,'.New Text Document.txt': 1135900552}">>> d = eval(data)>>> d{'.\\sync_pics.py': 1135900993, '.\\file_history.txt': 1135900994, '.\\New Text
Document.txt': 1135900552}eval() is risky if you can't control the contents of the file  :)

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

Re: reading files into dicts

2005-12-29 Thread Tim Williams (gmail)
On 30/12/05, rbt <[EMAIL PROTECTED]> wrote:
What's a good way to write a dictionary out to a file so that it can beeasily read back into a dict later? I've used realines() to read textfiles into lists... how can I do the same thing with dicts? Here's some
sample output that I'd like to write to file and then read back into a dict:
Depending on how often you need to read/write/access the dict, 
either the shelve module,  or the pickle / cpickle modules will do
what you need.
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Modifying values in a list

2005-12-29 Thread Tim Williams (gmail)
On 29 Dec 2005 08:43:17 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:The following code:numbers = [1, 2, 3]for value in numbers:
value *= 2print numbers
Above,  you are modifying "value", not the item in the list


>>> numbers = [1, 2, 3]
>>> for x in range(len(numbers)):
...     numbers[x] = numbers[x]*2
>>> numbers
[2, 4, 6]
HTH :)-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Windows and python execution

2005-12-26 Thread Tim Williams (gmail)
On 26/12/05, Mark Carter <[EMAIL PROTECTED]> wrote:
What I would like to do it type something like > myscript.pyinstead of > python myscript.py

Open an explorer window or open "My Computer"

  Click on TOOLS then FOLDER OPTIONS
  Select the "FILE TYPES tab and click on NEW
  Enter  PY as the file extension and click OK
  Select PY from the list and click CHANGE
  Select your Python.exe executable from the list or (using other) from your Python folder
  

in your Python folder (c:\python24?) create a file called
python.pth  and add a line for any  *subdir*  that you
have stored your python apps and scripts in eg:

c:\pythonapps
c:\pythonapps\data
c:\pythontest
c:\pythontest\archives
c:\pythontest\archives\temp

HTH :)





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

Re: File object question

2005-12-22 Thread Tim Williams (gmail)
On 22/12/05, S. D. Rose <[EMAIL PROTECTED]> wrote:
Hello all.  If I read a binary file:file = open('c:\\logo.gif', 'rw'') # Read from FS as one way to get theobject, d/l from website another...file.read()is there anyway I can determine the 'size' of the object file? (Without
going to the filesystem and reading the filesize from the directory ...
On my w2k box I use this for binary files

file = open('c:\\logo.gif', 'r+b'') # Read from FS as one way to get the
object, d/l from website another...
file_read = file.read() 
len(file_read)
Note:  you must specify the binary option for binary files or you may not get the whole file.HTH :)
-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A simple list question.

2005-12-22 Thread Tim Williams (gmail)
On 22/12/05, Tim Williams (gmail) <[EMAIL PROTECTED]> wrote:
On 22 Dec 2005 10:14:10 -0800, KraftDiner <
[EMAIL PROTECTED]> wrote:
Is there a cleaner way to implement this code?if
len(self.listOfObjects) == 0:self.listOfObjects.append(self.currentObject)elif:self.listOfObjects[self.currentSlice]
= self.currentObjectlistOfObjects is a list of listsIf the listOfObjects is [] then I have to use append to add the firstlistotherwise I can access each list using the index into the list.


I'm assuming from your code that self.listOfObjects always exists (even
if it is empty) and that self.currentObject is also  list. 

   if  (not self.listOfObjects) or (self.listOfObjects[self.currentSlice] = self.currentObject):
   
self.listOfObjects =  self.currentObject 

 If self.currentObject is not a list or is only sometimes a list then change the 2nd line to 

  
self.listOfObjects =  list( self.currentObject )

HTH :)-- Tim Williams

OOPS !!   completely misread your code, should that elif be an else?

Try this:

   
if not self.listOfObjects:self.listOfObjects.append(self.currentObject)
  
#or:  self.listOfObjects = list(self.currentObject)
elif 
self.listOfObjects[self.currentSlice]
= self.currentObject :
   
do something
   
else:



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

Re: A simple list question.

2005-12-22 Thread Tim Williams (gmail)
On 22 Dec 2005 10:14:10 -0800, KraftDiner <[EMAIL PROTECTED]> wrote:
Is there a cleaner way to implement this code?if
len(self.listOfObjects) == 0:self.listOfObjects.append(self.currentObject)elif:self.listOfObjects[self.currentSlice]
= self.currentObjectlistOfObjects is a list of listsIf the listOfObjects is [] then I have to use append to add the firstlistotherwise I can access each list using the index into the list.

I'm assuming from your code that self.listOfObjects always exists (even
if it is empty) and that self.currentObject is also  list. 

   if  (not self.listOfObjects) or (self.listOfObjects[self.currentSlice] = self.currentObject):
   
self.listOfObjects =  self.currentObject 

 If self.currentObject is not a list or is only sometimes a list then change the 2nd line to 

  
self.listOfObjects =  list( self.currentObject )

HTH :)-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Parsing a date-time string?

2005-12-22 Thread Tim Williams (gmail)
On 21 Dec 2005 01:43:13 -0800, Tim N. van der Leeuw <[EMAIL PROTECTED]> wrote:
Hi,I want to parse strings containing date-time, which look like thefollowing:
 "Mon Dec 19 11:06:12:333 CET 2005"[snipped]What I want to get is some sort of sortable date; either as a number or(if nothing else) as a string in ISO8601 format.
Its slow in the office today, so: ..

##

from email import Utils
import time

zones = {'CET': '+0100', 'GMT': '', 'EST': '-0500', 'PST': '-0800'}

def get_sortable_time(a_date):
    split_date = a_date.split()

    split_time = split_date[3].split(':')  # split the time
    microsecs = float('0.'+ split_time[-1])   # get the microseconds
    split_date[3] = ':'.join(split_time[:-1])    # join time, without microseconds 
    
    split_date[4] = zones[split_date[4]]     # convert the timezone to '-0800' format
    split_date = '
'.join(split_date) 
# eg "Mon Dec 19 11:06:12 +0100 2005"

    gmt_time_as_num = Utils.mktime_tz(Utils.parsedate_tz(split_date) )   # eg 1134993972.0

    return gmt_time_as_num + microsecs # time in GMT,  eg 1134993972.33 
    
sortable_time = get_sortable_time( "Mon Dec 19 11:06:12:333 CET 2005" )

print sortable_time          # = 1134993972.33  (in time.time() format )

print time.ctime(sortable_time)  # Mon Dec 19 12:06:12 2005

##
You could remove the 2 "microsecs" references if you don't need that level of granularity

 HTH :)

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

Re: coverting EST to PST

2005-12-21 Thread Tim Williams (gmail)
On 21 Dec 2005 03:15:47 -0800, Narendra <
[EMAIL PROTECTED]> wrote:
Hi All,i got a problem. I need to convert time from EST standard to PSTstandard.Thu, 15 Dec 2005 09:24:19 -0500 to PST

Quick and dirty,   might not work for times at the end of DST

>>> import time
>>> from email import Utils

>>> def tconv(t):
...     t1 = Utils.mktime_tz(Utils.parsedate_tz(t))
...     return time.ctime(t1 -(8*60*60)) + ' -0800'

>>> tconv('Thu, 15 Dec 2005 09:24:19 -0500')
'Thu Dec 15 06:24:19 2005 -0800'


Failing that,  google for "python converting timezones"

HTH :)

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

Re: Queueing in Python (ala JMS)

2005-12-20 Thread Tim Williams (gmail)
On 20 Dec 2005 15:01:02 +0100, Stefan Arentz <[EMAIL PROTECTED]> wrote:
Is there a JMS-like API available for Python? I would like toquickly receive messages through the network and then processthose slowly in the backgound. In the Java world I would simplycreate a (persistent) queue and tell the JSM provider to run
N messagehandlers parallel.Is something like that available for Python?

The Queue module

import Queue
q = Queue.Queue  

and  pass q as an argument to each "worker" , 

Then use , 

q.put()

q.get()  # or q.get(1)  if you need to wait for something to appear


HTH :)


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

Re: checking if a string contains a number

2005-12-20 Thread Tim Williams (gmail)
On 20/12/05, Suresh Jeevanandam <[EMAIL PROTECTED]> wrote:
Hi,I have a string like,s1 = '12e3's2 = 'junk'Now before converting these values to float, I want to check if theyare valid numbers.s1.isdigit returns False.
Is there any other function which would return True for s1 and Falsefor s2.
float()  itself can do the checking for you.  
 >>> for n in ['12e3','junk']:
...     try:
...         float(n)
...     except:
...         print "not valid: ",  n
...         
12000.0
not valid: junk
>>> 

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

Re: How to get the path of current running python script?

2005-12-20 Thread Tim Williams (gmail)
On 20/12/05, Kevin Yuan <[EMAIL PROTECTED]> wrote:
I tried the following  getFilePath = lambda name: os.path.normpath('%s\\%s' % (sys.modules[name].prefix, sys.modules[name].__name__))

 getFilePath('__main__')

getFilePath =  sys.argv[0]    ??

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

Re: Displaying error message in a try except?

2005-12-11 Thread Tim Williams (gmail)
On 11/12/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
[EMAIL PROTECTED] wrote:> Fairly new to python.  In a try except how do you display the true> (raw) error message so it can be displayed back to the user?
assuming that "true" means "the message you would get if you hadn'tused a try/except", the traceback module is what you want:import tracebacktry:raise SyntaxError("example")
except:traceback.print_exc()printsTraceback (innermost last):  File "module.py", line 4, in ?SyntaxError: examplemore here:
http://effbot.org/librarybook/traceback.htmyou can also inspect the exception status via the sys.exc_info() call.e.g.import systry:1/0except:print "%s: %s" % 
sys.exc_info()[:2]printsexceptions.ZeroDivisionError: integer division or modulo by zero
Or you can combine both,  I find these 3 lines after the except
most helpful during developement stages and liberally splatter them
around prototype code 

>>> import sys, traceback
>>> try:
...     1/0
... except:
... print sys.exc_info()[0]
... print sys.exc_info()[1]
... print "LINE=",traceback.tb_lineno(sys.exc_info()[2])
... 
exceptions.ZeroDivisionError
integer division or modulo by zero
LINE= 2>>>
HTH :)


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

Re: information needed to make a connection between computers

2005-12-11 Thread Tim Williams (gmail)
On 11/12/05, John Walton <[EMAIL PROTECTED]> wrote:
 Hello again! I'm still working on that instant messenger
(for science fair), and I have been reading about networking in some
Java tutorials. In one part of it, it said to have a connection with
another computer, you need to know the IP name of the computer you want
to connect with. I don't know whether or not this is the same for
Python, but could someone please tell me what information of the
computer you want to connect with the you actually need for a
connection? In other words (or plain english), what information do I
need to get a connection with another computer (IP address, name, IP
name)? Also, could you tell me how to find it on a computer? Since I'll
be testing the instant messenger on the three computers in my house, I
just need to know how to find the information on the computer I'd
currently be on (not from any remote location). Thanks!  :)

You need to know the hostname of the remote machine you are trying to
make a connection to.    From this you can work out the
IP address of the machine and then connect to it
directly.    You could work with just the IP address,
but these are liable to change, where as the hostname in theory won't.

>>> import socket
>>> socket.gethostbyname('www.yahoo.com')
'216.109.117.207'
>>> 

If the machine is on your network,  using its name (eg 'JohnW'   )  should give the same result

HTH :)


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

Re: Validating an email address

2005-12-09 Thread Tim Williams (gmail)
On 09/12/05, Ben Finney <[EMAIL PROTECTED]> wrote:
The only validation you should be doing before sending the message ison the domain part. Since there are records available in DNS toverify, you can check those. Is there an MX record? Is the addressvalid? Do the mappings both way for that record make sense?

Agreed,  BUT !!!

An MX record is not required by RFCs, a single  A record should be
tried if there are no MX records.  And the sending server's PTR
doesn't have to match its hostname(s), nor the domain in the email
address

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

Re: Constructing RFC2822 Message

2005-12-05 Thread Tim Williams (gmail)
On 5 Dec 2005 06:27:44 -0800, Narendra <[EMAIL PROTECTED]> wrote:
Hi All,This is narendra from india doing my engineering.i need to develop an E-mail client in python,which connects to my MTAon port 25 and sends email from there.I was able to do that but my e-mail is ending in bulk when i'm trying
to senf to hotmail/msn.

Hotmail score spam/junk/ on several criteria.   Including
whether the msg has a msg-id  (yours doesn't) and whether the
envelope sender and recipient(s)  match the header sender and
recipient(s).   Have a look at the headers from spam and not
spam in your hotmail account to see what sort of headers each type has
(or hasn't).

Also,  you may be better off using smtplib for the sending
portion,   the error types will be more informative if there
is a connection or sending issue.

HTH :)
-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [Forged?] Re: How to find the port a server is listening on (from within the server)

2005-11-25 Thread Tim Williams (gmail)
On 26/11/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
   If I understand correctly, you're looking for the socket methodgetsockname(), documented at
http://docs.python.org/lib/socket-objects.htmlJeff
Many thanks Jeff, self.server.socket.getsockname() did the trick.

-- 


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

How to find the port a server is listening on (from within the server)

2005-11-25 Thread Tim Williams (gmail)
How can I find the port a server is listening on - at the commented
line in the code below. (ie  self.serving_on_port_num = 
? )

I have googled a lot. :-(

--

class BaseSrvr(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def server_bind(self):
    """Override server_bind to store the server name."""
    try:
    SocketServer.TCPServer.server_bind(self)
    host, port = self.socket.getsockname()
    self.server_name = socket.getfqdn(host)
    self.server_port = port
    except:
    print "***server bind except"

class RequestHandler(SocketServer.StreamRequestHandler):
    def handle(self):
    self.incoming_port =
self.client_address[1]    
#===>   self.serving_on_port_num =  ?
# The number of the serving port not the connecting port

def StartServer(port):
    server = BaseSrvr(('', int(port) ), RequestHandler )
    server.serve_forever()

if __name__ == '__main__':

    StartServer(port)   
--
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: query domain registry from python?

2005-11-20 Thread Tim Williams (gmail)
On 19 Nov 2005 19:40:58 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:hi, does anyone know of a library that can query domain registry or any
site that provide information to such an activity? as i want to build asimple domain name searching program for my own benefit.. thanks alot :D
[TW]   Try http://www.faqts.com/knowledge_base/view.phtml/aid/4568 


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

Re: Adding through recursion

2005-11-18 Thread Tim Williams (gmail)
On 18 Nov 2005 06:30:58 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:> I still don't get it. I tried to test with x = 0 and found that to

Informative print statements can help you to see and understand 
the program flow, especially if the problem is conceptual,  with
no *real*  errors in your "script"

def add(x, y):
    print 'P1:', x,y
    if x == 0:
    print 'P2:', y
    return y
    else:
    x -= 1
    y += 1
    print "P3:",x,y
    add(x, y)
    print "p4"
    print 'P5'
    #implied return is here, so I will add it 
    return # returns None **to the next level up**

print add(2, 4) 

>>> reload(addtest)
P1: 2 4
P3: 1 5
P1: 1 5
P3: 0 6
P1: 0 6
P2: 6
p4
P5
p4
P5
None
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Spambayes modifications with web services

2005-11-02 Thread Tim Williams (gmail)
On 02/11/05, Steve Holden <[EMAIL PROTECTED]> wrote:
> Personally I didn't regard the reply as unhelpful, and I believe the
> replier was honestly trying to get you to see that your rather naive
> suggestion was most unlikely to make things better.
>


To the OP

A tip for curing your own problem - remove your catchall.   Only allow
incoming email and bounces to valid in-use addresses - not to an
infinite number of unused addresses.   Repeat after me "Catchalls are
lazy !!! "   :)

Catchalls are a spammer's best friend and contribute greatly to the
internet's spam problem AND to the increasingly harsh attempts by ISPs
and other mail providers to reduce their load and spam throughput.
Not to mention the slow lingering death of services that provide a
catchall that can be forwarded.

You used a real domain name in your original post !! Anyone
marking your post as spam using your criteria would have blacklisted
that unfortunate domain.

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


Re: dictionary that have functions with arguments

2005-11-02 Thread Tim Williams (gmail)
On 1 Nov 2005 20:02:41 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> hi
> i have a dictionary defined as
>
> execfunc = { 'key1' : func1 }

##

def __HELLO(x=' '):
print 'HELLO',x

def __BYE(x=' '):
print 'BYE',x

def __PRINT(x=None, y=None):
print 'PRINT',x,y

cmds = { 'HELLO' : __HELLO,
   'BYE' : __BYE,
   'PRINT' : __PRINT,
   }

a = 'HELLO JOE'
b = a.split()

if cmds.has_key(b[0]):
cmds[b[0]](b[1])
# -> HELLO JOE

cmds[b[0]]()
# -> HELLO

cmds['BYE']('TOM')
# -> BYE TOM

cmds['PRINT']( 'TOM','JOE' )
# -> PRINT TOM JOE

cmds['PRINT']
# -> *No output - No exception

#

Inside  a class use

cmds = { 'HELLO' : self.__HELLO,  # etc

def __HELLO(self, x=' '): #etc


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


Re: do cc list from smtplib

2005-10-21 Thread Tim Williams (gmail)
On 21/10/05, Steve Holden <[EMAIL PROTECTED]> wrote:

>
> Assuming that TO and CC are single addresses it would be saner to use:
>

:)

Assuming that the envelope TOs (inc CCs) are the same as the
Header-TOs and Header-CCs

Actually,  I think this would be safer !

> def email(HOST,FROM,TO,CC, RECIPS, SUBJECT,BODY):
..
..
..
  server.sendmail(FROM,RECIPS,body)

RECIPS = list of SMTP recipients
TO & CC = Text representation of some/all/none of the SMTP recipients
and/or other text

RECIPS should be either a single address as a string *or* a list
containing 1 or more addresses
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do cc list from smtplib

2005-10-21 Thread Tim Williams (gmail)
On 21 Oct 2005 02:34:40 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]>
>
> def email(HOST,FROM,TO,CC,SUBJECT,BODY):
> import smtplib
> import string, sys

> body = string.join((
> "From: %s" % FROM,
> "To: %s" % TO,
> "CC: %s % CC,
> "Subject: %s" % SUBJECT,
> "",
> BODY), "\r\n")
>
> print body
>
> server = smtplib.SMTP(HOST)
> server.sendmail(FROM, [TO]+[CC],body)
> server.quit()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-10 Thread Tim Williams (gmail)
On 10 Oct 2005 13:31:51 -0700, dcrespo <[EMAIL PROTECTED]> wrote:
> Hi. I found TSL, a Python Library that supports SRP.
> Do you know where can I find a sample client and server code? Thanks
> for your help.

http://trevp.net/tlslite/

It comes with examples.   I use it in several servers and clients.   
Quite simple to impliment.

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


Re: socketServer questions

2005-10-08 Thread Tim Williams (gmail)
On 07/10/05, rbt <[EMAIL PROTECTED]> wrote:
> I have written a python socketServer program and I have a few questions

This is a multithreaded non-blocking version of your server (not
tested), with a basic attempt to hande errors.

from socket import *
from SocketServer import *
import  time, threading, sys

class tr_server(ThreadingMixIn, TCPServer):
def some_function(self):
pass

class tr_handler(StreamRequestHandler):
global write_to_file, file_path

def handle(self):
print "Current Connection count:", threading.activeCount() -1
public_ip = self.client_address[0]
serv_date = time.strftime('%Y-%m-%d', time.localtime())
serv_time = time.strftime('%H:%M:%S', time.localtime())

try:
data = self.rfile.readline(300)
data = str.strip(data)
bytes = str(len(data))
# Note that 'data; comes from the client.
fp = file('/home/rbt/Desktop/tr_report.txt', 'a')

fp.write(data+"\t"+serv_date+"\t"+serv_time+"\t"+public_ip+"\t"+bytes+"\n")
fp.close()
except:
print "unknown error", sys.exc_info()[0]

def StartServer():
setdefaulttimeout( 30  )  # timeout incoming connections
server = tr_server(('', 55503 ), tr_handler)
server.serve_forever()

if __name__ == '__main__':
StartServer()

Consider putting the writing to file function in its own class or
thread.  Then opening the file once and appending the data to it from
each connection. Yoou would need to use fp.flush() after each
fp.write()  so that the data survives a program fail.

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


Re: Help installing Python 2.3 on Win2K

2005-09-23 Thread Tim Williams (gmail)
On 23/09/05, D.S. Hein <[EMAIL PROTECTED]> wrote:

> I have tried various ways to set PYTHONPATH with the various directories
> where I have python programs (i.e. xx.py) but no matter how I set
> PYTHONPATH I keep getting a message that python can't open the python
> file. If I try to specify the full pathname by typing: python
> c:\Documents and Settings\-rest of path- I get an error message that
> python can't open c:\Documents.
>

add these directories to a text file called python.pth  in your
python23 directory in the format
d:\dir1\dir2

HTH :)



--

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


Re: mailing from with python

2005-09-20 Thread Tim Williams (gmail)
On 20/09/05, M.N.A.Smadi <[EMAIL PROTECTED]> wrote:
> hi;
> if i want to send a mail message using the "mail" client on a machine
> that has smtp protocol is there an easy way (i.e. like bash where you
> would just type mail -s SUBJECT message RECIPIENT) to do it from a
> python script?

Any mail client using SMTP will be outbound only,  you wouldn't be
able to send mail "through" the client using SMTP.

>From a post earlier today :)

s = smtplib.SMTP("server")
s.sendmail(fromaddress, toaddresess, msg)

You can send email directly to your local server (or direct to the
recipeint server) directly from your python "script"

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


Re: Question about smtplib, and mail servers in general.

2005-09-20 Thread Tim Williams (gmail)
On 20/09/05, Daniel Dittmar <[EMAIL PROTECTED]> wrote:
> Chris Dewin wrote:
> > Hi. I've been thinking about using smtplib to run a mailing list from my 
> > website.
> >
> > s = smtplib.SMTP("server")
> > s.sendmail(fromaddress, toaddresess, msg)

> >
> 
> Not really an answer to your question, but it's probably considered bad
> style to publish the email addresses of the recipients via the address
> list. Use a neutral To-address (best: the mailing list address) and add
> the recipients via bcc: headers.
> 

For clarity

The toaddreses don't show in the email,  they are the envelope TO:
addreses.   The addresses in the email's TO: Headers are shown to the
recipient and these are the ones that should be "disguised" as best
practice for mailing lists.

The email module's replace_header('to', 'new-text) will do the job for you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about smtplib, and mail servers in general.

2005-09-20 Thread Tim Williams (gmail)
On 20/09/05, Chris Dewin <[EMAIL PROTECTED]> wrote:
> 
> s = smtplib.SMTP("server")
> s.sendmail(fromaddress, toaddresess, msg)
> 
> I know that in this instance, the toaddresses variable can be a variable
> of type list.
> 
> Suppose the list contains well over 100 emails. Would that create some
> sort of drain on the mail server? Would I be better off doing it in some
> other way?

 
> Suppose the list contains well over 100 emails

You mean the list of recipients (toaddresses) ?  

The 2 lines of example code send a *single* email to "server" with
len(toaddresses) recipients.  The server will then split the email
into smaller (or individual) email groups to send (depending on the
server in use and the mechanisms it uses to relay  the email)

You could send a single email for each recipient to "server"

> s = smtplib.SMTP("server")
>for addr in toaddresses:
>  s.sendmail(fromaddress,[addr], msg)
# in later revisions, [addr] can be a list,  or a string of one address

but that would create much more load on your machine AND server

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


Re: how to build email message with attachment?

2005-07-26 Thread Tim Williams (gmail)
On 7/26/05, praba kar <[EMAIL PROTECTED]> wrote:
> Dear All,
> 
>Can any one let me know? How to build
> email in python? with some some examples.
> 
> regards
> Prabahar

The email module is what you need.
http://docs.python.org/lib/module-email.html

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


Re: dictionary that discards old items

2005-07-22 Thread Tim Williams (gmail)
On 7/21/05, Michael Hoffman <[EMAIL PROTECTED]> wrote:
> Will McGugan wrote:
> 
> > I need a collection class that behaves like a dictionary but when it
> > reaches 'n' items it discards the oldest item so that the length never
> > goes above 'n'. (Its for caching search results)
> >
> > I have a vague memory of a module that does this, but I cant remember
> > where I read about it. Can anyone enlighten me?
> 
> You want a Least Recently Used, or LRU, cache. Here's one:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524
> 

http://py.vaults.ca/apyllo.py/514463245.769244789.92554878
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: open a mail and...

2005-07-15 Thread Tim Williams (gmail)
On 7/15/05, Alberto Vera <[EMAIL PROTECTED]> wrote:
>
> Hello
>
> Is it possible to open a mail and download its files attached in a hard-disk
> using a python script?
>
> Regards
> --
> http://mail.python.org/mailman/listinfo/python-list
>

yes, use the email module.

>>> msg = email.message_from_file(an_opened_file)
or
>>> msg = email.message_from_string(a_mail_string)

then use:

For part in msg.walk():
   do_something(part)

The email docs will help you with converting and extracting the
specific attachements you are expecting

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


Date & time in a Zip File

2005-07-13 Thread Tim Williams (gmail)
Using zipfile.Zipfile

How can I add a file to a zip file and keep its date and time correct?
 Currently the date/time change to the time the file was added to the
zip.Zipinfo doesn't have a write method!

Solutions other than zipfile are welcome, with snippets if possible :)

ginmf in this instance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Tim Williams (gmail)
On 7/5/05, Guy Lateur <[EMAIL PROTECTED]> wrote:
> > I just tried this and it failed with IP addresses but not
> > hostnames/machine names,  try it again with the server name. :)
> 
> Nope, same problem. I think TJG might be right, and our server probably
> doesn't have IMAP running (yet).

Could you SMTP it back in ?   It would gain an extra Received: header
but the rest of the email would most likely be unaltered.

> > Depends how secure you need it to be.For my simple stuff I just do
> > something like this
> > [snip]
> 
> That's a nice thought, although the pw is still pretty visible. Maybe
> there's a way to encode/decode it using some sort of key (that only I know),
> that produces a truly unrecognisable pw?

Not my area of expertise I'm afraid.If you manually run the script
then you could use getpass() to prompt you for the password at run
time.

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


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Tim Williams (gmail)
On 7/5/05, Guy Lateur <[EMAIL PROTECTED]> wrote:
> Thanks for the suggestion, Tim. Unfortunately, I get a 'connection refused'
> error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error:
> (10061, 'Connection refused')". I've tried both the external IP adress and
> the internal one (10.0.0.2). I'm sure there's a way to get over this, isn't
> there?

I just tried this and it failed with IP addresses but not
hostnames/machine names,  try it again with the server name. :)
  
> One more question: can I avoid having (plain text) passwords in my code? I
> guess I could make a special account for this with a password known by
> everybody.

Depends how secure you need it to be.For my simple stuff I just do
something like this

In idle/pythonwin/interactive

>>> p = 'password_string'
>>> p = p.encode("utf16")
>>> p
'\xff\xfep\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00_\x00s\x00t\x00r\x00i\x00n\x00g\x00'

Then in the script
user = mylogin
pw = 
'\xff\xfep\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00_\x00s\x00t\x00r\x00i\x00n\x00g\x00'
M = imaplib.IMAP4(server)
M.login(mylogin,pw.decode("utf16")
('OK', ['LOGIN completed.'])

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


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-04 Thread Tim Williams (gmail)
On 7/4/05, Guy Lateur <[EMAIL PROTECTED]> wrote:
> 
> Anything else I could try?

Lateral thinking ?

=== untested ===

import imaplib, time, sys

f = open(msg_file)
r = f.readlines()
f.close()
msg1 = ''.join(r)
server = 'my.exchangeserver.com' # or IP address

user = 'user'
pw = 'pw'

M = imaplib.IMAP4(server)
M.sock.settimeout(120)
M.login(user,pw)[1][0]
M.select()
M.append('INBOX',None ,time.time() , msg1) # Inbox or other folder name
print "MESSAGE successfully saved"
#M.close()  Don't use close,  deletes/purges items
M.logout()[1][0]
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >