Re: my email

2012-08-01 Thread BJ Swope
I would also recommend changing your birthday as well ;)


--
The end of democracy and the defeat of the American Revolution will occur
when government falls into the hands of lending institutions and moneyed
incorporations.
-- Thomas Jefferson

The whole world is a comedy to those that think, a tragedy to those that
feel.  ---Horace Walpole





On Sat, Jul 21, 2012 at 6:36 AM, Maria Hanna Carmela Dionisio 
mmdionisio1...@yahoo.com.ph wrote:

 lolz sorry i already change it..just a newbhie, that's why :Dv
   --
 *From:* MRAB pyt...@mrabarnett.plus.com
 *To:* python-list@python.org
 *Sent:* Wednesday, July 18, 2012 10:08 AM
 *Subject:* Re: my email

 On 18/07/2012 02:44, Maria Hanna Carmela Dionisio wrote:
  mmdionisio1...@yahoo.com.ph
 
  Just a newbhie here :
 
 ...who has just revealed her password!

 [remainder snipped]
 --
 http://mail.python.org/mailman/listinfo/python-list



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


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


Re: Inconsistent SMTP/Gmail connection drop

2011-08-05 Thread BJ Swope
The best tool to debug this is tcpdump.

Running a packet capture whilst sending the mail will most likely shed the
most light on the subject.


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


Re: IMAP4_SSL, libgmail, GMail and corporate firewall/proxy

2011-02-16 Thread BJ Swope
Imap is not on port 443.  IIRC, it's late and I'm to lazy to even google it
right now, but it's port 143 isn't it.



On Wed, Feb 16, 2011 at 11:58 PM, Andrea Gavana andrea.gav...@gmail.comwrote:

 Hi All,

I apologize in advance if I'm going to write very stupid things,
 my expertise in http/socket/imap stuff is very close to zero. I'm
 using Python 2.6.5 on Windows XP SP3.

 I am trying to access my GMail account from my office, and it appears
 our company's firewall is blocking all SMTP/POP3/IMAP attempts or
 there is simply something I don't understand. My first try was to use
 imaplib as follows:


 import imaplib

 m = imaplib.IMAP4_SSL('imap.gmail.com', 443)
 m.login(username, password)


 And I get the following:


 Traceback (most recent call last):
  File D:\MyProjects\gmail.py, line 17, in module
m = imaplib.IMAP4_SSL('imap.gmail.com', 443)
  File C:\Python26\lib\imaplib.py, line 1138, in __init__
IMAP4.__init__(self, host, port)
  File C:\Python26\lib\imaplib.py, line 163, in __init__
self.open(host, port)
  File C:\Python26\lib\imaplib.py, line 1150, in open
self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  File C:\Python26\lib\ssl.py, line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
  File C:\Python26\lib\ssl.py, line 118, in __init__
self.do_handshake()
  File C:\Python26\lib\ssl.py, line 293, in do_handshake
self._sslobj.do_handshake()
 ssl.SSLError: [Errno 8] _ssl.c:480: EOF occurred in violation of protocol


 OK. Then I googled back and forth for a possible solution, and I got a
 hint that (maybe) the problem could be related to proxy
 authentication. And I tried this solution (which uses SocksiPy) I
 found on the web (username2 and password2 are the user name and
 password for our company's proxy):

 import socks
 import socket

 proxy_ip = 10.100.100.20   # Your proxy IP/DNS here

 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy_ip, 8080, True,
 username2, password2)
 socket.socket = socks.socksocket

 import imaplib

 m = imaplib.IMAP4_SSL('imap.gmail.com', 443)
 m.login(username, password)


 This solution just hangs forever at the line:

 m = imaplib.IMAP4_SSL('imap.gmail.com', 443)

 And it never returns (it never gets to the m.login() stuff).


 Then I tried with libgmail, giving it the option of setting the proxy
 name and port:

 import libgmail

 # Connect from behind a proxy www.myproxy.org:3128 using
 # proxy authentication user = 'john', password = 'proxy4321'
 libgmail.PROXY_URL = username2:password2@my_company_proxy:443'  #
 Define the proxy

 ga = libgmail.GmailAccount(username, password)
 ga.login()


 And I got this at first:

 Traceback (most recent call last):
  File D:\MyProjects\gmail2.py, line 8, in module
ga.login()
  File C:\Python26\lib\site-packages\libgmail.py, line 305, in login
pageData = self._retrievePage(req)
  File C:\Python26\lib\site-packages\libgmail.py, line 340, in
 _retrievePage
req = ClientCookie.Request(urlOrRequest)
  File C:\Python26\lib\site-packages\mechanize\_request.py, line 31,
 in __init__
if not _rfc3986.is_clean_uri(url):
  File C:\Python26\lib\site-packages\mechanize\_rfc3986.py, line 63,
 in is_clean_uri
return not bool(BAD_URI_CHARS_RE.search(uri))
 TypeError: expected string or buffer


 Then I brutally hacked into mechanize here and there and I was able to
 fix all non-internet related errors. And when I try the libgmail
 solution above now I get:

 Traceback (most recent call last):
  File D:\MyProjects\gmail2.py, line 8, in module
ga.login()
  File C:\Python26\lib\site-packages\libgmail.py, line 305, in login
pageData = self._retrievePage(req)
  File C:\Python26\lib\site-packages\libgmail.py, line 348, in
 _retrievePage
resp = self.opener.open(req)
  File C:\Python26\lib\site-packages\mechanize\_opener.py, line 193, in
 open
response = urlopen(self, req, data)
  File C:\Python26\lib\site-packages\mechanize\_urllib2_fork.py,
 line 344, in _open
'_open', req)
  File C:\Python26\lib\site-packages\mechanize\_urllib2_fork.py,
 line 332, in _call_chain
result = func(*args)
  File C:\Python26\lib\site-packages\mechanize\_urllib2_fork.py,
 line 1171, in https_open
return self.do_open(conn_factory, req)
  File C:\Python26\lib\site-packages\gmail_transport.py, line 145, in
 do_open
return ClientCookie.HTTPSHandler.do_open(self,
 ProxyHTTPSConnection.new_auth(self.proxy, self.proxy_user,
 self.proxy_passwd), req)
  File C:\Python26\lib\site-packages\mechanize\_urllib2_fork.py,
 line 1118, in do_open
raise URLError(err)
 urllib2.URLError: urlopen error Tunnel connection failed: 403
 Forbidden ( The ISA Server denied the specified Uniform Resource
 Locator (URL).  )


 Just in case, I have tried also with port 80, with similar results:

 Traceback (most recent call last):
  File D:\MyProjects\gmail2.py, line 8, in module
ga.login()
  File C:\Python26\lib\site-packages\libgmail.py, line 305, in login

Passing Variable(s) as kwargs

2010-12-06 Thread BJ Swope
Hello All.

I am trying to use values, retrieved from a config file, as kwargs and not
having any luck.  Well at least I think that's what I'm trying to do ;)

Any suggestions would be most appreciated.

Here's the exception:

Traceback (most recent call last):
  File c:\dev\LogServerMonitor\LogServerMonitor.py, line 246, in module
sched.add_cron_job(check_logging_db, minute = '*/run_interval_quantity')
  File c:\Python26\lib\site-packages\apscheduler\scheduler.py, line 249,
in add_cron_job
second)
  File c:\Python26\lib\site-packages\apscheduler\triggers.py, line 22, in
__init__
self._compile_expressions(minutes, 'minute')
  File c:\Python26\lib\site-packages\apscheduler\triggers.py, line 43, in
_compile_expressions
compiled_expr_list = [compile_single(expr) for expr in expr_list]
  File c:\Python26\lib\site-packages\apscheduler\triggers.py, line 36, in
compile_single
(expr, fieldname))
ValueError: Unrecognized expression */run_interval_quantity for field
minute



An example of what I am doing is:
##
Config File Contents:
[RunInterval]
#How often the application queries the DB to look for the date of
#the last entry (Default every 1 Minute).

#Valid RunInterval Quantities are integers  0
RunIntervalQuantity: 1

#Valid RunInterval Types are S=Seconds, M=Minutes, H=Hours, D=Days
RunIntervalType: M

##

My Code


config = ConfigParser.ConfigParser()
try:
config.readfp(open(config_file))
except:
sys.stderr.write('Config file, %s, is missing or unreadable. Exiting.'
% config_file)
sys.stderr.write('ERROR: %s\r\n' % str(err))
sys.exit(1)


def getOption(section, option):
try:
opt_value = config.get(section, option)
return opt_value
except (ConfigParser.NoOptionError), err:
sys.stderr.write( Application requires \%s\ be defined in the
[%s] section of the config file %s\r\n % (option, section, config_file))
sys.stderr.write('ERROR: %s\r\n' % str(err))
sys.exit(1)

def getOptionInt(section, option):
try:
opt_value = config.getint(section, option)
return opt_value
except (ValueError, ConfigParser.NoOptionError), err:
sys.stderr.write(Application requires \%s\ be defined as an
Integer in the \[%s]\ section of the config file %s % (option, section,
config_file))
sys.stderr.write('ERROR: %s\r\n' % str(err))
sys.exit(1)



# Start the scheduler
sched = Scheduler()
sched.start()
run_interval_quantity = getOptionInt('RunInterval', 'RunIntervalQuantity')
run_interval_type = getOption('RunInterval', 'RunIntervalType')

if run_interval_type in ['S', 's']:
sched.add_cron_job(check_logging_db, second = '*/run_interval_quantity')
elif run_interval_type in ['M', 'm']:
sched.add_cron_job(check_logging_db, minute = '*/run_interval_quantity')

elif run_interval_type in ['H', 'h']:
sched.add_cron_job(check_logging_db, hour = '*/run_interval_quantity')
elif run_interval_type in ['D', 'd']:
sched.add_cron_job(check_logging_db, day = '*/run_interval_quantity')
else:
my_logger.warning('The value of RunIntervalType in the configuration
file section RunInterval was not one of S, M, H or D. Running
LogServerMonitor application once per minute by default.')
sched.add_cron_job(check_logging_db, minute = '*')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing Variable(s) as kwargs

2010-12-06 Thread BJ Swope

 It's complaining that the 'minute' argument which you're passing to
 'add_cron_job' is '*/run_interval_quantity', which the scheduler
 doesn't understand.
 --


Hey, what do you know, there's a forest amongst all those trees...

key_words = '*/%d' % (run_interval_quantity)

sched.add_cron_job(check_logging_db, minute = key_words)

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


Python does not allow a variable named pass

2010-04-11 Thread BJ Swope
I am trying to automate access to a web page that has forms based
authentication.  The password field is named pass which python is
not going to like.

Other than asking the website owner to change the name of the field
how can I go about passing that field in the form post?

dev:~$ python
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2] on linux2
Type help, copyright, credits or license for more information.
 import urllib
 params = urllib.urlencode(dict(past='foo'))
 params = urllib.urlencode(dict(passs='foo'))
 params = urllib.urlencode(dict(pass='foo'))
  File stdin, line 1
params = urllib.urlencode(dict(pass='foo'))
  ^
SyntaxError: invalid syntax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not allow a variable named pass

2010-04-11 Thread BJ Swope
 urllib.urlencode({'pass' : 'foo'})
 'pass=foo'



 --- Giampaolo
 http://code.google.com/p/pyftpdlib
 http://code.google.com/p/psutil
 --
 http://mail.python.org/mailman/listinfo/python-list


Thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spam from gmail (Was: fascism)

2010-02-25 Thread BJ Swope

 If you like, but I tend to interpret meta- as idempotent. It's easier on
 my aspirin budget.

 --
 Robert Kern

And here I thought it was little blue pills for idempotentcy...




Life is a sexually transmitted disease with a 100% fatality rate. -- brazzy

Auburn fans are like slinkys... not really good for anything but they
still bring a smile to your face when you push them down a flight of
stairs.

To argue that honorable conduct is only required against an honorable
enemy degrades the Americans who must carry out the orders. -- Charles
Krulak, Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will
remain outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


TypeError Exception in email lib

2010-02-15 Thread BJ Swope
  File /usr/lib/python2.5/email/_parseaddr.py, line 142, in mktime_tz
if data[9] is None:
TypeError: 'NoneType' object is unsubscriptable

I'm parsing a bunch of spam and using the date field from the spams
for a date-time stamp.

I've fixed the lib on my box to place the call inside a try/except
clause to catch the exception now, but it seems the module has a bug
in it.

How would I go about recommending a change the module?

Original code:
def mktime_tz(data):
Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
if data[9] is None:
# No zone info, so localtime is better assumption than GMT
return time.mktime(data[:8] + (-1,))
else:
t = time.mktime(data[:8] + (0,))
return t - data[9] - time.timezone

Patched code:
def mktime_tz(data):
Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
try:
if data[9] is None:
# No zone info, so localtime is better assumption than GMT
return time.mktime(data[:8] + (-1,))
else:
t = time.mktime(data[:8] + (0,))
return t - data[9] - time.timezone
except TypeError:
return time.mktime(data[:8] + (-1,))



Auburn fans are like slinkys... not really good for anything but they
still bring a smile to your face when you push them down a flight of
stairs.

To argue that honorable conduct is only required against an honorable
enemy degrades the Americans who must carry out the orders. -- Charles
Krulak, Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will
remain outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError Exception in email lib

2010-02-15 Thread BJ Swope
On Mon, Feb 15, 2010 at 2:31 PM, Stephen Hansen apt.shan...@gmail.com wrote:
 On Mon, Feb 15, 2010 at 10:53 AM, BJ Swope bigbluesw...@gmail.com wrote:

  File /usr/lib/python2.5/email/_parseaddr.py, line 142, in mktime_tz
    if data[9] is None:
 TypeError: 'NoneType' object is unsubscriptable

 I'm parsing a bunch of spam and using the date field from the spams
 for a date-time stamp.

 I've fixed the lib on my box to place the call inside a try/except
 clause to catch the exception now, but it seems the module has a bug
 in it.

 While there may or may not be a bug in the library, I don't think its where
 you're fixing. Just because an exception occurs in a function doesn't mean
 that function is broken: its documented as accepting a 10 item tuple, only.
 Functions in the stdlib generally -should- throw exceptions on invalid
 input.
 Someone's passing None into it, which its not allowed to do. So -that's-
 where the bug probably is, I think. (Although it may not be the immediate of
 mktime_tz; it could be happening higher up on the stack)
 Advice: Always post complete tracebacks to c.p.l/python-list :)
 --S


From the module:

def mktime_tz(data):
Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
if data[9] is None:
   # No zone info, so localtime is better assumption than GMT
   return time.mktime(data[:8] + (-1,))
else:
t = time.mktime(data[:8] + (0,))
return t - data[9] - time.timezone


It appears that the module is trying to accommodate the potential
missing TZ data because poorly written emails are missing the TZ data.

I discarded all the crontab emails that had the full traceback in
them.  I took out the try/except clause in the hopes that I'll get
another exception soon.

If I do I'll post the entire exception traceback.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError Exception in email lib

2010-02-15 Thread BJ Swope
On Mon, Feb 15, 2010 at 2:47 PM, BJ Swope bigbluesw...@gmail.com wrote:
 On Mon, Feb 15, 2010 at 2:31 PM, Stephen Hansen apt.shan...@gmail.com wrote:
 On Mon, Feb 15, 2010 at 10:53 AM, BJ Swope bigbluesw...@gmail.com wrote:

  File /usr/lib/python2.5/email/_parseaddr.py, line 142, in mktime_tz
    if data[9] is None:
 TypeError: 'NoneType' object is unsubscriptable

 I'm parsing a bunch of spam and using the date field from the spams
 for a date-time stamp.

 I've fixed the lib on my box to place the call inside a try/except
 clause to catch the exception now, but it seems the module has a bug
 in it.

 While there may or may not be a bug in the library, I don't think its where
 you're fixing. Just because an exception occurs in a function doesn't mean
 that function is broken: its documented as accepting a 10 item tuple, only.
 Functions in the stdlib generally -should- throw exceptions on invalid
 input.
 Someone's passing None into it, which its not allowed to do. So -that's-
 where the bug probably is, I think. (Although it may not be the immediate of
 mktime_tz; it could be happening higher up on the stack)
 Advice: Always post complete tracebacks to c.p.l/python-list :)
 --S


 From the module:

 def mktime_tz(data):
    Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
    if data[9] is None:
       # No zone info, so localtime is better assumption than GMT
       return time.mktime(data[:8] + (-1,))
    else:
        t = time.mktime(data[:8] + (0,))
        return t - data[9] - time.timezone


 It appears that the module is trying to accommodate the potential
 missing TZ data because poorly written emails are missing the TZ data.

 I discarded all the crontab emails that had the full traceback in
 them.  I took out the try/except clause in the hopes that I'll get
 another exception soon.

 If I do I'll post the entire exception traceback.



Speak of the devil and demons appear...

 /logs/python/imap_fetcher/spam_serv1.bigbluenetworks.com.py

Parsing of emails for spam at serv1.bigbluenetworks.com failed.

Traceback (most recent call last):
  File /logs/python/imap_fetcher/spam_serv1.bigbluenetworks.com.py,
line 81, in module
clean_stale_mail()
  File /logs/python/imap_fetcher/spam_serv1.bigbluenetworks.com.py,
line 24, in clean_stale_mail
utc_msg_date = email.utils.mktime_tz(msg_date2)
  File /usr/lib/python2.5/email/_parseaddr.py, line 142, in mktime_tz
if data[9] is None:
TypeError: 'NoneType' object is unsubscriptable





def clean_stale_mail():
msg_date1= the_email.get('Date')
msg_date2 = email.utils.parsedate_tz(msg_date1)
try:
utc_msg_date = email.utils.mktime_tz(msg_date2)
except OverflowError:
M.store(msg_id, '+FLAGS.SILENT', '\\Deleted')
return
utc_stale_date = time.time() - (86000*stale_days)
if utc_msg_date = utc_stale_date:
M.store(msg_id, '+FLAGS.SILENT', '\\Deleted')


try:
#M = imaplib.IMAP4(HOST)
M = imaplib.IMAP4_SSL(HOST)
M.login(USER, PASSWD)
M.select(MAILBOX)

response, msg_list = M.search(None, 'ALL') # response is IMAP
response, msg_list is list of Message IDs

for msg_id in msg_list[0].split(): #msg_list[0] is a space
separated string of message ids
response, message = M.fetch(msg_id, '(RFC822)') # response is
the IMAP response, message is an RFC222 message

msg = email.FeedParser.FeedParser( )
msg.feed(message[0][1])
the_email = msg.close()

clean_stale_mail()

if the_email.is_multipart():
for part in the_email.walk():
if part.get_content_type() == 'text/html':
decoded_part = part.get_payload(decode=1)
soup_parse(decoded_part)
elif the_email.get_content_type() == 'text/html':
decoded_part = the_email.get_payload(decode=1)
soup_parse(decoded_part)
elif the_email.get_content_type() == 'text/plain':
msg_payload = the_email.get_payload()
manual_parse(msg_payload)
else:
continue
#print msg_id, Did't match any defined content types...
#print the_email
M.expunge()
M.close()
M.logout()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError Exception in email lib

2010-02-15 Thread BJ Swope
On Mon, Feb 15, 2010 at 3:42 PM, MRAB pyt...@mrabarnett.plus.com wrote:
 BJ Swope wrote:
 [snip]

 def clean_stale_mail():
    msg_date1= the_email.get('Date')

 What is the value of 'msg_date1' at this point?

    msg_date2 = email.utils.parsedate_tz(msg_date1)

 What is the value of 'msg_date2' at this point?

 The docs say that parsedate_tz() can return a 10-tuple or None.

 Presumably, if it can't parse the date then it returns None.


 [snip]


msg_date1:  @@DATE
msg_date2:  None

Thanks MRAB, Dave and Stephen!

The spam bot didn't populate the date field with anything remotely
resembling the date.  The @@DATE var was left in the Date header.

In reading the module I misunderstood what the if date[9] is None: was doing.

I'll wrap my calls in a try/except.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib retrlines timeout

2009-12-16 Thread BJ Swope
I've had experiences with some python mail servers that time out connections
if data from the socket is not sent to the application within the timeout
parameter.

I have seen a python app on FreeBSD that would timeout a connection after
600 seconds if freebsd did not receive at least 32 kb of data within the 600
second timeout.  FreeBSD would only send from the buffer to the app if there
was 32kb of data, unless TCP segments were received with the PUSH flag set
which would force a flush of the network buffer.

It sounds like this is the behavior Brendan is seeing.



Auburn fans are like slinkys... not really good for anything but they still
bring a smile to your face when you push them down a flight of stairs.

To argue that honorable conduct is only required against an honorable enemy
degrades the Americans who must carry out the orders. -- Charles Krulak,
Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay



On Wed, Dec 16, 2009 at 7:41 AM, Brendan brendandetra...@yahoo.com wrote:

 On Dec 15, 6:17 pm, Jennifer owenzhang.chic...@gmail.com wrote:
  I am writing a program that has a requirement for  a timeout of
  retrlines after the connection established. I just wonder if timeout
  of ftplib.FTP('.xxx.com',username,password,timeout) will work for
  retrlines method after the connection established. Or
  socket.setdefaulttimeout will work in this case. Please let me know.
 
  What exception will be throwed if ftp.retrlines timed out.
 
  Many Thanks!
 
  - Jennifer

 I asked a similar question on here a few days ago and got no response,
 however I tried a large download which timed out with the following:
 Traceback (most recent call last):
  File ./download_r1_neodf.py, line 167, in module
result = ftp.quit()
  File /usr/local/lib/python2.6/ftplib.py, line 566, in quit
resp = self.voidcmd('QUIT')
  File /usr/local/lib/python2.6/ftplib.py, line 248, in voidcmd
return self.voidresp()
  File /usr/local/lib/python2.6/ftplib.py, line 223, in voidresp
resp = self.getresp()
  File /usr/local/lib/python2.6/ftplib.py, line 209, in getresp
resp = self.getmultiline()
  File /usr/local/lib/python2.6/ftplib.py, line 195, in getmultiline
line = self.getline()
  File /usr/local/lib/python2.6/ftplib.py, line 182, in getline
line = self.file.readline()
  File /usr/local/lib/python2.6/socket.py, line 406, in readline
data = self._sock.recv(self._rbufsize)
 socket.error: [Errno 110] Connection timed out


 BTW, if you want to use the timeout paramter, you must also use the
 account parameter. Set it to ''.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: ftplib retrlines timeout

2009-12-16 Thread BJ Swope
If it works like I've seen other python based network apps that have app
timeouts, and Brandon's post seemed to indicate that his timed out during
the readline portion of the FTP transfer.



Auburn fans are like slinkys... not really good for anything but they still
bring a smile to your face when you push them down a flight of stairs.

To argue that honorable conduct is only required against an honorable enemy
degrades the Americans who must carry out the orders. -- Charles Krulak,
Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay



On Wed, Dec 16, 2009 at 5:01 PM, Jennifer owenzhang.chic...@gmail.comwrote:

 So you mean ftplib.FTP('.xxx.com',username,password,timeout) will
 timeout the retrlines as well, correct? Thanks.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Split string but ignore quotes

2009-09-29 Thread BJ Swope
Would the csv module be appropriate?

On 9/29/09, Scooter slbent...@gmail.com wrote:
 I'm attempting to reformat an apache log file that was written with a
 custom output format. I'm attempting to get it to w3c format using a
 python script. The problem I'm having is the field-to-field matching.
 In my python code I'm using split with spaces as my delimiter. But it
 fails when it reaches the user agent because that field itself
 contains spaces. But that user agent is enclosed with double quotes.
 So is there a way to split on a certain delimiter but not to split
 within quoted words.

 i.e. a line might look like

 2009-09-29 12:00:00 - GET / Mozilla/4.0 (compatible; MSIE 7.0;
 Windows NT 6.0; GTB5; SLCC1; .NET CLR 2.0.50727; Media Center PC
 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022) http://somehost.com 200
 1923 1360 31715 -
 --
 http://mail.python.org/mailman/listinfo/python-list



-- 
To argue that honorable conduct is only required against an honorable
enemy degrades the Americans who must carry out the orders. -- Charles
Krulak, Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will
remain outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic Form

2009-09-24 Thread BJ Swope
1. Did you try the headers for no-caching of the page?
2. If you wish to avoid dupes in a DB, Primary Keys are the tool to prevent
duplicates.


On Thu, Sep 24, 2009 at 11:01 AM, victorsubervi victorsube...@gmail.comwrote:

 in line...

 On Wed, Sep 23, 2009 at 9:13 PM, BJ Swope bigbluesw...@gmail.com wrote:

 What is your code not doing?


 see below


 Are you winding up with duplicate data in the DB?


 yes


 Is your web browser re-submitting the form with the same data if you
 refresh the screen?


 yes


 Is your web browser pre-filling the fields of the form due to caching?


 no

 If I must use cookies, do I want cookielib/cookiejar, or just Cookie?
 TIA.
 V


 I don't understand what's not working


 On Wed, Sep 23, 2009 at 12:40 PM, Victor Subervi victorsube...@gmail.com
  wrote:

 I've been trying the hidden field, but the problem is that when I set the
 variable flag, it stays in memory. I would rather just pass a var like I've
 been trying, but I don't think it's possible. Any ideas? Is a session cookie
 the only way? Here's more simplified code:

 #!/usr/bin/python

 import cgitb; cgitb.enable()
 import cgi
 import sys,os
 sys.path.append(os.getcwd())
 import MySQLdb
 import string, re

 def client():
   form = cgi.FieldStorage()
   client = string.replace(string.replace(form.getfirst('client', ''),
 ', '#39;'), '', '#34;')
   flag = form.getfirst('flag', '')
   print Content-Type: text/html
   print
   print 
 !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Frameset//EN 
 http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd;
 head xmlns=http://www.w3.org/1999/xhtml;
 body
 
   if flag == '':
 print 
 form method=post action=client.py
 Company Name: input type='text' value='' size='20' maxlength='100'
 name='client' /br /
 input type='hidden' name='flag' value='y' /
 div align='center'
   input type='submit' value=' Send ' /
 /div
 /form
 /body/html
 
   else:
 host = 'h'
 db = 'db'
 user = 'u'
 passwd = '1'
 database = MySQLdb.connect(host, user, passwd, db)
 cursor = database.cursor()
 cursor.execute('insert into companies (client);' % (client))
 cursor.close()
 print '/body/html'

 client()

 TIA,
 V


 On Tue, Sep 22, 2009 at 1:43 PM, Dennis Lee Bieber 
 wlfr...@ix.netcom.com wrote:

 On Tue, 22 Sep 2009 12:50:31 -0400, Victor Subervi
 victorsube...@gmail.com declaimed the following in
 gmane.comp.python.general:

  Well it's Web stuff, sure, but it's written in python :) The code
 follows.
  The problem is that I haven't figured out how to tell the program that
 the
  user has entered data and to clear the cache of that data so that it's
 not
  re-entered. How do I do that?

Remember, HTTP is a stateless protocol. EACH submission is
 considered a totally new transaction with no memory of the previous
 processing.

Possible solutions...

 *   Use a session cookie that identifies what phase in the multistep
 processing you are in...

 *   Use a hidden field in the form that defaults to, say False,
 when
 you first display the form, but then gets set to True during the first
 response process (and is then sent back out with True so the second
 response takes a different branch).

 --
Wulfraed Dennis Lee Bieber   KD6MOG
wlfr...@ix.netcom.com   
 HTTP://wlfraed.home.netcom.com/http://wlfraed.home.netcom.com/

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



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




  --
 To argue that honorable conduct is only required against an honorable
 enemy degrades the Americans who must carry out the orders. -- Charles
 Krulak, Former Commandant of the Marine Corps

 We are all slave to our own paradigm. -- Joshua Williams

 If the letters PhD appear after a person's name, that person will remain
 outdoors even after it's started raining. -- Jeff Kay


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





-- 
To argue that honorable conduct is only required against an honorable enemy
degrades the Americans who must carry out the orders. -- Charles Krulak,
Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic Form

2009-09-23 Thread BJ Swope
What is your code not doing?

Are you winding up with duplicate data in the DB?

Is your web browser re-submitting the form with the same data if you refresh
the screen?

Is your web browser pre-filling the fields of the form due to caching?

I don't understand what's not working

On Wed, Sep 23, 2009 at 12:40 PM, Victor Subervi victorsube...@gmail.comwrote:

 I've been trying the hidden field, but the problem is that when I set the
 variable flag, it stays in memory. I would rather just pass a var like I've
 been trying, but I don't think it's possible. Any ideas? Is a session cookie
 the only way? Here's more simplified code:

 #!/usr/bin/python

 import cgitb; cgitb.enable()
 import cgi
 import sys,os
 sys.path.append(os.getcwd())
 import MySQLdb
 import string, re

 def client():
   form = cgi.FieldStorage()
   client = string.replace(string.replace(form.getfirst('client', ''), ',
 '#39;'), '', '#34;')
   flag = form.getfirst('flag', '')
   print Content-Type: text/html
   print
   print 
 !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Frameset//EN 
 http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd;
 head xmlns=http://www.w3.org/1999/xhtml;
 body
 
   if flag == '':
 print 
 form method=post action=client.py
 Company Name: input type='text' value='' size='20' maxlength='100'
 name='client' /br /
 input type='hidden' name='flag' value='y' /
 div align='center'
   input type='submit' value=' Send ' /
 /div
 /form
 /body/html
 
   else:
 host = 'h'
 db = 'db'
 user = 'u'
 passwd = '1'
 database = MySQLdb.connect(host, user, passwd, db)
 cursor = database.cursor()
 cursor.execute('insert into companies (client);' % (client))
 cursor.close()
 print '/body/html'

 client()

 TIA,
 V


 On Tue, Sep 22, 2009 at 1:43 PM, Dennis Lee Bieber 
 wlfr...@ix.netcom.comwrote:

 On Tue, 22 Sep 2009 12:50:31 -0400, Victor Subervi
 victorsube...@gmail.com declaimed the following in
 gmane.comp.python.general:

  Well it's Web stuff, sure, but it's written in python :) The code
 follows.
  The problem is that I haven't figured out how to tell the program that
 the
  user has entered data and to clear the cache of that data so that it's
 not
  re-entered. How do I do that?

 Remember, HTTP is a stateless protocol. EACH submission is
 considered a totally new transaction with no memory of the previous
 processing.

Possible solutions...

 *   Use a session cookie that identifies what phase in the multistep
 processing you are in...

 *   Use a hidden field in the form that defaults to, say False, when
 you first display the form, but then gets set to True during the first
 response process (and is then sent back out with True so the second
 response takes a different branch).

 --
Wulfraed Dennis Lee Bieber   KD6MOG
wlfr...@ix.netcom.com   HTTP://wlfraed.home.netcom.com/

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



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




-- 
To argue that honorable conduct is only required against an honorable enemy
degrades the Americans who must carry out the orders. -- Charles Krulak,
Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic Form

2009-09-22 Thread BJ Swope
If you are trying to avoid the browser caching the pages so that they fetch
a new copy of the page every time, add the following 2 meta tags to the
header of the html page:

META HTTP-EQUIV=CACHE-CONTROL CONTENT=NO-CACHE
META HTTP-EQUIV=PRAGMA CONTENT=NO-CACHE

Those don't guarantee that the browser won't cache the page but it should
help the situation.

If on the other hand, you only want to populate each company's table with
the data from the form that is currently being submitted, you would run a
delete query on that company's table before you do the insert of the current
form's data.

I have some questions for you.

1. Why create a distinct table for each company?  Why not have a single
table called lets say, catalog.  Have company be just an additional field
in the catalog table.  This way you can avoid having to create distinct
tables every time somebody submits the form with a distinct company.

2.  Why do you use build your sql statements differently and call
cursor.execute() differently.  In the first sql declaration you are using a
static string then using the string substitution when you make the
cursor.execute() call.  In the second sql declaration you perform the string
substitiution and then make the cursor.execute() call with the resulting
variable.  Why not use the same technique in both places.

3.  And as a way to make the catalog item entry page easier on the eyes, why
not use tables to give a consistent spacing/alignment.

Replace the following:
  print 'hr /\n'
  print Category: input type='text' value='' size='20' maxlength='100'
name='cat%s' /br /\n % (str(i))
  print Item: input type='text' value='' size='20' maxlength='20'
name='item%s' /br /\n % (str(i))
  print Description: input type='text' value='' size='20'
maxlength='255' name='descr%s' /br /\n % (str(i))
  print UOM: input type='text' value='' size='20' maxlength='20'
name='uom%s' /br /\n % (str(i))
  print Price: input type='text' value='' size='10' maxlength='10'
name='price%s' /br /\n % (str(i))

With the following:
  print hr
  print table
  print trtdCategory/tdtdinput type='text' value='' size='20'
maxlength='100' name='cat%s' //td/tr % (str(i))
  print trtdItem/tdtdinput type='text' value='' size='20'
maxlength='20' name='item%s' //td/tr % (str(i))
  print trtdDescription/tdtdinput type='text' value=''
size='20' maxlength='255' name='descr%s' //td/tr % (str(i))
  print trtdUOM/tdtdinput type='text' value='' size='20'
maxlength='20' name='uom%s' //td/tr % (str(i))
  print trtdPrice/tdtdinput type='text' value='' size='10'
maxlength='10' name='price%s' //td/tr % (str(i))
  print /table

Makes the web page much easier to read.


-- 
To argue that honorable conduct is only required against an honorable enemy
degrades the Americans who must carry out the orders. -- Charles Krulak,
Former Commandant of the Marine Corps

We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay



On Tue, Sep 22, 2009 at 12:50 PM, Victor Subervi victorsube...@gmail.comwrote:

 Well it's Web stuff, sure, but it's written in python :) The code follows.
 The problem is that I haven't figured out how to tell the program that the
 user has entered data and to clear the cache of that data so that it's not
 re-entered. How do I do that?
 TIA,
 Victor

 snip

 sql = 'Category varchar(100), Item varchar(20), Description
 varchar(255), UOM varchar(20), Price float(7,2)'
 cursor.execute('create table if not exists %s (%s);' % (company, sql))

 snip

   sql = 'insert into %s (Category, Item, Description, UOM, Price)
 values (%s, %s, %s, %s, %s);' % (company, cat, item, descr, uom,
 price)
   cursor.execute(sql)

 snip

 i = 0
 while i  num:
   print 'hr /\n'
   print Category: input type='text' value='' size='20'
 maxlength='100' name='cat%s' /br /\n % (str(i))
   print Item: input type='text' value='' size='20' maxlength='20'
 name='item%s' /br /\n % (str(i))
   print Description: input type='text' value='' size='20'
 maxlength='255' name='descr%s' /br /\n % (str(i))
   print UOM: input type='text' value='' size='20' maxlength='20'
 name='uom%s' /br /\n % (str(i))
   print Price: input type='text' value='' size='10' maxlength='10'
 name='price%s' /br /\n % (str(i))



 On Tue, Sep 22, 2009 at 11:34 AM, Simon Forman sajmik...@gmail.comwrote:

 On Tue, Sep 22, 2009 at 10:46 AM, Victor Subervi
 victorsube...@gmail.com wrote:
  Hi;
  I have a dynamic form in which I do the following:
  1) Request two fields (company name, number of entries). That is sent
 back
  to the form.
  2) If the two fields are not None, the form requests other data. That,
 too,
  is sent back to the form.
  3) That new data is then entered into a MySQL table.
  The problem is, that when I go back to refresh the form, the data is
  re-entered into the 

Re: Why does this group have so much spam?

2009-09-04 Thread BJ Swope
And I would kindly appreciate it if you fellas wouldn't go solving
this little spam problem!  Selling Anti-Spam industry leading
appliances has managed to put me in a rather nice house and I'd hate
to lose it just because you fellas went and solved the problem! ;)



On Thu, Sep 3, 2009 at 11:24 PM, rrt8...@gmail.com wrote:

 *ahem*! You guy's do remember this thread (?at one time in history?)
 was about spam on this list, right? Not internet connection fees. ;-)
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will
remain outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get Exif data from a jpeg file

2009-05-18 Thread BJ Swope
On Sun, May 17, 2009 at 4:17 AM, Arnaud Delobelle
arno...@googlemail.com wrote:

 Daniel Fetchinson fetchin...@googlemail.com writes:

  I need to get the creation date from a jpeg file in Python.  Googling
  brought up a several references to apparently defunct modules.  The best
  way I have been able to find so far is something like this:
 
  from PIL import Image
  img = Image.open('img.jpg')
  exif_data = img._getexif()
  creation_date = exif_data[36867]
 
  Where 36867 is the exif tag for the creation date data (which I found by
  ooking at PIL.ExifTags.TAGS).  But this doesn't even seem to be
  documented in the PIL docs.  Is there a more natural way to do this?
 
 
  Have you tried http://sourceforge.net/projects/exif-py/ ?
 
  HTH,
  Daniel

 I will have a look - thank you.

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


I use the EXIF module to do bulk renames of all the pictures in a directory.

Here's my hackeration...



import sys
import os
import re
import time
import win32file
import datetime
import EXIF

DATE_FORMAT   = '%Y%m%d_%H%M%S'
allowed_files = ['.asf', '.jpg', '.mod', '.mov', '.mpeg', '.mpg',
'.jpeg', '.png', '.tiff', '.tif']
named_files = []

r = re.compile('.mod',)

def is_a_file(path, file, xtn):
    
    We only want to rename the files right?
    Return True or False depending on whether object is a file or a directory
    

    if os.path.isdir(os.path.join(path,file)):
    print This is a directory not a file.  Will not rename!
    return False
    if allowed_files.count(xtn):
    return True
    else:
    print file, is not a in the list of allowed extensions. Will
not rename!
    return False


def renameFile(path, file):
     Rename old_filename with the using the date/time created or
modified for the new file name

    old_filename = os.path.join(path,file)

    (name,xtn) = os.path.splitext(file)
    xtn = xtn.lower()

    if re.search(r, xtn):
    xtn_old = xtn
    xtn = '.mpg'
    print xtn_old, 'changed to', xtn

    if is_a_file(path, file, xtn):
    created_time = os.path.getctime(old_filename)
    modify_time = os.path.getmtime(old_filename)

    f = open(old_filename, 'rb')
    try:
    tags=EXIF.process_file(f)
    except UnboundLocalError:
    print No EXIF data available for , file
    tags = {}
    exif_time = 0
    try:
    tags['EXIF DateTimeOriginal']
    exif_time = str(tags['EXIF DateTimeOriginal'])
    exif_time = int(time.mktime(time.strptime(exif_time,
%Y:%m:%d %H:%M:%S)))
    except (KeyError,ValueError):
    print 'No EXIF DateTimeOriginal for ', file
    exif_time = 0
    f.close()

    if created_time  modify_time:
    local_time = time.localtime(created_time)
    else:
    local_time = time.localtime(modify_time)

    if exif_time:
    if exif_time  local_time:
    local_time = time.localtime(exif_time)

    date_time_name = time.strftime(DATE_FORMAT, local_time)

    copy_number = named_files.count(date_time_name)
    named_files.append(date_time_name)

    new_name = date_time_name + _ + str(copy_number) + xtn

    new_filename = os.path.join(path, new_name)

    print 'Renaming:', old_filename, 'to', new_filename
    #print 'Created Time  = ', created_time
    #print 'Modified Time = ', modify_time
    #print 'EXIF Time = ', exif_time
    #print 'Time Used = ', local_time
    os.rename(old_filename, new_filename)


if __name__ == '__main__':
    if os.path.isdir(sys.argv[1]):
    Recursively walk the directory listed as Arg 1 and work each file.
    print
    for path,dirs,files in os.walk(sys.argv[1]):
    for file in files:
    renameFile(path, file)
    else:
    print \nNo path to rename specified.\n
    print Usage:\n\tpython, sys.argv[0], path to directory of
source files
    sys.exit(1)




--
We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will
remain outdoors even after it's started raining. -- Jeff Kay

Fascism is a term used to describe authoritarian nationalist political
ideologies or mass movements that are concerned with notions of
cultural decline or decadence and seek to achieve a millenarian
national rebirth by exalting the nation or race, and promoting cults
of unity, strength and purity. - Wikipedia

The story of postwar American conservatism is best understood as a
continual replay of a single long-standing debate. On one side are
those who have upheld the Burkean ideal of replenishing civil society
by adjusting to changing conditions. On the other are those committed
to a revanchist counterrevolution, the restoration of America's
pre-welfare state ancien regime. And, time and again, the
counterrevolutionaries have won. The result is that modern American

Re: smtplib problem with newly rebuilt Debian/lenny system

2009-03-30 Thread BJ Swope
try
 s=smtplib.SMTP('127.0.0.1')

instead.  I'm guessing that it's trying to bind to the IPv6 or some other
non IPv4 localhost instance.

On Wed, Mar 18, 2009 at 11:25 AM, cassiope f...@u.washington.edu wrote:

 A hard drive failure forced me to rebuild my main system.  Just a few
 things haven't been restored; one of them is a python script which is
 used to email users of important events.

 In attempting to diagnose the cause, I tried directly executing the
 lines inside the python2.5 interpreter:

import  smtplib
s= smtplib.SMTP('localhost')

 but the second line causes  a traceback:

File stdin, line 1, in module
File /usr/lib/python2.5/smtplib.py, line 244, in __init__
(code, msg) = self.connect(host, port)
File /usr/lib/python2.5/smtplib.py, line 310, in connect
raise socket.error, msg
socket.error: (97, 'Address family not supported by protocol')

 This is with exim4 and python2.5 on a newly installed lenny system.
 No error messages appear in /var/log or /var/log/exim4 directories.

 Helpful clues or pointers to relevant documentation would be
 appreciated!

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




-- 
We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay

Fascism is a term used to describe authoritarian nationalist political
ideologies or mass movements that are concerned with notions of cultural
decline or decadence and seek to achieve a millenarian national rebirth by
exalting the nation or race, and promoting cults of unity, strength and
purity. - Wikipedia

The story of postwar American conservatism is best understood as a continual
replay of a single long-standing debate. On one side are those who have
upheld the Burkean ideal of replenishing civil society by adjusting to
changing conditions. On the other are those committed to a revanchist
counterrevolution, the restoration of America's pre-welfare state ancien
regime. And, time and again, the counterrevolutionaries have won. The result
is that modern American conservatism has dedicated itself not to fortifying
and replenishing civil society but rather to weakening it through a politics
of civil warfare. -- Sam Tanenhaus
--
http://mail.python.org/mailman/listinfo/python-list


Re: Obtaining SMTP address of a sender and receiver of an outlook mail

2008-12-03 Thread BJ Swope
If you have access to the AD server that hosts those DNs you can use
python's ldap module to retrieve the smtp attribute for the DN you've just
parsed from the message.

On Wed, Dec 3, 2008 at 2:06 AM, [EMAIL PROTECTED] 
[EMAIL PROTECTED] wrote:

 Hi all,
   I am trying to use python for extracting contents of an outlook
 email. For extracting the list of Recipients addresses I tried using
 the MAPI.message.Recipients.Address property, but the problem I am
 facing is that it is giving the complete DN name which is putting me
 in further complications. Is there any way to obtain the actual SMTP
 mail address ([EMAIL PROTECTED]) from the above object? I searched
 for it in the MSDN help but couldn't succeed.

 Thanks in advance,
 Venu
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay

Fascism is a term used to describe authoritarian nationalist political
ideologies or mass movements that are concerned with notions of cultural
decline or decadence and seek to achieve a millenarian national rebirth by
exalting the nation or race, and promoting cults of unity, strength and
purity. - Wikipedia
--
http://mail.python.org/mailman/listinfo/python-list


Re: Open a List of Files

2008-01-08 Thread BJ Swope
On Jan 8, 2008 6:03 AM, Fredrik Lundh [EMAIL PROTECTED] wrote:

 BJ Swope wrote:

  given a list such as
 
  ['messages', 'recipients', 'viruses']
 
  how would I iterate over the list and use the values as variables and
  open the variable names a files?
 
  I tried
 
  for outfile in ['messages', 'recipients', 'viruses']:
  filename = os.path.join(Host_Path, outfile)
  outfile = open(filename, 'w')
 
  But it's not working.

 the code looks ok.  please define not working.

 /F

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


Yep, defining not working is always helpful! :)

I want to have all 3 files open at the same time.  I will write to each of
the files later in my script but just the last file is open for writing.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Open a List of Files

2008-01-08 Thread BJ Swope
On Jan 8, 2008 7:22 AM, Hrvoje Niksic [EMAIL PROTECTED] wrote:

 Fredrik Lundh [EMAIL PROTECTED] writes:

  BJ Swope wrote:
 
  the code looks ok.  please define not working.
 
  Yep, defining not working is always helpful! :)
 
  I want to have all 3 files open at the same time.  I will write to
  each of the files later in my script but just the last file is open
  for writing.
 
  to keep more than one file open, you need more than one variable, or a
  variable that can hold more than one object.
 
  if the number of files may vary, put the file objects in a list.

 Or in a dict:

 open_files = {}
 for fn in ['messages', 'recipients', 'viruses']:
open_files[fn] = open(getfilename(fn), 'w')

 # open_files['messages'] is the open file 'messages' etc.
 --
 http://mail.python.org/mailman/listinfo/python-list


I decided that I was just trying to be too smooth by 1/2 so I fell back to
...


messages = open(os.path.join(host_path,'messages.txt'), 'wb')
deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb')
actions = open(os.path.join(host_path,'actions.txt'), 'wb')
parts = open(os.path.join(host_path,'parts.txt'), 'wb')
recipients = open(os.path.join(host_path,'recipients.txt'), 'wb')
viruses = open(os.path.join(host_path,'viruses.txt'), 'wb')
esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb')


Thank you to everybody who answered.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Open a List of Files

2008-01-08 Thread BJ Swope
On Jan 8, 2008 9:34 PM, Terry Jones [EMAIL PROTECTED] wrote:


 I think you should revisit this decision.  Something like Fredrik's code
 is
 the way to go.  It has multiple advantages:

  - It's much shorter.
  - It's arguably easier to add/remove to/from.
  - It has less risk of error (much less repetition).
  - It allows your code to later take a string file tag and
   write to that file by looking up its file descriptor in the dict.
  - You can close all open files with a trivial loop.

 Also, if you start writing code like Fredrik's instead of like what you
 fell back on you'll make yourself a better programmer (in general, not
 just
 in Python).

 Terry



Thanks for the advice Terry.  With your prompting I went back and looked at
the examples and sought to understand them.

The results are...

#File Creations/Openings
def getfilename(host_path, fn):
return os.path.join(host_path, '%s.txt' % fn)

outfiles_list = ['messages', 'deliveries', 'actions', 'parts', 'recipients',
'viruses', 'esp_scores']
open_files = {}
for fn in outfiles_list:
open_files[fn] = open(getfilename(host_path, fn), 'wb')


#Referring to files to write in various places...
open_files['deliveries'].write(flat_line)
open_files['deliveries'].write('\n')


#And finally to close the opened files
for fn in open_files.keys():
open_files[fn].close()


I sure am glad I posted this to the list.  It is exactly the kind of stuff I
was hoping to find.

Again, to all who answered, Thank You!


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

Open a List of Files

2008-01-07 Thread BJ Swope
given a list such as

['messages', 'recipients', 'viruses']

how would I iterate over the list and use the values as variables and open
the variable names a files?

I tried

for outfile in ['messages', 'recipients', 'viruses']:
filename = os.path.join(Host_Path, outfile)
outfile = open(filename, 'w')


But it's not working.



-- 
We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will remain
outdoors even after it's started raining. -- Jeff Kay
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: smtplib starttls gmail example - comments?

2007-01-24 Thread BJ Swope

On 1/24/07, Tim Williams [EMAIL PROTECTED] wrote:


On 24/01/07, py [EMAIL PROTECTED] wrote:
 I would love for anybody to comment on this code with regard to
redundancy/efficiency/wordiness or whatever else.
 for instance, do i understand correctly that i cant have a try: else:
without an intervening except:?
 -dave

 stdout.write(calling smtp server...)
 try:
 server = SMTP(msgsmtp)
 except:
 stdout.write(FAIL.)   #using .write to avoid the implied
\n with print
 else:
 server.set_debuglevel(msgdebug)
 stdout.write(starting tls...)
 server.ehlo(msgfrom)
 try:server.starttls()
 except: stdout.write(FAIL.)
 else:
 server.ehlo(msgfrom)   #neessary duplication (?)
 stdout.write(logging in...)
 try:server.login(msgfrom, msgpass)
 except: stdout.write(FAIL.)
 else:
 stdout.write(sending...)
 try:server.sendmail(msgfrom, msgto, msgtxt +
\n.\n)
 except: stdout.write(FAIL.)
 else:
 try:
 server.quit()
 except sslerror:  # a known and largely
ignored issue with early EOF in ssl protocol
 stdout.write(success.)
 else:
 stdout.write(success.)
 --


*** Not tested  but should have the same functionality and error
handling as your script ***

this_host = 'myhostname.mydom1.com'
print calling smtp server..., #  the trailing comma removes '\n'
try:
server = smtplib.SMTP(msgsmtp,local_hostname=this_host)
server.set_debuglevel(msgdebug)
print starting tls...,
server.starttls()
server.ehlo(this_host)  # RFC requirement for 2nd EHLO after
requesting TLS
print logging in...,
server.login(msgfrom, msgpass)
print sending...,
failed = server.sendmail(msgfrom, msgto, msgtxt + \n.\n)
try:
server.quit()
except: pass
print success.
except:
print FAIL.,

if failed:
print failed:, failed  # some recipients, but not all of them,
failed
--
http://mail.python.org/mailman/listinfo/python-list





Both examples have included the cardinal sin in smtp...

They both send the message text followed by new line dot new line.

The smtp protocol specifically mentions CRLF dot CRLF.   Please please
please use \r\n.\r\n in your code...

--
We are all slave to our own paradigm. -- Joshua Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: smtplib starttls gmail example - comments?

2007-01-24 Thread BJ Swope

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

Re: Monitoring number of smtp bytes sent through python e-mail socket

2006-12-05 Thread BJ Swope

BTW, I noticed a bunch of new line characters in your test message.

If you ever send mail to a qmail server it will be rejected because rfc 821
says that new line characters cannot occur without a carriage return.  So
change all those \n's to \r\n's ;)
--
We are all slave to our own paradigm. -- Joshua Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Slicing Issues

2006-05-21 Thread BJ Swope
Given this set of data (88 characters wide) in a file...


067AARON
WAY
3004300252599A
098 067017 129 672
067ABBA
CT
30518000882000902A 025
11 0670163227 365 670
067ABBEY HILL
RD
3002400010299A 004
12 067027 276 667
067ABBEY
LN
SW3004700495099A
052 067036 093 659
067ABBEY PARK
WAY
30044000901000967A
043 0670161916 177 622
067ABBEY POINTE
WAY
30024000103000176A 100
12 0670178087 235 667
067ABBIE KILGORE
WAY
30052001314001487A
041 0670155595 096 649
067ABBOTT
DR
30519002103002236A
129 0670176283 007 682
067ABBOTTS BRIDGE
RD
30096003550003578E 096
04 0670128036 293 697
067ABBOTTS BRIDGE
RD
30096003551003935O 056
04 0670128046 293 697

and this code...
dafile = 'gwinnett_streets_short.txt'
f = open(dafile, 'r')
for line in f:
 line=line.strip('\r\n')
 county_code=line[0:3]
 street_name=line[3:30]
 district_combo=line[85:3]
 print county_code, '|' , street_name , '|' , district_combo , '|' , len(line), '|'


I get this output...
067 | AARON
WAY
| | 88 |
067 | ABBA
CT
| | 88 |
067 | ABBEY HILL RD | | 88 |
067 | ABBEY
LN
| | 88 |
067 | ABBEY PARK WAY | | 88 |
067 | ABBEY POINTE WAY | | 88 |
067 | ABBIE KILGORE WAY | | 88 |
067 | ABBOTT
DR
| | 88 |
067 | ABBOTTS BRIDGE RD | | 88 |
067 | ABBOTTS BRIDGE RD | | 88 |

If I change the slice for district_combo to 
 district_combo=line[85:]

The output is what I want...

067 | AARON
WAY
| 672 | 88 |
067 | ABBA
CT
| 670 | 88 |
067 | ABBEY HILL RD | 667 | 88 |
067 | ABBEY
LN
| 659 | 88 |
067 | ABBEY PARK WAY | 622 | 88 |
067 | ABBEY POINTE WAY | 667 | 88 |
067 | ABBIE KILGORE WAY | 649 | 88 |
067 | ABBOTT
DR
| 682 | 88 |
067 | ABBOTTS BRIDGE RD | 697 | 88 |
067 | ABBOTTS BRIDGE RD | 697 | 88 |


Why does the final slice have to be an open slice? Why can the
slice not be like the previous slices in which it is a specified range
of characters?

-- We are all slave to our own paradigm. -- Joshua Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Slicing Issues

2006-05-21 Thread BJ Swope
On 5/21/06, Heiko Wundram [EMAIL PROTECTED] wrote:
Am Sonntag 21 Mai 2006 22:52 schrieb BJ Swope: district_combo=line[85:3]This returns the slice from character 85 to character 3 in the string, readforwards. Basically, as Python slices are forgiving (because the borders are
actually illogical), this amounts to nothing, but could also amountto: your indexing boundaries are invalid.Basically, what you want is:district_combo = line[85:88]where 88 = 85 + 3 (3 being the length). Read up on Python slices...
--- Heiko.--http://mail.python.org/mailman/listinfo/python-listHeiko,


Thank you. I was thinking like mysql for the indexs.
Thinking start at 85 and go for 3 characters instead of like python
start at x and go up to and including y.

The pages I had googled showed examples that were less than clear ;)

BJ-- We are all slave to our own paradigm. -- Joshua Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Problem with FTPLib and incomplete files on some downloads

2006-01-20 Thread BJ Swope
Just guessing but are the files binary yet you are downloading them without declaring binary?On 1/16/06, Peter A.Schott 
[EMAIL PROTECTED] wrote:I download a lot of 4-6 KB files and regularly run into issues with files that
don't get downloaded all the way or otherwise get corrupt.I do something like:RemoteList = nlstdir()for filename in RemoteList:LocalFile = open(filename, wb)LocalFile.write( get file code here )
LocalFile.close()#ftplib call to delete the remote fileI've tried to insert a pause into the code between the close and the remotedelete, but that doesn't seem to help.For some reason it doesn't seem like the
buffer is completely written or read before the remote delete is called.Thatleads to a file that's not 100% complete and thus can't be decrypted.Any ideas on what to look for?I don't have my exact code handy at the moment
or I'd post some actual snippets.It's also not consistent or it would be awhole lot easier to troubleshoot.:-)Running Python 2.4.2 on Win32.Thanks.-Pete Schott--
http://mail.python.org/mailman/listinfo/python-list-- But
we also know the dangers of a religion that severs its links with
reason and becomes prey to fundamentalism --Cardinal Paul
PoupardIt morphs into the Republican party!-- BJ
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python CGI

2005-12-01 Thread BJ Swope
Here's a snippet of code I use in a CGI I use...

I check to see if the params has any data, if it does then return that
data and some other data that comes from the params. If params is
empty, then draw a different page that says give me some data.

 if len(params):
 return params,inc_fields
 else:
 generate_form()
 sys.exit(1)


def generate_form():
 html_stuff.print_headers('Error','FF')
 print Need some information for which to search...\n\nbrbr\n
 html_stuff.form_open('search.cgi')
 html_stuff.submit_button('Try Again')
 print 'bra href="" New User/abr'
 html_stuff.form_close()
 html_stuff.print_footers()
On 30 Nov 2005 20:52:01 -0800, jbrewer [EMAIL PROTECTED] wrote:
I need to update a CGI script I have been working on to performvalidation of input files.The basic idea is this:1.) HTML page is served2.) User posts file and some other info3.) Check file for necessary data
* If data is missing, then post a 2nd page requesting needed data* If data is present, continue to 44.) Process input file and display results (processing path depends onwhether data from 3 was present in file or had to be input by user)
I'm unsure of the best way to implement step 3.Is it even possible toput all of this into one script?Or should I have one script check thefile for the data, then pass the info on to a 2nd script?The
cgi.FieldStorage() function should only be called once, so it seemslike it's not possible to read a form and then repost another one andread it.If this is true and I need 2 scripts, how do I pass on theinformation in step 3 automatically if the file has the proper data and
no user input is needed?Sorry if this is a dumb question (or unclear), but this is my(ever-growing) first CGI script.Thanks.Jeremy--
http://mail.python.org/mailman/listinfo/python-list-- But
we also know the dangers of a religion that severs its links with
reason and becomes prey to fundamentalism --Cardinal Paul
PoupardIt morphs into the Republican party!-- BJ
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pywin32: How to import data into Excel?

2005-11-08 Thread BJ Swope
On 11/8/05, Dmytro Lesnyak [EMAIL PROTECTED] wrote:





Hello,


I need to import some big 
data into Excel from my Python 
script. I have TXT file (~7,5 Mb). I'm using Pywin32 library for that, but if I 
first try to read the TXT file and then save the values one by one 
like


I have to question the reasoning behind using Excel. That much
data seems like it would be troublesome to manage in Excel. How
good is Excel at working with that much data?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Vim capable IDE?

2005-10-18 Thread BJ Swope
On 18 Oct 2005 07:16:11 -0700, Chris Lasher [EMAIL PROTECTED] wrote:
A marriage of the twowould seem like the best of both worlds.Chris
The pessimists would say the worst of both worlds ;)

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

Re: Jargons of Info Tech industry

2005-08-25 Thread BJ Swope
So says Chris from his webmail account...

On 8/25/05, Chris Head [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 [EMAIL PROTECTED] wrote:
 [snip]
  ... and generally these web based message boards (i.e. forums I
  assume you mean) have none of the useful tools that Usenet offers and
  are much, much slower.
 [snip]
 
 Arrgh, I *emphatically* *hate* Web-based-(almost anything). Why, oh WHY,
 would we subject ourselves to Web-based message boards and Webmail
 services? When using a proper e-mail client, your bandwidth usage
 consists of downloading your e-mail. When using a Webmail service, your
 bandwidth usage consists of downloading the message, PLUS the entire
 user interface. Additionally, a user interface operating inside an HTML
 renderer can NEVER be as fast as a native-code user interface with only
 the e-mail message itself passed through the renderer. I mean, the way
 Webmail works, you're at the message list and click on a message to
 view. This causes a whole new page, user-interface and all, to be
 loaded. In comparison, that's like shutting down and re-opening your
 e-mail program for every single message you want to view!
 
 Why can't we use the Web for what it was meant for: viewing hypertext
 pages? Why must we turn it into a wrapper around every application
 imaginable?
 
 ...
 
 /rant
 
 Chris
 -BEGIN PGP SIGNATURE-
 Version: GnuPG v1.2.1 (MingW32)
 
 iD8DBQFDDoRR6ZGQ8LKA8nwRAvinAKCVi3Sfztpm3ILUk7TnunPJxBEVzwCguvAu
 ME8mWt2eVNpPUckJ3NT39KY=
 =TdTk
 -END PGP SIGNATURE-
 --
 http://mail.python.org/mailman/listinfo/python-list

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