Re: MySQLdb insert HTML code error

2012-12-10 Thread Anatoli Hristov
>
>First thing -- DON'T put quotes around the %s place-holders... The
> whole purpose of using the parameterized .execute() is to let the
> database adapter properly escape the parameters before putting them into
> the SQL (since MySQL didn't have prepared statements before v5, it was
> producing full SQL statements for each insert, even with .executemany()
> )

Thank you, this solved my problem.:)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with usbtmc-communication

2012-12-10 Thread Jean Dubois
On 10 dec, 16:34, w...@mac.com wrote:
> On Dec 10, 2012, at 8:31 AM, Jean Dubois  wrote:
>
> [byte]
>
>
>
>
>
>
>
>
>
> > As you can see this approach suffers from the same "buffer problem" as
> > the approach with readline did. One now good argue as a workaround:
> > get rid of the first data pair and add an extra measure command for
> > the missing data pair, however this still does not explain why this
> > problem is there in Python and not in Octave and I also fear I'll get
> > more trouble when sending combined commands e.g. such as that to
> > create a staircase current
> > So my question is, how to modify the Python-code such that the first
> > data pair is indeed the first data pair
>
> > thanks,
> > jean
>
> > Here follows the new code:
> > #!/usr/bin/python
> > import time
> > import os
> > import sys
> > measurementcurr=''
> > measurementvolt=''
> > timesleepdefault=5
> > print "Enter a numofchar (11 = > numofchar = int(raw_input())
> > filename ='mydata.txt'
> > usbkeith = open('/dev/usbtmc1','r+')
> > usbkeith.flush()
> > usbkeith.write("*IDN?\n")
>
> It seems like a real leap of faith to be opening /dev/usbtmc1 as though it 
> were a file-oriented device.  I've never heard of ANY instrument interface 
> implemented this way.
> Where did you see example code that did that.
I found examples in the usbtmc kernel driver documentation (the
examples there are given in C):
http://www.home.agilent.com/upload/cmc_upload/All/usbtmc.htm?&cc=BE&lc=dut


>  Have you tried to access /dev/usbtmc1 as though it were a serial device?
Yes, I did, as I used to do when communicating with rs232 devices. I
first tried to communicate to with the Keithley using cutecom but I
soon discovered you can't work that way because as soon as you open
the device it closes immediately thereafter. You really have to use
usbtmc (unfortunately) I'm missing the correct "flushing commands" to
do it correctly in Python...Maybe I should try to call the octave code
from within Python?


thanks
jean
>
>
>
>
>
>
>
> > #strip blank line:
> > identification=usbkeith.readline().strip()
> > print 'Found device: ',identification
> > usbkeith.write("SYST:REM" + "\n")
> > usbkeith.write(":SENS:VOLT:PROT 1.5\n")
> > keithdata = open(filename,'w')
> > usbkeith.write(":OUTP:STAT ON\n")
> > for number, current_in in enumerate(('0.025', '0.050', '0.075',
> > '0.100'), 1):
> >   usbkeith.write(":SOUR:CURR %s\n" % current_in)
> >   time.sleep(timesleepdefault)
> >   usbkeith.write(":MEAS:CURR?\n")
> >   measurementcurr=usbkeith.read(numofchar)
> >   print 'Measured current %d: ' % number, measurementcurr
> >   usbkeith.write(":MEAS:VOLT?\n")
> >   measurementvolt=usbkeith.read(numofchar)
> >   print 'Measured voltage %d: ' % number, measurementvolt
> >   keithdata.write(measurementcurr.strip()+' '+measurementvolt)
> > usbkeith.write(":OUTP:STAT OFF\n")
> > print "Goodbye, data logged in file:"
> > print filename
> > usbkeith.close()
> > keithdata.close()
> > --
> >http://mail.python.org/mailman/listinfo/python-list

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-10 Thread Ian Kelly
On Mon, Dec 10, 2012 at 8:48 PM, Dave Cinege  wrote:
> Thesaurus: A different way to call a dictionary.
>
> Thesaurus is a new a dictionary subclass which allows calling keys as
> if they are class attributes and will search through nested objects
> recursively when __getitem__ is called.
>
> You will notice that the code is disgusting simple. However I have found that
> this has completely changed the way I program in python. I've re-written some
> exiting programs using Thesaurus, and often realized 15-30% code reduction.
> Additionally I find the new code much easier to read.
>
> If you find yourself programing with nested dictionaries often, fighting to
> generate output or command lines for external programs, or wish you had
> a dictionary that could act (sort of) like a class, Thesaurus may be for you.

I have a few critiques on the code.  First, you might want to use
__getattribute__ instead of __getattr__.  Otherwise you'll end up
running into bugs like this:

>>> thes = Thesaurus()
>>> thes.update = 'now'
>>> thes.update


Hey, where'd my data go?  The answer is that it is in the Thesaurus:

>>> thes['update']
42

But it's not visible as an attribute because it is shadowed by the
dict methods.  Using __getattribute__ instead of __getattr__ would
mean that those non-special methods simply wouldn't be visible at all.

Second, in __getitem__ you start a loop with "for i in
range(len(l)):", and then you use i as an index into l several times.
It would be cleaner and more Pythonic to do "for i, part in
enumerate(l):", and then you can replace every occurrence of "l[i]"
with "part" (or whatever you want to call that variable).

Third, also in __getitem__ you have this code:

"""
if '.' not in key:
return dict.__getitem__(self, key)
l = key.split('.')
if isinstance(l[0], (dict, Thesaurus)):
a = self.data
else:
a = self
"""

It's not clear to me what the isinstance call here is meant to be
testing for.  The prior statements require key to be a string.  If key
is a string, then by construction l[0] is also a string.  So it seems
to me that the isinstance check here will always be False.

In any case, the key splitting here seems to be done primarily to
support the use of formatting placeholders like "%(L.l.1)s" in the
examples.  I want to point out that this use case is already well
supported (I might even say "better" supported since it cleanly
distinguishes index elements from attributes with syntax) by the
str.format style of string formatting:

>>> L = {'l': ['zero', 'one']}
>>> "There should be {L[l][1]}-- and preferably only {L[l][1]} --obvious way to 
>>> do it.".format(L=L)
'There should be one-- and preferably only one --obvious way to do it.'

Lastly, you have several bare "except" clauses in the code.  Bare
excepts are almost always incorrect.  I appreciate that it's not easy
to predict exactly what exceptions might turn up here (although I
posit that for all of these, subsets of (TypeError, KeyError,
AttributeError, IndexError) are sufficient), but at the very minimum
you should specify "except Exception", so that you're not
inadvertently catching things like SystemExit and KeyboardInterrupt.

Cheers and hope this is helpful,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-10 Thread Michael Torrie
On 12/10/2012 02:18 PM, noydb wrote:
> Follow-on question to this earlier topic - 
> https://groups.google.com/d/topic/comp.lang.python/wnUlPBBNah8/discussion 
> 
> Was curious to know if there was a way to handle different user computers 
> with different operating system set date formats.  2/10/2006 vs 2-10-2006, 
> for example.  Not an issue for my current task, but was just curious how this 
> could be handled?
> 
> If in my code I am declaring the user entered date foramtted as
> x = datetime.datetime.strptime(user_entered_time , "%m/%d/%Y %I:%M:%S %p") # 
> format for my computer
> 
> but on another person's computer, their's is set as 2-10-2006 14:26:06, the 
> code fails.  Can this be accounted for?

I use a module I got from pypi called dateutil.  It has a nice submodule
called parser that can handle a variety of date formats with good
accuracy.  Not sure how it works, but it handles all the common American
date formats I've thrown at it.

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-10 Thread Jason Friedman
> Thesaurus is a new a dictionary subclass which allows calling keys as
> if they are class attributes and will search through nested objects
> recursively when __getitem__ is called.

Good stuff.  You might consider:
1) Licensing under an OSI-approved license
(http://opensource.org/licenses/index.html).
2) Posting your code at ActiveState.com.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-10 Thread Dave Cinege
Thesaurus: A different way to call a dictionary.

Thesaurus is a new a dictionary subclass which allows calling keys as
if they are class attributes and will search through nested objects
recursively when __getitem__ is called.

You will notice that the code is disgusting simple. However I have found that
this has completely changed the way I program in python. I've re-written some
exiting programs using Thesaurus, and often realized 15-30% code reduction.
Additionally I find the new code much easier to read.

If you find yourself programing with nested dictionaries often, fighting to 
generate output or command lines for external programs, or wish you had 
a dictionary that could act (sort of) like a class, Thesaurus may be for you.
#!/usr/bin/env python
"""
thesaurus.py		2012-09-13

Copyright (c) 2012 Dave Cinege
Licence: python, Copyright notice may not be altered.

Thesaurus: A different way to call a dictionary.

Thesaurus is a new a dictionary subclass which allows calling keys as
if they are class attributes and will search through nested objects
recursivly when __getitem__ is called.

You will notice that the code is disgusting simple. However I have found that
this has completely changed the way I program in python. I've re-written some
exiting programs using Thesaurus, and often relized 15-30% code reduction.
Additionally I find the new code much easier to read.

If you find yourself programing with nested dictionaries often, fighting to 
generate output or command lines for external programs, or wish you had 
a dictionary that could act (sort of) like a class, Thesaurus may be for you.

By example:
---
#!/usr/bin/env python

import thesaurus
thes = thesaurus.Thesaurus

# I like to create a master global object called 'g'.
# No more 'global' statements for me.
g = thes()

g.prog = thes()
g['prog']['VERSION'] = '1.0'	# I can do this like a normal nested dictionary
g.prog.VERSION = '1.0'		# But isn't this so much cleaner?
g.prog.NAME = 'Thesaurus'

class TestClass:
	no = 'Class'
	way = 'this'

def main ():

	L = thes()		# Some local varibles

	L.tc = TestClass()	# We can also recurse to class attributes

	L.l = list()		# And recurse to indices too!
	L.l.append('Some')
	L.l.append('objects')
	
	g.L = L		# Easily make these locals global
	
	# Here's the real magic. Creating output without a fight.
	print '''
		When programing python using %(prog.NAME)s, it is very
		easy to access your %(L.l.1)s.
		
		%(L.l.0)s people might say %(prog.NAME)s has no %(L.tc.no)s.
	'''.replace('\t','')[1:-1] % g

	del g.L		# Clean locals up out of global space

	# If I was using a storage class, I must use hasattr() or an ugly eval.
	# But we can still use a str for the key name and 'in' like on any
	# regular dictionary.
	if 'VERSION' in g.prog:
		print 'But I challenge them to write code %(tc.way)s clean without it!' % L


if __name__ == '__main__':
	main()

---

"""
__VERSION__ = 20120913

class Thesaurus (dict):
	def __getattr__(self, name):
		return self.__getitem__(name)
	def __setattr__(self, name, value):
		return dict.__setitem__(self, name, value)
	def __delattr__(self, name):
		return dict.__delitem__(self, name)
	def __getitem__(self, key):
		if '.' not in key:
			return dict.__getitem__(self, key)
		l = key.split('.')
		if isinstance(l[0], (dict, Thesaurus)):
			a = self.data
		else:
			a = self
		for i in range(len(l)):		# Walk keys recursivly
			try:
a = a[l[i]]		# Attempt key
			except:
try:
	a = getattr(a, l[i])	# Attempt attr
except:
	try:
		a = a[int(l[i])]	# Attempt indice
	except:
		raise KeyError(key + ' [%s]' % i)
		return a
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-10 Thread Steven D'Aprano
On Mon, 10 Dec 2012 16:36:37 -0500, Dave Angel wrote:

> When accepting input from a user, consider their environment.  Perhaps
> they're in a different timezone than your program (or your native
> location), or use some other ordering for the date (for example, the
> Japanese sensibly put year first, then month, then day.  Other regions
> have different conventions.  If you can't detect the user environment,
> then you'd better tell them yours.  For example,by prompting for day,
> month, and year separately.

+1

In a nutshell, you can't know ahead of time what the user will be using 
as a date format, or what their computer will be set to use as date 
format. Unless you control the operating system and can force a 
particular date format, you are at the OS's mercy.

Having stated that the problem is hard, what's the solution? I expect 
that it will depend on the OS. Presumably under Windows there is some way 
of asking Windows "What is the current date format?". I defer to Windows 
users for that. On Linux, and probably Mac OS X, I think this is the 
right way to get the system's preferred date format:

py> import locale
py> locale.setlocale(locale.LC_ALL, '')  # You MUST call this first.
'en_AU.utf8'
py> locale.nl_langinfo(locale.D_FMT)
'%d/%m/%y'

You can pass that string on to strptime:

py> import time
py> time.strptime("11/12/13", '%d/%m/%y')
time.struct_time(tm_year=2013, tm_mon=12, tm_mday=11, tm_hour=0, 
tm_min=0, tm_sec=0, tm_wday=6, tm_yday=346, tm_isdst=-1)



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


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-10 Thread Mark Hammond

On 11/12/2012 8:39 AM, bitbucket wrote:

On Monday, December 10, 2012 3:58:33 PM UTC-5, Terry Reedy wrote:

I believe the easiest way to do that is to install the pywin
extensions

http://sourceforge.net/projects/pywin32/?source=directory

I assume it can handle out params.


That definitely looks like a good starting point.  Just hoping
someone knows whether or not it'll support the out params before I
spend too much time digging into it.


"out" params are best supported if the object supplied a typelib - then 
Python knows the params are out and does the right thing automagically. 
 If out params are detected, the result of the function will be a tuple 
of (real_result, out_param1, ...)


Even if no typelib is supported, you can access them with a little pain 
via the win32com.client.Dispatch() object.  You might like to follow up 
to the python-wi...@python.org mailing list where many people will be 
able to help.


HTH,

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


Re: MySQLdb insert HTML code error

2012-12-10 Thread Anatoli Hristov
> You're using a parametrised query (which is good :-)), but you've included
> quotes around the placeholders. There's no need to do that. They'll be
> quoted automatically when necessary:
>
> sql = "INSERT INTO product_description (product_id, language_id, name,
> description) VALUES (%s,%s,%s,%s)"

Thanks a lot it wrks. I was looking in the wrong direction (escape
str. raw etc) Thanks again :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb insert HTML code error

2012-12-10 Thread MRAB

On 2012-12-11 00:04, Anatoli Hristov wrote:

Hi all,

I'm facing an issue inserting an html code into the DB, it comes out
with a syntax error but I face it only when I have html code. Could
help me escape the error somehow ?

Here is my code

def InsertSpecsDB(product_id, spec, lang, name):
 db = MySQLdb.connect("localhost","getit","opencart")
 cursor = db.cursor()
 sql = ("INSERT INTO product_description (product_id, language_id,
name, description) VALUES ('%s','%s','%s','%s')")
 params = (product_id, lang, name, spec)
 cursor.execute(sql, params)
 id = cursor.lastrowid
 print"Updated ID %s description %s" %(int(id), lang)
 return id


You're using a parametrised query (which is good :-)), but you've included
quotes around the placeholders. There's no need to do that. They'll be
quoted automatically when necessary:

sql = "INSERT INTO product_description (product_id, language_id, name, 
description) VALUES (%s,%s,%s,%s)"


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


Re: MySQLdb insert HTML code error

2012-12-10 Thread Mark Lawrence

On 11/12/2012 00:29, Anatoli Hristov wrote:

As much use as a chocolate teapot, all you've given is a function/method
definition.  No indication of your OS, Python version, calling code, what
you expect to happen, what actually happened, apart from that your request
for assistance is perfect.  Usually I'd be able to help but sadly my crystal
ball is in for repairs at the moment.  Would you please be kind enough to
elucidate.


Thanks for your answer, the OS is CentOS release 5.7. MySQL - 5.0.96
As I said the function is working right, except when I insert an HTML code.

Thanks



Brilliant, I think your problem is in line 97 of the code that you 
*HAVEN'T QUOTED*.  Please go here, read and inwardly digest before you 
say anything else http://www.sscce.org/


--
Cheers.

Mark Lawrence.

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


Re: MySQLdb insert HTML code error

2012-12-10 Thread Anatoli Hristov
On Tue, Dec 11, 2012 at 1:29 AM, Anatoli Hristov  wrote:
>> As much use as a chocolate teapot, all you've given is a function/method
>> definition.  No indication of your OS, Python version, calling code, what
>> you expect to happen, what actually happened, apart from that your request
>> for assistance is perfect.  Usually I'd be able to help but sadly my crystal
>> ball is in for repairs at the moment.  Would you please be kind enough to
>> elucidate.
>
> Thanks for your answer, the OS is CentOS release 5.7. MySQL - 5.0.96
> As I said the function is working right, except when I insert an HTML code.
>
> Thanks

And sorry, Python 2.4
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb insert HTML code error

2012-12-10 Thread Anatoli Hristov
> As much use as a chocolate teapot, all you've given is a function/method
> definition.  No indication of your OS, Python version, calling code, what
> you expect to happen, what actually happened, apart from that your request
> for assistance is perfect.  Usually I'd be able to help but sadly my crystal
> ball is in for repairs at the moment.  Would you please be kind enough to
> elucidate.

Thanks for your answer, the OS is CentOS release 5.7. MySQL - 5.0.96
As I said the function is working right, except when I insert an HTML code.

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


Re: MySQLdb insert HTML code error

2012-12-10 Thread Mark Lawrence

On 11/12/2012 00:04, Anatoli Hristov wrote:

Hi all,

I'm facing an issue inserting an html code into the DB, it comes out
with a syntax error but I face it only when I have html code. Could
help me escape the error somehow ?

Here is my code

def InsertSpecsDB(product_id, spec, lang, name):
 db = MySQLdb.connect("localhost","getit","opencart")
 cursor = db.cursor()
 sql = ("INSERT INTO product_description (product_id, language_id,
name, description) VALUES ('%s','%s','%s','%s')")
 params = (product_id, lang, name, spec)
 cursor.execute(sql, params)
 id = cursor.lastrowid
 print"Updated ID %s description %s" %(int(id), lang)
 return id

Thanks



As much use as a chocolate teapot, all you've given is a function/method 
definition.  No indication of your OS, Python version, calling code, 
what you expect to happen, what actually happened, apart from that your 
request for assistance is perfect.  Usually I'd be able to help but 
sadly my crystal ball is in for repairs at the moment.  Would you please 
be kind enough to elucidate.


--
Cheers.

Mark Lawrence.

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


Re: open URL in the current tab

2012-12-10 Thread Chris Angelico
On Tue, Dec 11, 2012 at 11:05 AM, Jabba Laci  wrote:
> Hi,
>
>> If this is for use on somebody else's system, *please don't*. My
>
> This is for me. I have a simple GUI that produces some URL that I want
> to open in the current tab. Since I want to verify several URLs, I
> don't want to open dozens of new tabs.
>
> Here is my working solution. It requires the MozRepl Firefox add-on
> that I mentioned in the previous message.

Looks good! Since it's your own single system, the add-on requirement
isn't too onerous (but even if it's an all-mine system, I'd hesitate
to deploy an add-on to more than a handful of computers).

Specific problem, specific solution. I like it.

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


MySQLdb insert HTML code error

2012-12-10 Thread Anatoli Hristov
Hi all,

I'm facing an issue inserting an html code into the DB, it comes out
with a syntax error but I face it only when I have html code. Could
help me escape the error somehow ?

Here is my code

def InsertSpecsDB(product_id, spec, lang, name):
db = MySQLdb.connect("localhost","getit","opencart")
cursor = db.cursor()
sql = ("INSERT INTO product_description (product_id, language_id,
name, description) VALUES ('%s','%s','%s','%s')")
params = (product_id, lang, name, spec)
cursor.execute(sql, params)
id = cursor.lastrowid
print"Updated ID %s description %s" %(int(id), lang)
return id

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


Re: open URL in the current tab

2012-12-10 Thread Jabba Laci
Hi,

> If this is for use on somebody else's system, *please don't*. My

This is for me. I have a simple GUI that produces some URL that I want
to open in the current tab. Since I want to verify several URLs, I
don't want to open dozens of new tabs.

Here is my working solution. It requires the MozRepl Firefox add-on
that I mentioned in the previous message.

Laszlo

===

import telnetlib

HOST = 'localhost'
PORT = 4242# MozRepl default

def open_curr_tab(url):
tn = telnetlib.Telnet(HOST, PORT)
cmd = "content.location.href = '{url}'".format(url=url)
tn.read_until("repl> ")
tn.write(cmd + "\n")
tn.write("repl.quit()\n")

#

if __name__ == "__main__":
open_curr_tab('http://www.python.org')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String manipulation in python..NEED HELP!!!!

2012-12-10 Thread Chris Angelico
On Tue, Dec 11, 2012 at 9:38 AM,   wrote:
> I need help with a program i am doing. it is a cryptography program. i am 
> given a regular alphabet and a key. i need to use the user input and use the 
> regular alphabet and use the corresponding letter in the key and that becomes 
> the new letter. i have the basic code but need help with how to mainpulate 
> the string to do the encryption/decryption. please help

A few starting tips. Firstly, I'm going to assume here that this is a
homework question; you haven't said so, but it seems rather more
likely than the alternative (that you're actually going to use such an
incredibly low-grade cipher and an interactive prompt like this).
Please be honest about this; it's okay to ask for help, but we're not
here to do your homework for you. (We do NOT want to help you to get a
certificate you don't merit, then get a job using that certificate,
and then write code that we'll be staring at in our next jobs. There
are already more than enough incompetent programmers in the world; I'd
rather that you either learn the material for real, or if you can't,
fail the course honestly. Sorry if that sounds harsh, but I'm sure
you'd rather that I didn't have a certificate entitling me to drive a
truck on roads near you/your kids, because I do not know how to drive
one safely.)

Secondly, putting "NEED HELP" in your subject line doesn't, in fact,
help. :) It just makes you sound demanding.

So! On to the actual problem. What you need to do is find the letter
that corresponds to the one you have. Decryption is the same as
encryption but with the "alpha" and "key" switched, so I recommend
creating a function that accepts those two as arguments - something
like this:

clear = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"

def crypt(msg,from,to):
# and put your code in here

# To encrypt:
encrypted = crypt(original, clear, key)

# To decrypt:
message = crypt(encrypted, key, clear)

The details of the encryption you can put together from John's and/or
vbr's responses, but make sure you understand the code yourself. For
example: What will each of them do with any non-alphabetic characters?
Suppose your original message is "HELLO, WORLD!" - what will happen to
the comma, space, and exclamation mark? Be sure you know *why* this is
how it is, too.

If you run into trouble, post your non-working code and exactly how
it's not working, and we'll try to help you understand why it's not
working. :) In the meantime, here's a document that you may want to
familiarize yourself with:

http://www.catb.org/esr/faqs/smart-questions.html

It's a great explanation of the how and, more importantly, the why of
asking questions of volunteer geeks.

All the best!

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


Re: String manipulation in python..NEED HELP!!!!

2012-12-10 Thread Vlastimil Brom
2012/12/10  :
> I need help with a program i am doing. it is a cryptography program. i am 
> given a regular alphabet and a key. i need to use the user input and use the 
> regular alphabet and use the corresponding letter in the key and that becomes 
> the new letter. i have the basic code but need help with how to mainpulate 
> the string to do the encryption/decryption. please help
>
> here is my code so far:
>
>
> """ crypto.py
> Implements a simple substitution cypher
> """
>
> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
>
> def main():
>   keepGoing = True
>   while keepGoing:
> response = menu()
> if response == "1":
>   plain = raw_input("text to be encoded: ")
>   print encode(plain)
> elif response == "2":
>   coded = raw_input("code to be decyphered: ")
>   print decode(coded)
> elif response == "0":
>   print "Thanks for doing secret spy stuff with me."
>   keepGoing = False
> else:
>   print "I don't know what you want to do..."
>
>
>
>
> i really need help on how to encrypt it im not sure how to go about doing 
> that please help.
> --
> http://mail.python.org/mailman/listinfo/python-list


Hi,
if I understand correctly, for the data shown in the code, you may
probably use the translate method of the string (and the corresponding
maketrans method);
cf.:

python 2.7
>>> import string
>>> "ABCDEF...VWXYZ".translate(string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 
>>> "XPMGTDHLYONZBWEARKJUFSCIQV"))
'XPMGTD...SCIQV'
>>>


python 3.2
>>> "ABCDEF...VWXYZ".translate("".maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 
>>> "XPMGTDHLYONZBWEARKJUFSCIQV"))
'XPMGTD...SCIQV'
>>>

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


Re: open URL in the current tab

2012-12-10 Thread Chris Angelico
On Tue, Dec 11, 2012 at 9:27 AM, Jabba Laci  wrote:
> Hi,
>
> With the webbrowser module you can open a URL in a new tab. But how
> could I tell Firefox from Python to open a URL in the _current_ tab?

If this is for use on somebody else's system, *please don't*. My
current tab is my business, not your program's. But if this is your
own system (eg you want to use Firefox as your GUI), there are a few
options. The easiest, I think, is to have the previous page handle the
transition - trigger it in some way, and then it simply does:

location.href = "some_new_url"

How you go about triggering this is the next problem :) But that
depends hugely on what you're trying to accomplish.

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


Re: String manipulation in python..NEED HELP!!!!

2012-12-10 Thread John Gordon
In  qbai...@ihets.org 
writes:

> """ crypto.py
> Implements a simple substitution cypher
> """

> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

> def main():
>   keepGoing = True
>   while keepGoing:
> response = menu()
> if response == "1":
>   plain = raw_input("text to be encoded: ")
>   print encode(plain)
> elif response == "2":
>   coded = raw_input("code to be decyphered: ")
>   print decode(coded)
> elif response == "0":
>   print "Thanks for doing secret spy stuff with me."
>   keepGoing = False
> else:
>   print "I don't know what you want to do..."

> i really need help on how to encrypt it im not sure how to go about doing
> that please help.

def encode(plain):
   '''Return a substituted version of the plain text.'''

   encoded = ''

   for ch in plain:
  encoded += key[alpha.index(ch)]

   return encoded

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: open URL in the current tab

2012-12-10 Thread Jabba Laci
Thanks. I've found something interesting since then:

https://addons.mozilla.org/en-US/firefox/addon/mozrepl/
https://github.com/bard/mozrepl/wiki

It allows you to connect to your Firefox via telnet. Then changing the URL:

content.location.href = 

However, for this you need to install this add-on.

Laszlo

On Mon, Dec 10, 2012 at 11:43 PM, Boris FELD  wrote:
> Don't think that it's possible with webbrowser, you should try with Selenium.
>
> For example with sst (Simple Selenium Test), it open url in current
> tab or create a new one if no one exists:
>
> from sst.actions import *
> go_to('http://www.ubuntu.com/')
>
> 2012/12/10 Jabba Laci :
>> Hi,
>>
>> With the webbrowser module you can open a URL in a new tab. But how
>> could I tell Firefox from Python to open a URL in the _current_ tab?
>>
>> Thanks,
>>
>> Laszlo
>> --
>> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: open URL in the current tab

2012-12-10 Thread Boris FELD
Don't think that it's possible with webbrowser, you should try with Selenium.

For example with sst (Simple Selenium Test), it open url in current
tab or create a new one if no one exists:

from sst.actions import *
go_to('http://www.ubuntu.com/')

2012/12/10 Jabba Laci :
> Hi,
>
> With the webbrowser module you can open a URL in a new tab. But how
> could I tell Firefox from Python to open a URL in the _current_ tab?
>
> Thanks,
>
> Laszlo
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


String manipulation in python..NEED HELP!!!!

2012-12-10 Thread qbailey
I need help with a program i am doing. it is a cryptography program. i am given 
a regular alphabet and a key. i need to use the user input and use the regular 
alphabet and use the corresponding letter in the key and that becomes the new 
letter. i have the basic code but need help with how to mainpulate the string 
to do the encryption/decryption. please help

here is my code so far:


""" crypto.py
Implements a simple substitution cypher
"""

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
  keepGoing = True
  while keepGoing:
response = menu()
if response == "1":
  plain = raw_input("text to be encoded: ")
  print encode(plain)
elif response == "2":
  coded = raw_input("code to be decyphered: ")
  print decode(coded)
elif response == "0":
  print "Thanks for doing secret spy stuff with me."
  keepGoing = False
else:
  print "I don't know what you want to do..."




i really need help on how to encrypt it im not sure how to go about doing that 
please help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: open URL in the current tab

2012-12-10 Thread Joel Goldstick
On Mon, Dec 10, 2012 at 5:27 PM, Jabba Laci  wrote:

> Hi,
>
> With the webbrowser module you can open a URL in a new tab. But how
> could I tell Firefox from Python to open a URL in the _current_ tab?
>
>
The docs say this:
webbrowser.open_new(*url*)

Open *url* in a new window of the default browser, if possible, otherwise,
open *url* in the only browser window.
 webbrowser.open_new_tab(*url*)

Open *url* in a new page (“tab”) of the default browser, if possible,
otherwise equivalent to
open_new()
.






> Thanks,
>
> Laszlo
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


open URL in the current tab

2012-12-10 Thread Jabba Laci
Hi,

With the webbrowser module you can open a URL in a new tab. But how
could I tell Firefox from Python to open a URL in the _current_ tab?

Thanks,

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


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-10 Thread bitbucket
On Monday, December 10, 2012 3:58:33 PM UTC-5, Terry Reedy wrote:
> I believe the easiest way to do that is to install the pywin extensions
> 
> http://sourceforge.net/projects/pywin32/?source=directory
> 
> I assume it can handle out params.

That definitely looks like a good starting point.  Just hoping someone knows 
whether or not it'll support the out params before I spend too much time 
digging into it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-10 Thread Dave Angel
On 12/10/2012 04:18 PM, noydb wrote:
> Follow-on question to this earlier topic - 
> https://groups.google.com/d/topic/comp.lang.python/wnUlPBBNah8/discussion 

For those who avoid googlegroups with a passion, and/or don't have
internet access, the subject of that thread is "date-time comparison,
aware vs naive", on this same mailing list.

> Was curious to know if there was a way to handle different user computers 
> with different operating system set date formats.  2/10/2006 vs 2-10-2006, 
> for example.  Not an issue for my current task, but was just curious how this 
> could be handled?
>
> If in my code I am declaring the user entered date foramtted as
> x = datetime.datetime.strptime(user_entered_time , "%m/%d/%Y %I:%M:%S %p") # 
> format for my computer
>
> but on another person's computer, their's is set as 2-10-2006 14:26:06, the 
> code fails.

You can save people a lot of time if you just think before posting. 
What do you define as failure?  is your motherboard smoking, or is the
final result off by a second?
Please reread my last message on the previous thread.  If you want us to
give you code advice, show us what you're doing, don't just describe it
in vague terms.

>  Can this be accounted for?

When accepting input from a user, consider their environment.  Perhaps
they're in a different timezone than your program (or your native
location), or use some other ordering for the date (for example, the
Japanese sensibly put year first, then month, then day.  Other regions
have different conventions.  If you can't detect the user environment,
then you'd better tell them yours.  For example,by prompting for day,
month, and year separately.


-- 

DaveA

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


Re: strptime - dates formatted differently on different computers

2012-12-10 Thread noydb
NTFS partition
Windows 7
Python 2.7
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date-time comparison, aware vs naive

2012-12-10 Thread noydb

> 
> >
> 
> >
> 
> http://docs.python.org/2/library/datetime
> 
> """ An object of type *time* or *datetime* may be naive or *aware"
> 
> 
> 
> aware refers to time-zone and daylight savings time, such political
> 
> ephemerals.  Two times can only be changed if one knows they're both in
> 
> the same one, or if one knows precisely what each is.
> 
> *
> 
> naive assumes the former, while aware trusts the latter.
> 
> 
> 
> 
> 
> To the OP:  please specify your python version, your OS, and show your
> 
> source. Also show the complete error traceback.  And while you're at it,
> 
> it might be useful to know the type of drive the file is on, since
> 
> Windows uses local times on FAT32 partitions, and gmt on NTFS  partitions.
> 
> 
> 
> I suspect you're on Windows, so I can't help you with this nonsense.  But I 
> can at least help you ask a clear question.
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

Fair enough, thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


strptime - dates formatted differently on different computers

2012-12-10 Thread noydb
Follow-on question to this earlier topic - 
https://groups.google.com/d/topic/comp.lang.python/wnUlPBBNah8/discussion 

Was curious to know if there was a way to handle different user computers with 
different operating system set date formats.  2/10/2006 vs 2-10-2006, for 
example.  Not an issue for my current task, but was just curious how this could 
be handled?

If in my code I am declaring the user entered date foramtted as
x = datetime.datetime.strptime(user_entered_time , "%m/%d/%Y %I:%M:%S %p") # 
format for my computer

but on another person's computer, their's is set as 2-10-2006 14:26:06, the 
code fails.  Can this be accounted for?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date-time comparison, aware vs naive

2012-12-10 Thread Dave Angel
On 12/10/2012 03:52 PM, Steven D'Aprano wrote:
> On Mon, 10 Dec 2012 11:57:37 -0800, noydb wrote:
>
>> I want to compare a user entered date-and-time against the date-and-time
>> of a pdf file.  I posted on this (how to get a file's date-time) before,
>> was advised to do it like:
>>
>> import datetime, os, stat
>> mtime = os.lstat(filename)[stat.ST_MTIME]   // the files modification 
>> time
> What language are you writing? Using // for comments is not Python.
>
>
>> dt = datetime.datetime.fromtimestamp(mtime)
>>
>> I am having problems with the comparison, that line is failing.
> You haven't shown us the comparison line. Would you like us to guess what 
> it does?
>
> My guess is that you are doing this:
>
> if mtime is dtime: ... 
>
> Am I close?
>
> If not, please forgive me, my crystal ball is often faulty.
>
>
>> I think
>> I may have figured out the issue -- I think it is a matter of the file's
>> time being 'aware' and the user-input date-time being 'naive'.
> "Aware" of what?
>
>
http://docs.python.org/2/library/datetime
""" An object of type *time* or *datetime* may be naive or *aware"

aware refers to time-zone and daylight savings time, such political
ephemerals.  Two times can only be changed if one knows they're both in
the same one, or if one knows precisely what each is.
*
naive assumes the former, while aware trusts the latter.


To the OP:  please specify your python version, your OS, and show your
source. Also show the complete error traceback.  And while you're at it,
it might be useful to know the type of drive the file is on, since
Windows uses local times on FAT32 partitions, and gmt on NTFS  partitions.

I suspect you're on Windows, so I can't help you with this nonsense.  But I can 
at least help you ask a clear question.

-- 

DaveA

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


Re: date-time comparison, aware vs naive

2012-12-10 Thread noydb
On Monday, December 10, 2012 3:52:55 PM UTC-5, Steven D'Aprano wrote:
> On Mon, 10 Dec 2012 11:57:37 -0800, noydb wrote:
> 
> 
> 
> > I want to compare a user entered date-and-time against the date-and-time
> 
> > of a pdf file.  I posted on this (how to get a file's date-time) before,
> 
> > was advised to do it like:
> 
> > 
> 
> > import datetime, os, stat
> 
> > mtime = os.lstat(filename)[stat.ST_MTIME]   // the files modification 
> 
> > time
> 
> 
> 
> What language are you writing? Using // for comments is not Python.
> 
> 
> 
> 
> 
> > dt = datetime.datetime.fromtimestamp(mtime)
> 
> > 
> 
> > I am having problems with the comparison, that line is failing.
> 
> 
> 
> You haven't shown us the comparison line. Would you like us to guess what 
> 
> it does?
> 
> 
> 
> My guess is that you are doing this:
> 
> 
> 
> if mtime is dtime: ... 
> 
> 
> 
> Am I close?
> 
> 
> 
> If not, please forgive me, my crystal ball is often faulty.
> 
> 
> 
> 
> 
> > I think
> 
> > I may have figured out the issue -- I think it is a matter of the file's
> 
> > time being 'aware' and the user-input date-time being 'naive'.
> 
> 
> 
> "Aware" of what?
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven

Forgive me, I was just copying the code from the original reply to my orignal 
question.

Forgive me for not posting the comparison line, it goes something like
if one_time > another_time:

Forgive me - the 'aware' time vs 'naive' time refers to documentation I found 
for the datetime module, see second sentence down 
http://docs.python.org/2/library/datetime.html 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-10 Thread Terry Reedy

On 12/10/2012 2:13 PM, bitbucket wrote:

I have an existing Windows application which provides an OLE
Automation (IDispatch) interface.  I'm not able to change that
interface.  I'd like to call it from a scripting language.  I figure
this would provide a nice quick way to invoke on the app.


I believe the easiest way to do that is to install the pywin extensions
http://sourceforge.net/projects/pywin32/?source=directory

I assume it can handle out params.

--
Terry Jan Reedy

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


Re: date-time comparison, aware vs naive

2012-12-10 Thread Steven D'Aprano
On Mon, 10 Dec 2012 11:57:37 -0800, noydb wrote:

> I want to compare a user entered date-and-time against the date-and-time
> of a pdf file.  I posted on this (how to get a file's date-time) before,
> was advised to do it like:
> 
> import datetime, os, stat
> mtime = os.lstat(filename)[stat.ST_MTIME]   // the files modification 
> time

What language are you writing? Using // for comments is not Python.


> dt = datetime.datetime.fromtimestamp(mtime)
> 
> I am having problems with the comparison, that line is failing.

You haven't shown us the comparison line. Would you like us to guess what 
it does?

My guess is that you are doing this:

if mtime is dtime: ... 

Am I close?

If not, please forgive me, my crystal ball is often faulty.


> I think
> I may have figured out the issue -- I think it is a matter of the file's
> time being 'aware' and the user-input date-time being 'naive'.

"Aware" of what?



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


Re: About open file for Read

2012-12-10 Thread Steven D'Aprano
On Mon, 10 Dec 2012 08:36:22 -0800, moonhkt wrote:

> Hi All
> 
> I am new in Python. When using open and then for line in f .
> 
> Does it read all the data into f object ? or read line by line ?

Have you read the Fine Manual?

http://docs.python.org/2/library/stdtypes.html#file-objects

If you have read it, and the answer is still not clear, then please tell 
us so we can improve the documentation.

`for line in open(file, "r"):` does not read the entire file into memory 
at once, it iterates over the file reading one line at a time.


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


Matplotlib/Pylab Error

2012-12-10 Thread subhabangalore
Dear Group,

I am trying to enumerate few interesting errors on pylab/matplotlib. 
If any of the learned members can kindly let me know how should I address them.

I am trying to enumerate them as follows.

i) >>> import numpy
>>> import pylab
>>> t = numpy.arange(0.0, 1.0+0.01, 0.01)
>>> s = numpy.cos(2*2*numpy.pi*t)
>>> pylab.plot(t, s)
[]
>>> pylab.show()
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
line 236, in resize
self.show()
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
line 239, in draw
FigureCanvasAgg.draw(self)
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", line 
421, in draw
self.figure.draw(self.renderer)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\figure.py", line 898, in draw
func(*args)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\axes.py", line 1997, in draw
a.draw(renderer)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\axis.py", line 1045, in draw
tick.draw(renderer)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\axis.py", line 239, in draw
self.label1.draw(renderer)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\text.py", line 591, in draw
ismath=ismath)
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", line 
167, in draw_text
font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
TypeError: draw_glyphs_to_bitmap() takes no keyword arguments

ii) Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit 
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 2.6.1  
>>> import networkx as nx
>>> G=nx.Graph()
>>> G.add_node(1)
>>> G.add_nodes_from([2,3])
>>> H=nx.path_graph(10)
>>> G.add_nodes_from(H)
>>> G.add_node(H)
>>> G.add_edge(1,2)
>>> G.draw()

Traceback (most recent call last):
  File "", line 1, in 
G.draw()
AttributeError: 'Graph' object has no attribute 'draw'
>>> import matplotlib.pyplot as plt
>>> plt.show()
>>> nx.draw(G)
>>> plt.show()
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
line 236, in resize
self.show()
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
line 239, in draw
FigureCanvasAgg.draw(self)
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", line 
421, in draw
self.figure.draw(self.renderer)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\figure.py", line 898, in draw
func(*args)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\axes.py", line 1997, in draw
a.draw(renderer)
  File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
draw_wrapper
draw(artist, renderer, *args, **kwargs)
  File "C:\Python26\Lib\site-packages\matplotlib\text.py", line 591, in draw
ismath=ismath)
  File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", line 
167, in draw_text
font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
TypeError: draw_glyphs_to_bitmap() takes no keyword arguments

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


Re: date-time comparison, aware vs naive

2012-12-10 Thread noydb
Found this, and it solved my problem
http://blogs.law.harvard.edu/rprasad/2011/09/21/python-string-to-a-datetime-object/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date-time comparison, aware vs naive

2012-12-10 Thread John Gordon
In <21eb3e6f-9a82-47aa-93ff-8f4083d18...@googlegroups.com> noydb 
 writes:

> I want to compare a user entered date-and-time against the date-and-time of
> a pdf file.  I posted on this (how to get a file's date-time) before, was
> advised to do it like:

> import datetime, os, stat
> mtime = os.lstat(filename)[stat.ST_MTIME] // the files modification time
> dt = datetime.datetime.fromtimestamp(mtime)

> I am having problems with the comparison, that line is failing.

What line?  You haven't posted any comparison line of code here.

Please post the actual code you're using, instead of telling us about it.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


date-time comparison, aware vs naive

2012-12-10 Thread noydb
I want to compare a user entered date-and-time against the date-and-time of a 
pdf file.  I posted on this (how to get a file's date-time) before, was advised 
to do it like:

import datetime, os, stat 
mtime = os.lstat(filename)[stat.ST_MTIME]   // the files modification time 
dt = datetime.datetime.fromtimestamp(mtime) 

I am having problems with the comparison, that line is failing.  I think I may 
have figured out the issue -- I think it is a matter of the file's time being 
'aware' and the user-input date-time being 'naive'.  The user-input date-time 
has a parameter type of date (calender and time tool supplied to enter), but is 
it 'aware'?  The comparison is not working so I think that it is not aware.  I 
can successfully compare two pdf file times against one another.  So, is there 
a way to cast that user-input value (prints as 2/10/2012 3:19:57 PM) as an 
'aware' date-time?  How?  And can anyone confirm that my findings are probably 
correct?

Thanks for any help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using poplib to parse headers - Thank You All!

2012-12-10 Thread asklucas
Hello Jean-Claude!

Thank you for your post, it helped me a lot!
I'm not too new to Python but still struggling to make use of that great 
language's features.

I haven't tested it but since you are interested in syntactic subtleties, I 
think you can save one iterator (k):

for j in popconnection.retr( i+1):
if type( j) == list:
outString = ""
for line in j:
outString += line
outString += '\n'

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


accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-10 Thread bitbucket
I have an existing Windows application which provides an OLE Automation 
(IDispatch) interface.  I'm not able to change that interface.  I'd like to 
call it from a scripting language.  I figure this would provide a nice quick 
way to invoke on the app.

I initially tried this with Windows Powershell but ran into the following 
problem.  I was able to create the object and invoke simple methods on it.  
However the interface for this app has methods which take out params.  i.e. you 
pass in a reference to a variable and the server fills in the value.  I 
couldn't get that to work.  I finally gave up and decided it was just a 
limitation of Powershell, not being able to work with those out params.

My next thought was to do it in python.  I've been reading up on python and 
I've found a decent amount of into out there on doing OLE and I'm optimistic.  
But, I thought that I'd ask the question before digging too much farther into 
it...

When calling an OLE Automation (IDispatch) server from python can I make use of 
"out params" defined by the interface?

To get more specific, here's an example from the server's IDL for one of its 
methods.

[id(15), helpstring("method GetSettingValue")] VARIANT_BOOL 
GetSettingValue(BSTR settingName, BSTR* settingValue);

As you can see, you have to pass in an out param for settingValue.  The server 
fills this in for you.  And this is what I couldn't get to work in Powershell.

Anyone know whether or not OLE from python will allow passing in out params?  
Do you think this will work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About open file for Read

2012-12-10 Thread Peter Otten
Dave Angel wrote:

> On 12/10/2012 11:36 AM, moonhkt wrote:
>> Hi All
>>
>> I am new in Python. When using open and then for line in f .
>>
>> Does it read all the data into f object ? or read line by line ?
>>
>>
>>   f=open(file, 'r')
>>for line in f:
>>   if userstring in line:
>>  print "file: " + os.path.join(root,file)
>>  break
>>f.close()
>>
>>
>> moonhk
> 
> open() does not read the whole file into any object.  There is buffering
> that goes on in the C libraries that open() calls, but that should be
> transparent to you for regular files.
> 
> When you ask for a line, it'll read enough to fulfill that request, and
> maybe some extra that'll get held somewhere in the C runtime library.
> 
> You should look into the 'with' statement, to avoid that f.close().
> That way the file will be closed, regardless of whether you get an
> exception or not.
> 
> http://docs.python.org/2/reference/compound_stmts.html#index-15
> 
> with open(file,. "r") as f:
> for line in f:
>  etc.
> 
> BTW, since you're in version 2.x, you should avoid hiding the builtin
> file object.  Call it something like file_name, or infile_name.
> 

Python does a bit of buffering on its own (which is why you cannot mix file 
iteration and .readline() calls):

>>> with open("tmp.txt", "w") as f: f.writelines("%s\n" % i for i in 
range(10**6))
... 
>>> f = open("tmp.txt")
>>> f.readline()
'0\n'
>>> f.tell()
2
>>> f.readline()
'1\n'
>>> f.tell()
4
>>> next(f) # a for-loop does this implicitly
'2\n'
>>> f.tell()
8196 # after a next() call or the first loop iteration
 # part of the file is now in a buffer.
>>> f.readline()
Traceback (most recent call last):
  File "", line 1, in 
ValueError: Mixing iteration and read methods would lose data
>>> f.seek(0, 2)
>>> f.tell()
690


This is Python 2, in Python 3 f.tell() would fail after a next(f) call, but 
f.readline() continues to work.


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


Re: About open file for Read

2012-12-10 Thread Dave Angel
On 12/10/2012 11:36 AM, moonhkt wrote:
> Hi All
>
> I am new in Python. When using open and then for line in f .
>
> Does it read all the data into f object ? or read line by line ?
>
>
>   f=open(file, 'r')
>for line in f:
>   if userstring in line:
>  print "file: " + os.path.join(root,file)
>  break
>f.close()
>
>
> moonhk

open() does not read the whole file into any object.  There is buffering
that goes on in the C libraries that open() calls, but that should be
transparent to you for regular files.

When you ask for a line, it'll read enough to fulfill that request, and
maybe some extra that'll get held somewhere in the C runtime library.

You should look into the 'with' statement, to avoid that f.close(). 
That way the file will be closed, regardless of whether you get an
exception or not.

http://docs.python.org/2/reference/compound_stmts.html#index-15

with open(file,. "r") as f:
for line in f:
 etc.

BTW, since you're in version 2.x, you should avoid hiding the builtin
file object.  Call it something like file_name, or infile_name.

-- 

DaveA

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


Re: forking and avoiding zombies!

2012-12-10 Thread peter

On 12/10/2012 12:42 PM, andrea crotti wrote:

So I implemented a simple decorator to run a function in a forked
process, as below.

It works well but the problem is that the childs end up as zombies on
one machine, while strangely
I can't reproduce the same on mine..

I know that this is not the perfect method to spawn a daemon, but I
also wanted to keep the code
as simple as possible since other people will maintain it..

What is the easiest solution to avoid the creation of zombies and
maintain this functionality?
thanks


def on_forked_process(func):
 from os import fork
 """Decorator that forks the process, runs the function and gives
 back control to the main process
 """
 def _on_forked_process(*args, **kwargs):
 pid = fork()
 if pid == 0:
 func(*args, **kwargs)
 _exit(0)
 else:
 return pid

 return _on_forked_process
Ou. yo need to use something more advanced. This is the code from book 
('Unix Network Programing' - the python implementation)


import sys, os
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid( )
# Perform second fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)
# The process is now daemonized, redirect standard file descriptors.
for f in sys.stdout, sys.stderr: f.flush( )
si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno( ), sys.stdin.fileno( ))
os.dup2(so.fileno( ), sys.stdout.fileno( ))
os.dup2(se.fileno( ), sys.stderr.fileno( ))

Put this file and named daemon.py, then just for your program by calling 
import this file.


Like this.

from daemon import daemonize

def main():
  while True:
print 'I'm Alive :)'

if __name__ == '__main__':
daemonize(stdout='/var/log/run_time.log', stderr='/var/log/error.log')
main()

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


About open file for Read

2012-12-10 Thread moonhkt
Hi All

I am new in Python. When using open and then for line in f .

Does it read all the data into f object ? or read line by line ?


  f=open(file, 'r')
   for line in f:
  if userstring in line:
 print "file: " + os.path.join(root,file)
 break
   f.close()


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


Re: using smtp sent large file upto 60MB

2012-12-10 Thread moonhkt
On 12月5日, 下午11時01分, Michael Torrie  wrote:
> On 12/04/2012 05:54 PM, moonhkt wrote:
>
> > Our SMTP can send file more than 60MB. But our notes server can
> > configured 100MB,30MB or 10MB. My notes Mail box can receive 100MB.
>
> > In UNIX, by below command send  smtp mail.
> > uuencode $xfn $xfn | mail -s "$SUBJECT" $NAME
>
> Just continue to use this set of commands.  You can use the subprocess
> module to interact with these programs.

OK. Will try using subprocess.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with usbtmc-communication

2012-12-10 Thread wrw
On Dec 10, 2012, at 8:31 AM, Jean Dubois  wrote:

[byte]

> As you can see this approach suffers from the same "buffer problem" as
> the approach with readline did. One now good argue as a workaround:
> get rid of the first data pair and add an extra measure command for
> the missing data pair, however this still does not explain why this
> problem is there in Python and not in Octave and I also fear I'll get
> more trouble when sending combined commands e.g. such as that to
> create a staircase current
> So my question is, how to modify the Python-code such that the first
> data pair is indeed the first data pair
> 
> thanks,
> jean
> 
> Here follows the new code:
> #!/usr/bin/python
> import time
> import os
> import sys
> measurementcurr=''
> measurementvolt=''
> timesleepdefault=5
> print "Enter a numofchar (11 = numofchar = int(raw_input())
> filename ='mydata.txt'
> usbkeith = open('/dev/usbtmc1','r+')
> usbkeith.flush()
> usbkeith.write("*IDN?\n")

It seems like a real leap of faith to be opening /dev/usbtmc1 as though it were 
a file-oriented device.  I've never heard of ANY instrument interface 
implemented this way.
Where did you see example code that did that.  Have you tried to access 
/dev/usbtmc1 as though it were a serial device?

> #strip blank line:
> identification=usbkeith.readline().strip()
> print 'Found device: ',identification
> usbkeith.write("SYST:REM" + "\n")
> usbkeith.write(":SENS:VOLT:PROT 1.5\n")
> keithdata = open(filename,'w')
> usbkeith.write(":OUTP:STAT ON\n")
> for number, current_in in enumerate(('0.025', '0.050', '0.075',
> '0.100'), 1):
>   usbkeith.write(":SOUR:CURR %s\n" % current_in)
>   time.sleep(timesleepdefault)
>   usbkeith.write(":MEAS:CURR?\n")
>   measurementcurr=usbkeith.read(numofchar)
>   print 'Measured current %d: ' % number, measurementcurr
>   usbkeith.write(":MEAS:VOLT?\n")
>   measurementvolt=usbkeith.read(numofchar)
>   print 'Measured voltage %d: ' % number, measurementvolt
>   keithdata.write(measurementcurr.strip()+' '+measurementvolt)
> usbkeith.write(":OUTP:STAT OFF\n")
> print "Goodbye, data logged in file:"
> print filename
> usbkeith.close()
> keithdata.close()
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: The Zen of Zope, by Alex Clark

2012-12-10 Thread Alex Clark

On 2012-12-10 04:24:00 +, Steven D'Aprano said:


On Sun, 09 Dec 2012 20:13:43 -0500, Alex Clark wrote:


import other

The Zen of Zope, by Alex Clark


I expect that I would find that hilarious if I knew anything about Zope :)



Well, you are in luck! Because it's a tutorial too: 
https://github.com/aclark4life/other/blob/master/other.py :-)




--
Alex Clark · https://www.gittip.com/aclark4life/


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


Re: problem with usbtmc-communication

2012-12-10 Thread Jean Dubois
On 7 dec, 14:46, Jean Dubois  wrote:
> On 6 dec, 21:15, w...@mac.com wrote:
>
> > On Dec 6, 2012, at 2:41 PM, Jean Dubois  wrote:
>
> > > On 6 dec, 15:50, w...@mac.com wrote:
> > >> On Dec 6, 2012, at 8:50 AM, Jean Dubois  wrote:
>
> > >> [byte]
>
> > >>> It seems there is some misunderstanding here. What I meant with  how
> > >>> to "do the equivalent in Python" refered to  "reading characters
> > >>> rather than lines".
> > >>> I have written working code myself for another Keithleu which does use
> > >>> RS232 for communication. The problem now is specifically for the new
> > >>> Keithley which doesn't allow RS232 but only USB-communication over
> > >>>usbtmc. So if the "buffer-problem" could be changed by reading
> > >>> characters that would be great.
>
> > >>> regards,
> > >>> Jean
>
> > >>> --
> > >>>http://mail.python.org/mailman/listinfo/python-list
>
> > >> Sorry about the misunderstanding (and subsequent waste of bandwidth).  
> > >> However, if you will look at the serial reads and writes in that 
> > >> handler, you will see that it does things like "serial.read(n)" where 
> > >> "n" is an explicit number, the number of bytes to be read from the 
> > >> serial buffer.
>
> > >> -Bill
> > > I tried changing measurementcurr=usbkeith.readline() to
> > > measurementcurr=usbkeith.read(1)
> > > but this leads to trouble with theusbtmc-thing:
>
> > > Measured current 1:
> > > Traceback (most recent call last):
> > >  File "./keith2200rev2.py", line 26, in 
> > >    measurementvolt=usbkeith.read(1)
> > > IOError: [Errno 110] Connection timed out
>
> > > and hereafter I need to restart the Keithley...:-(
>
> > > regards,
> > > Jean
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > Several comments:
>
> > 1)  I can't be sure, but that would seem to be asking the Keithley to be 
> > providing 10,000 readings.  I don't know about the GPIB bus (which 
> > thisUSBTMClibrary seems to be trying >to emulate), but most serial devices 
> > expect to provide one answer per read-write handshake.  That is, you send 
> > one read command and get one answer back.  That answer may contain >several 
> > bytes, but I'd be surprised it it contained 10,000.  The typical cycle is 
> > something like send-an-initialize, read-status, send-mode-set-up, 
> > read-status, send trigger >command, read-answer…  lather and repeat.   (Or 
> > some logical equivalent of all that).  On the assumption that theUSBTMCAPI 
> > handles most of that, I'd try usbkeith.read(n) where >"n" is the number of 
> > decimal digits you expect to get back plus sign.
>
> 1 wasn't a good guess indeed> -
>
> > 2) I took a quick look at the Keithley and National Instruments web sites 
> > (where the documentation is at best, VERY poorly indexed and hard to search 
> > for).  USBTMC*appears* to be a software layer designed to allow newer 
> > Tektronix and Keithley instruments to be driven using older software that 
> > drove GPIB equipment.  To make matters worse, if I'm reading it right (I 
> > didn't study in detail) it appears to ALSO be providing a GPIB-like API to 
> > Windows versions of National Instruments LabView.
>
> > 3)  If I understand what you are trying to do, you want to go straight from 
> > python to the Keithley USB port, without detouring (USB-to-GPIB and GPIB 
> > back to USB).
>
> Yes indeed, that's exactly what I want
>
> > 4)  I did find (but did not try to read in detail) the following link:  
> > http://www.ni.com/white-paper/4478/en which documents direct USB control of 
> > instruments.  The python serial >library provides quite transparent control 
> > of reading and writing to the USB interface.  Maybe following this link 
> > will get you going.
>
> Thanks for the link, but as you can see there they want to push NI-
> VISA forward as the solution, which under Linux means more complexity
> and surely isn't as simple to install as they claim, so if possible
> I'd avoid ni-visa.
>
> I'll experiment further Monday with read() and keep you informed
>
> regards,
> Jean
I changed the program as below an experimentally found out I have to
use an number of characters between 11 and 4095
I doesn't seem to make any difference which value I choose in that
interval, however the results are as follows:
0.0077219 0.0295029; this is rubbish
0.0249596 0.261837; this should have been the first data pair
0.0499763 0.516741; this should have been the 2nd data pair
0.0750685 0.767388; this should have been the 3rd data pair
 4th data pair is missing

As you can see this approach suffers from the same "buffer problem" as
the approach with readline did. One now good argue as a workaround:
get rid of the first data pair and add an extra measure command for
the missing data pair, however this still does not explain why this
problem is there in Python and not in Octave and I also fear I'll get
more trouble when sending combined commands e.g. such as that to
create a staircase current
So

Re: why the conut( ) can not get the number?

2012-12-10 Thread Peter Otten
水静流深 wrote:

> i wnat to get the number of  a atrributes in a xpath,here is my code,why i
> can not get the number ? import urllib
> import lxml.html
> down="http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html";
> file=urllib.urlopen(down).read()
> root=lxml.html.document_fromstring(file)
> for order,node in enumerate(root.xpath('//li[@class="toctree-l1"]')):
>   print order,node.xpath('.//a[count(*)]')

This looks more like an xpath than a python problem. I'm no xpath expert -- 
and you don't describe the expected outcome -- maybe you want

print order, node.xpath("count(.//a)")

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


why the conut( ) can not get the number?

2012-12-10 Thread ????????
i wnat to get the number of  a atrributes in a xpath,here is my code,why i can 
not get the number ? 
import urllib
import lxml.html
down="http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html"; 
file=urllib.urlopen(down).read() 
root=lxml.html.document_fromstring(file)
for order,node in enumerate(root.xpath('//li[@class="toctree-l1"]')):
  print order,node.xpath('.//a[count(*)]')-- 
http://mail.python.org/mailman/listinfo/python-list


Dropbox Hires Away Google’s Guido Van Rossum

2012-12-10 Thread Rodrick Brown
http://techcrunch.com/2012/12/07/dropbox-guido-van-rossum-python/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Noob Question.

2012-12-10 Thread Alexander Blinne
Am 05.12.2012 21:24, schrieb Owatch:
> Thanks a TON for your answer thought, this is exactly what I really hoped for.
> The problem for me is that I don't actually know anything about writing a 
> function that opens a network socket, and "connects to that plugin und asks 
> it for the 
> information you require."

That plugin should have some documentation which should tell you
something about how to connect to it and how to request information.
When you know that you can turn to the python documentation and find out
how to do this in python.

> That's all really beyond me, all I can do is what I did so far, which is make 
> it ask for your temperature value, and then test it to see if its an integer
> 
> Then (I added this for testing) It asks for any temperature value. And if it 
> exceeds the given limit, it rings an alarm. Until it freezes and becomes 
> unresponsive :D

If you have specific problems with code you have written, try to build
up a minimal "working" example that shows the problem plus any error
messages/exceptions/stack traces you get back. We might be able to help
you with your code.

> I don't know how to make it 'query' or grab values constantly, if you don't 
> mind my potentially incorrect terminology. 

This is typically done with some kind of loop, e.g.

run = True
while run:
#do something repeatedly and do "run = False" if you want to stop
pass

Greetings
Alexander

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


Re: A question about readability

2012-12-10 Thread rusi
On Dec 10, 3:03 pm, Jean-Michel Pichavant 
wrote:
> - Original Message -
> > On Dec 7, 6:46 pm, Marco  wrote:
> > > Hi all, do you think this code:
>
> > > $ more myscript.py
> > > for line in open('data.txt'):
> > >      result = sum(int(data) for data in line.split(';'))
> > >      print(result)
>
> > > that sums the elements of the lines of this file:
>
> > > $ more data.txt
> > > 30;44;99;88
> > > 11;17;16;50
> > > 33;91;77;15
> > > $ python3.3 myscript.py
> > > 261
> > > 94
> > > 216
>
> > > is explicit enough? Do you prefer a clearer solution?
> > > Thanks in advance, Marco
> > > --
> > > Marco
>
> > Interpreting your question as a general question of stylistics, my
> > experience is that a 3 line script often becomes a 10 line or a 50
> > line script at which point the direct printing will have to be
> > modified to create an internal data structure.
>
> > So on the whole I find it expedient to start with that assumption and
> > write it as:
>
> > def linesums(file):
> >   return [sum(int(i) for i in l.split(';')) for l in open(file, 'r')]
>
> Why change the OP's namings ? 'data' and 'line' were more suitable than 'i' 
> and 'l'. Of course we're nitpicking, no one will get hurt.
>
> JM

Yes, l is an undesirable name because it can look like 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A question about readability

2012-12-10 Thread Jean-Michel Pichavant


- Original Message -
> On Dec 7, 6:46 pm, Marco  wrote:
> > Hi all, do you think this code:
> >
> > $ more myscript.py
> > for line in open('data.txt'):
> >      result = sum(int(data) for data in line.split(';'))
> >      print(result)
> >
> > that sums the elements of the lines of this file:
> >
> > $ more data.txt
> > 30;44;99;88
> > 11;17;16;50
> > 33;91;77;15
> > $ python3.3 myscript.py
> > 261
> > 94
> > 216
> >
> > is explicit enough? Do you prefer a clearer solution?
> > Thanks in advance, Marco
> > --
> > Marco
> 
> Interpreting your question as a general question of stylistics, my
> experience is that a 3 line script often becomes a 10 line or a 50
> line script at which point the direct printing will have to be
> modified to create an internal data structure.
> 
> So on the whole I find it expedient to start with that assumption and
> write it as:
> 
> def linesums(file):
>   return [sum(int(i) for i in l.split(';')) for l in open(file, 'r')]

Why change the OP's namings ? 'data' and 'line' were more suitable than 'i' and 
'l'. Of course we're nitpicking, no one will get hurt.

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list