Re: AttributeError: 'module' object has no attribute 'urlretrieve' in window subsystem ubuntu bash for tensorflow

2017-05-21 Thread Kev Dwyer
Ho Yeung Lee wrote:

> i use window subsystem ubuntu
> and install python 3 and tensorflow
> 
> then when try deep learning
> 
> https://www.tensorflow.org/tutorials/wide_and_deep
> 
> got error when urlretrieve local directory in ubuntu in window
> 
> tried urllib3 still have error
> 
> import tempfile
> import pandas as pd
> import urllib as urllib
> import os
> 
> model_dir = tempfile.mkdtemp()
> m = tf.contrib.learn.DNNLinearCombinedClassifier(
> model_dir=model_dir,
> linear_feature_columns=wide_columns,
> dnn_feature_columns=deep_columns,
> dnn_hidden_units=[100, 50])
> 
> ...
> 
> urllib.urlretrieve(r"/mnt/c/Users/hello/Documents/data.csv",
> train_file.name)
> urllib.urlretrieve(r"/mnt/c/Users/hello/Documents/dataTest.csv",
> test_file.name)
> 
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'module' object has no attribute 'urlretrieve'


If you're using python3, you need to do:

from urllib.request import urlretrieve

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


Re: cross python version randomness

2017-03-21 Thread Kev Dwyer
Robin Becker wrote:

> Is there a way to get the same sequences of random numbers in python 2.7
> and python >= 3.3?
> 
> I notice that this simple script produces different values in python 2.7
> and >=3.3
> 
> C:\code\hg-repos\reportlab>cat s.py
> import sys, random
> print(sys.version)
> random.seed(103)
> for i in range(5):
>  print(i, random.randint(10,25))
> 
> C:\code\hg-repos\reportlab>\python27\python s.py
> 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit
> (AMD64)] 0 25
> 1 17
> 2 21
> 3 21
> 4 13
> 
> C:\code\hg-repos\reportlab>\python33\python s.py
> 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit
> (AMD64)] 0 24
> 1 16
> 2 12
> 3 13
> 4 22
> 
> However, when I use random.random() all seems to be the same so this
> script C:\code\hg-repos\reportlab>cat u.py
> import sys, random
> print(sys.version)
> random.seed(103)
> for i in range(5):
>  print(i, random.random())
> 
> seems to be fine
> 
> 
> C:\code\hg-repos\reportlab>\python27\python u.py
> 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit
> (AMD64)] (0, 0.9790501200727744)
> (1, 0.45629827629184827)
> (2, 0.7188470341002364)
> (3, 0.7348862425853395)
> (4, 0.21490166849706338)
> 
> C:\code\hg-repos\reportlab>\python33\python u.py
> 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit
> (AMD64)] 0 0.9790501200727744
> 1 0.45629827629184827
> 2 0.7188470341002364
> 3 0.7348862425853395
> 4 0.21490166849706338
> 
> presumably randint is doing something different to get its values.


The docs [https://docs.python.org/3/library/random.html#random.randrange] 
for randrange have this note:

Changed in version 3.2: randrange() is more sophisticated about producing 
equally distributed values. Formerly it used a style like int(random()*n) 
which could produce slightly uneven distributions.

Maybe that's the explanation?  Unfortunately I don't have an install of 
3.0/1 to test against.

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


Re: sorting a list of dicts by a computed field

2017-01-31 Thread Kev Dwyer
Larry Martell wrote:

> I have a list of dicts and one item of the dict is a date in m/d/Y
> format. I want to sort by that. I tried this:
> 
> sorted(data['trends'], key=lambda k:
> datetime.strptime(k['date_time'],'%m/%d/%Y'))
> 
> But that fails with:
> 
> Exception Type: AttributeError at
> /report/CDSEM/WaferAlignment/ajax/waChart.json Exception Value: 'module'
> object has no attribute 'strptime'
> 
> How can I do this sort?

datetime.datetime.strptime?

>>> import datetime
>>> datetime.strptime
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: module 'datetime' has no attribute 'strptime'
>>> datetime.datetime.strptime



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


Mutable global state and threads

2017-01-06 Thread Kev Dwyer
Hello List,

I came across some threading code in Some Other place recently and wanted to 
sanity-check my assumptions.

The code (below) creates a number of threads; each thread takes the last (index 
-1) value from a global list of integers, increments it by one and appends the 
new value to the list.

The originator of the code expected that when all the threads completed, the 
list would be an ascending sequence of integers, for example if the original 
list was [0] and two threads mutated it twice each, the final state would be 
[0, 1, 2, 3, 4].

Here is a version of the code (slightly simplified and modified to allow 
changing the number of threads and mutations).


import sys
import threading


class myThread(threading.Thread):

def __init__(self, nmutations):
threading.Thread.__init__(self)
self.nmutations = nmutations

def run(self):
mutate(self.nmutations)
# print (L)
return


def mutate(nmutations):
n = nmutations
while n:
L.append(L[-1 ]+ 1)
n -= 1
return


def main(nthreads=2, nmutations=2):
global L
L = [0]
threads = [myThread(nmutations) for i in range(nthreads)]
for t in threads:
t.start()
for t in threads:
t.join()
print(L)
assert L == list(range((nthreads * nmutations) + 1))

if __name__ == '__main__':
nthreads, nmutations = int(sys.argv[1]), int(sys.argv[2])
main(nthreads, nmutations)

Firstly, is it true that the statement

L.append(L[-1 ]+ 1)

is not atomic, that is the thread might evaluate L[-1] and then yield, allowing 
another thread to mutate L, before incrementing and appending?

Secondly, the original code printed the list at the end of a thread's run 
method to examine the state of the list.  I don't think this would work quite 
as expected, because the thread might yield after mutating the list but before 
printing, so the list could have been mutated before the print was executed.  
Is there a way to display the state of the list before any further mutations 
take place?

(Disclaimer: I understand that sanity, mutable global state and threads are 
unlikely bedfellows and so promise never to try anything like this in 
production code).

Cheers,

Kev

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


Mutable global state and threads

2017-01-03 Thread Kev Dwyer
Hello List,

I came across some threading code in Some Other place recently and wanted to 
sanity-check my assumptions.

The code (below) creates a number of threads; each thread takes the last 
(index -1) value from a global list of integers, increments it by one and 
appends the new value to the list.

The originator of the code expected that when all the threads completed, the 
list would be an ascending sequence of integers, for example if the original 
list was [0] and two threads mutated it twice each, the final state would be 
[0, 1, 2, 3, 4].

Here is a version of the code (slightly simplified and modified to allow 
changing the number of threads and mutations).


import sys
import threading


class myThread(threading.Thread):

def __init__(self, nmutations):
threading.Thread.__init__(self)
self.nmutations = nmutations

def run(self):
mutate(self.nmutations)
# print (L)
return


def mutate(nmutations):
n = nmutations
while n:
L.append(L[-1 ]+ 1)
n -= 1
return


def main(nthreads=2, nmutations=2):
global L
L = [0]
threads = [myThread(nmutations) for i in range(nthreads)]
for t in threads:
t.start()
for t in threads:
t.join()
print(L)
assert L == list(range((nthreads * nmutations) + 1))

if __name__ == '__main__':
nthreads, nmutations = int(sys.argv[1]), int(sys.argv[2])
main(nthreads, nmutations)

Firstly, is it true that the statement

L.append(L[-1 ]+ 1)

is not atomic, that is the thread might evaluate L[-1] and then yield, 
allowing another thread to mutate L, before incrementing and appending?

Secondly, the original code printed the list at the end of a thread's run 
method to examine the state of the list.  I don't think this would work 
quite as expected, because the thread might yield after mutating the list 
but before printing, so the list could have been mutated before the print
was executed.  Is there a way to display the state of the list before any 
further mutations take place?

(Disclaimer: I understand that sanity, mutable global state and threads are 
unlikely bedfellows and so promise never to try anything like this in 
production code).

Cheers,

Kev



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


Re: Why do these statements evaluate the way they do?

2016-05-07 Thread Kev Dwyer
Anthony Papillion wrote:

> I'm trying to figure out why the following statements evaluate the way
> they do and I'm not grasping it for some reason. I'm hoping someone can
> help me.
> 
> 40+2 is 42 #evaluates to True
> But
> 2**32 is 2**32 #evaluates to False
> 
> This is an example taken from a Microsoft blog on the topic. They say the
> reason is because the return is based on identity and not value but, to
> me, these statements are fairly equal.
> 
> Can someone clue me in?
> 
> Anthony

The *is* operator tests for identity, that is whether the objects on either 
side of the operator are the same object.

CPython caches ints in the range -5 to 256 as an optimisation, so ints in 
this range are always the same object, and so the is operator returns True.

Outside this range, a new int is created as required, and comparisons using 
is return False.

This can be seen by looking at the id of the ints:

Python 3.5.1 (default, Dec 29 2015, 10:53:52)   

[GCC 4.8.3 20140627 [gcc-4_8-branch revision 212064]] on linux  

Type "help", "copyright", "credits" or "license" for more information. 
>>> a = 42
>>> b = 42
>>> a is b
True
>>> id(a)
9186720
>>> id(b)
9186720
>>> c = 2 ** 32
>>> d = 2 ** 32
>>> c is d
False
>>> id(c)
140483107705136
>>> id(d)
140483107705168

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


Re: Help needed with compiling python

2015-11-26 Thread Kev Dwyer
Cecil Westerhof wrote:

> On Thursday 26 Nov 2015 09:29 CET, Steven D'Aprano wrote:
> 
>> On Thursday 26 November 2015 18:00, Cecil Westerhof wrote:
>>
>>> On Wednesday 25 Nov 2015 23:58 CET, Laura Creighton wrote:
>>>
 In a message of Wed, 25 Nov 2015 22:52:23 +0100, Cecil Westerhof
 writes:
>
> My system python was all-ready damaged: that is why I wanted to
> build myself.

 Your Suse system probably wants to use python for something. If
 your system python is damaged, you badly need to fix that, using
 the system package managers tools, before Suse does some sort of
 update on you, using the broken python, which damages more of your
 system.
>>>
>>> I tried that. But it installs only things in /usr/lib and
>>> /usr/lib64, nothing in /usr/bin, but at the same time it is adamant
>>> that it installed python. I wanted a quick fix, but it looks like
>>> that is not going to work. :'-( I'll have to find a way to get
>>> things fixed.
>>>
>>
>> On the assumption that you are more interested in fixing your broken
>> system than learning how to compile Python, what happens if you use
>> the Suse package manager to re-install Python?
>>
>> e.g. zypper python
> 
> It installs things in /usr/lib and /usr/lib64, but nothing in
> /usr/bin. So it installs libraries, but not programs.
> 
> 
> By the way: I am of-course most interested to fix my system, but I
> would not mind to have python compiled also, so I (can) work with the
> latest stable version. ;-)
> 

FWIW, I'm running OpenSuse 13.2 on a number of machines.  Pythons built
with make altinstall have the python executable placed in /usr/local/bin.

e.g.:

kev@pluto ~  which python3.5
/usr/local/bin/python3.5

kev@pluto ~  which python2.7
/usr/local/bin/python2.7


NB due to http://bugs.python.org/issue15631 I find I have to symlink 
lib-dynload to get a working python:

kev@pluto ~  ls -l /usr/local/lib/python3.5/lib-dynload
lrwxrwxrwx 1 root root 38 Sep 26 19:51 /usr/local/lib/python3.5/lib-dynload 
-> /usr/local/lib64/python3.5/lib-dynload

Having said that, I'd still recommend that you follow everyone else's advice 
and fix your system python/rebuild your OS.  Opensuse has not attempted to 
install python 2.7.9 on any of my (fully patched) machines, so something is 
wrong with your install, unless you're using Tumbleweed.

Cheers,

Kev

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


Re: PyPi bug?

2015-10-22 Thread Kev Dwyer
Nagy László Zsolt wrote:

> Today I have tried to register and upload a new package by executing
> 
> setup.py register
> 
> 
> I was asked if I want to save the creditentials in a .pypirc file and I
> answered yes.
> 
> Next I wanted to run
> 
> setup.py upload
> 
> and I got this error:
> 
> 
> Traceback (most recent call last):
>   File "C:\Python\Projects\some_package\setup.py", line 15, in 
> classifiers=['Topic :: Security', 'Topic :: Internet :: WWW/HTTP'],
>   File "C:\Python35\lib\distutils\core.py", line 148, in setup
> dist.run_commands()
>   File "C:\Python35\lib\distutils\dist.py", line 955, in run_commands
> self.run_command(cmd)
>   File "C:\Python35\lib\distutils\dist.py", line 973, in run_command
> cmd_obj.ensure_finalized()
>   File "C:\Python35\lib\distutils\cmd.py", line 107, in ensure_finalized
> self.finalize_options()
>   File "C:\Python35\lib\distutils\command\upload.py", line 46, in
> finalize_options
> config = self._read_pypirc()
>   File "C:\Python35\lib\distutils\config.py", line 83, in _read_pypirc
> current[key] = config.get(server, key)
>   File "C:\Python35\lib\configparser.py", line 798, in get
> d)
>   File "C:\Python35\lib\configparser.py", line 396, in before_get
> self._interpolate_some(parser, option, L, value, section, defaults, 1)
>   File "C:\Python35\lib\configparser.py", line 445, in _interpolate_some
> "found: %r" % (rest,))
> configparser.InterpolationSyntaxError: '%' must be followed by '%' or
> '(', found
> : *'
> 
> Instead of the many stars, of course there is the password. The problem
> might be that the password contains a % character, and it was
> incorrectly saved by distutils.
> 
> Can somebody please confirm that this is a bug in distutils? The we
> probably have to submit a bug report.
> 
> Thanks,
> 
>Laszlo


Could be http://bugs.python.org/issue20120 ?



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


Re: Cannot create a virtualenv

2015-09-14 Thread Kev Dwyer
paul.hermeneu...@gmail.com wrote:

> - I downloaded and installed Python 3.5 64-bit onto a Windows 7 64-bit
> machine. - Using `pip install virtualenv` worked fine.
> - Now, it is time to create a virtualenv, but it is not working fine.
> - I had to add Python 3.5 to the PATH.
> - Any suggestions?
> 
> C:\ve>virtualenv -p "\Program Files\Python 3.5\python.exe" ve33
> Running virtualenv with interpreter C:\Program Files\Python 3.5\python.exe
> Using base prefix 'C:\\Program Files\\Python 3.5'
> New python executable in ve33\Scripts\python.exe
> Installing setuptools, pip, wheel...
>   Complete output from command C:\ve\ve33\Scripts\python.exe -c
> "import sys, pip; sys...d\"] + sys.argv[1:]))" setuptools pip wheel:
>   Ignoring indexes: https://pypi.python.org/simple
> Collecting setuptools
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   The repository located at None is not a trusted or secure host and
> is being ignored. If this repository is available via HTTPS it is
> recommended to use HTTPS instead, otherwis
> e you may silence this warning and allow it anyways with '--trusted-host
> None'.
>   Could not find a version that satisfies the requirement setuptools
> (from versions: )
> No matching distribution found for setuptools
> 
> ...Installing setuptools, pip, wheel...done.
> Traceback (most recent call last):
>   File "c:\program files\python 3.5\lib\site-packages\virtualenv.py",
> line 2363, in 
> main()
>   File "c:\program files\python 3.5\lib\site-packages\virtualenv.py",
> line 832, in main
> symlink=options.symlink)
>   File "c:\program files\python 3.5\lib\site-packages\virtualenv.py",
> line 1004, in create_environment
> install_wheel(to_install, py_executable, search_dirs)
>   File "c:\program files\python 3.5\lib\site-packages\virtualenv.py",
> line 969, in install_wheel
> 'PIP_NO_INDEX': '1'
>   File "c:\program files\python 3.5\lib\site-packages\virtualenv.py",
> line 910, in call_subprocess
> % (cmd_desc, proc.returncode))
> OSError: Command C:\ve\ve33\Scripts\python.exe -c "import sys, pip;
> sys...d\"] + sys.argv[1:]))" setuptools pip wheel failed with error
> code 1


Have you tried using the venv module?

https://docs.python.org/3/library/venv.html

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


Re: No Content-Length header, nor length property

2015-07-08 Thread Kev Dwyer
zljubi...@gmail.com wrote:

 
 
 Hello,
 
 urlopen returns an HttpResponse
 object(https://docs.python.org/3/library/http.client.html#httpresponse-objects).
  You need to call read() on the return value to get the page content, or
 you could consider the getheader method to check for a Content- Length
 header.
 
 Hope that helps,
 
 Kev
 
 Kev, did you mean?
 
 import urllib.request
 
 url = 'http://radio.hrt.hr/prvi-program/aod/download/118467/'
 site = urllib.request.urlopen(url)
 
 print( site.getheader('Content-Length'))# None
 x = site.read(1)# No 'Content-Length' header
 
 print('File size:', site.length)
 
 I am still not getting anywhere. :(
 
 Regards.


Ah - looking at the response headers, they include Transfer-Encoding   
chunked - I don't think urlopen handles chunked responses by default, 
though I could be wrong, I don't have time to check the docs right now.

The requests library (https://pypi.python.org/pypi/requests) seems to handle 
them - 
http://docs.python-requests.org/en/latest/user/advanced/#chunk-encoded-requests



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


Re: No Content-Length header, nor length property

2015-07-07 Thread Kev Dwyer
zljubi...@gmail.com wrote:

 Hi,
 
 if I put the link in the browser, I will be offered to save the file to
 the local disk.
 
 If I execute these few lines of code, I will get None:
 
 import urllib.request
 
 url = 'http://radio.hrt.hr/prvi-program/aod/download/118467/'
 site = urllib.request.urlopen(url)
 print('File size:', site.length)
 
 Why I can't get the size of this particular file?
 On other servers, the same procedure would return file size in bytes, but
 not for this file?
 
 Does it depend on server itself, or there is a way to get remote file size
 before downloading?
 
 Regards.


Hello,

urlopen returns an HttpResponse 
object(https://docs.python.org/3/library/http.client.html#httpresponse-objects).
  You need to call read() on the return value to get the page 
content, or you could consider the getheader method to check for a Content-
Length header.

Hope that helps,

Kev

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


Re: mutual coaching

2015-06-25 Thread Kev Dwyer
adham...@gmail.com wrote:

 hello anyone wants to study python? we can learn together! pm me my name
 is adham128 iam at the #programming room

Welcome to Python!

To improve your chances of finding someone who wants to learn with you, you 
might try posting your message in the Python Tutor list too: 
https://mail.python.org/mailman/listinfo/tutor

Good luck!

Kev

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


Re: SSL Socket Error

2015-05-09 Thread Kev Dwyer
shdwkee...@gmail.com wrote:

 Ive setup a Debian server with Python 2.7.9.  Have everything running and
 SSL as well, but when I try and login to using HTTPS:// I get this error:
 
 Incoming web connection from ('192.168.15.177', 53202)
 error: uncaptured python exception, closing channel main.AlarmServer
 listening :8111 at 0x75ea7b48 (:certfile must be specified for
 server-side operations [/usr/lib/python2.7/asyncore.py|read|83]
 [/usr/lib/python2.7/asyncore.py|handle_read_event|443]
 [./alarmserver.py|handle_accept|456]
 [/usr/lib/python2.7/ssl.py|wrap_socket|891]
 [/usr/lib/python2.7/ssl.py|init|498])
 
 Any ideas how to resolve?

It looks like the exception is coming up through alarmserver.py, which seems 
to be based on https://github.com/juggie/AlarmServer (I'm not entirely
certain because the line numbers don't seem to match).  Anyway, looking at 
the code for alarmserver.py it expects to find certificate paths defined in
its config file, but they are undefined.

The sample config file for the project includes this section:

## The server runs with SSL. You need a certificate and key
## server.crt and server.key are included but you should 
## generate your own.
## If left blank the default included cert/key will be used
#certfile=/etc/apache2/ssl/server.crt
#keyfile=/etc/apache2/ssl/server.key
certfile=
keyfile=

So I think you need to start by examining the config file on your server.

Good luck,

Kev

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


Re: GAE environment differences

2015-05-02 Thread Kev Dwyer
Robin Becker wrote:

 On 01/05/2015 13:15, Chris Angelico wrote:
 On Fri, May 1, 2015 at 8:29 PM, Robin Becker ro...@reportlab.com wrote:


 Best thing to do is to ask the user to post the complete traceback.
 You might need to use import os.path but normally I would expect
 that not to be an issue.
 
 
 
 jamesbynd said:

 here's a traceback:

 ```
 #!python

 ImportError: No module named pwd
 (12 additional frame(s) were not displayed)
 ...
   File
   /base/data/home/apps/e~yt-maggi-2015-
eu/testing.383971015313322618/vendor/xhtml2pdf/context.py,
   line 5, in module
 from reportlab.lib.styles import ParagraphStyle
   File
   /base/data/home/apps/e~yt-maggi-2015-
eu/testing.383971015313322618/vendor/reportlab/lib/styles.py,
   line 28, in module
 from reportlab.rl_config import canvas_basefontname as _baseFontName,
 baseUnderlineProportion as _baseUnderlineProportion
   File
   /base/data/home/apps/e~yt-maggi-2015-
eu/testing.383971015313322618/vendor/reportlab/rl_config.py,
   line 131, in mod
  ule
 _startUp()
   File
   /base/data/home/apps/e~yt-maggi-2015-
eu/testing.383971015313322618/vendor/reportlab/rl_config.py,
   line 99, in _startUp
 d = os.path.expanduser(d)   #appengine fails with KeyError
   File python2.7/posixpath.py, line 268, in expanduser
 import pwd
 ```
 the user suggests that even though claims are made that you can use a
 filesystem, but stuff like pwd is missing. Apparently the user module has
 no meaning, but there is a users module? I guess I'll need to keep
 patching reportlab when GAE users find these glitches.

For what it's worth, we use reportlab on GAE to generate a simple pdf
and the above error is the only one that I've encountered.  For us it was 
enough to trap the ImportError.

Thanks for all your work on reportlab,

Kev

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


Re: téléchaegement

2015-03-14 Thread Kev Dwyer
peronin jean jacques wrote:

 Bonjour
 
 Je rencontre des problèmes d’ouverture de la console python . J’ai donc
 tout désinstallé. Je vous demande donc qu’elle version je dois installer à
 partir
 de votre site . J’utilise  Windows 8-1 sur PC portable.
 
 Merci . Cordialement.

Essayez pyt...@aful.org - python-list en francais si vous ne peut pas ecrire 
en anglais.

(et excusez ma francais pauvre, s'il vous plait)

Kev

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


Re: lxml objectify - attribute elements to list.

2015-02-08 Thread Kev Dwyer
Sayth Renshaw wrote:

 
 Hi
 
 How can I actually access the values of an element with lxml objectify?
 
 for example if I had this element in my xml file.
 
 Track VenueName=Flemington VenueDesc=Flemington VenueAbbr=FLEM
 VenueCode=151 TrackName=Main TrackCode=149
 
 I can see all the attributes using this.
 
 In [86]: for child in root.getchildren():
 print(child.attrib)
:
 {}
 {'RequestCode': '', 'RequestId': '0'}
 {}
 {}
 ...
 {}
 {}
 {}
 {'Category': 'Metro', 'AbrClubDesc': 'VRC', 'State': 'VIC', 'ClubCode':
 {'10018', 'Title': 'Victoria Racing Club'} 'TrackName': 'Main',
 {'VenueName': 'Flemington', 'TrackCode': '149', 'VenueAbbr': 'FLEM',
 {'VenueDesc': 'Flemington', 'VenueCode': '151'} } }
 ...
 
 Trying to access by attribs isn't working or me.
 
 In [90]: names = [p.text for p in root.Track.attrib['VenueName']]
 
---
 AttributeErrorTraceback (most recent call
 last) ipython-input-90-8e4bdae01d63 in module()
  1 names = [p.text for p in root.Track.attrib['VenueName']]
 
 AttributeError: 'str' object has no attribute 'text'
 
 
 What am I missing with this?
 
 Thanks
 
 Sayth


Hello

Is this what you're trying to do?

(tmp-179b92275909243d)kev@pluto ~/virtual-envs/tmp-179b92275909243d  python 

  
Python 3.4.1 (default, May 23 2014, 17:48:28) [GCC] on linux

  
Type help, copyright, credits or license for more information.  

  
 from lxml import objectify
 root = objectify.fromstring('rootTrack VenueName=Flemington 
VenueDesc=Flemington VenueAbbr=FLEM VenueCode=151 TrackName=Main 
TrackCode=149//root')
 root.Track
''
 root
Element root at 0x7f65c6965d08
 for child in root.getchildren():
... print(child.attrib)
... 
{'VenueCode': '151', 'TrackCode': '149', 'VenueName': 'Flemington', 
'VenueDesc': 'Flemington', 'TrackName': 'Main', 'VenueAbbr': 'FLEM'}
   
 for child in root.getchildren():
... print(child.get('VenueName'))
... 
Flemington
 

Cheers,

Kev


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


Re: OSError: [WinError 10022] An invalid argument was supplied in udp python file

2015-01-10 Thread Kev Dwyer
contro opinion wrote:

 When i test an udp.py file on server and client in python34.
 
 
 #!/usr/bin/env python
 import socket, sys
 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 MAX = 65535
 PORT = 1060
 if sys.argv[1:] == ['server']:
 s.bind(('127.0.0.1', PORT))
 print('Listening at', s.getsockname())
 while True:
   data, address = s.recvfrom(MAX)
   print('The client at', address, 'says', repr(data))
   s.sendto('Your data was %d bytes' % len(data), address)
 elif sys.argv[1:] == ['client']:
 print('Address before sending:',s.getsockname())
 s.sendto('This is my message',('127.0.0.1', PORT))
 print('Address after sending',s.getsockname())
 data, address = s.recvfrom(MAX)
 print('The server', address, 'says', repr(data))
 else:
   print('usage: udp_local.py server|client')
 
 
 The command `python udp.py server`  get output:
 Listening at ('127.0.0.1', 1060)
 
 Why   `python udp.py client`  run failure:
 
 Traceback (most recent call last):
   File d://udp.py, line 15, in module
 print('Address before sending:', s.getsockname())
 OSError: [WinError 10022] An invalid argument was supplied


Hello,

According to 
http://stackoverflow.com/questions/15638214/socket-error-invalid-argument-supplied,
 the client socket doesn't have an address at time
when you call s.getsocketname.  This raises an exception on Windows.

Removing the 'Address before sending' line will prevent the error.

As you're using Python3, you'll find that passing strings to s.sendto raises
a TypeError; you'll need to encode the strings as bytes.

Hope that helps,

Kev

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


Re: Google Maps and Python: creating a map, embedding it, adding images, videos, markers, using python

2014-12-18 Thread Kev Dwyer
Veek M wrote:

 I'm messing with Google-Maps. Is there a way I can create a map, embed it
 on a page (CSS/HTML/Javascript for this bit), and add images, videos,
 markers - using python? Any libraries available?

Hello,

Googling for google maps python client returns

https://developers.google.com/api-client-library/python/apis/mapsengine/v1 

as the first result...

HTH

Kev

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


Re: Google Appengine Proxy Post method error

2014-09-23 Thread Kev Dwyer
alextr...@googlemail.com wrote:

 So I got the Labnol Google Appengine proxy but it can't handle the Post
 method aka error 405.
 
 I need help adding this method to the script:
 
 mirror.py = http://pastebin.com/2zRsdi3U
 
 transform_content.py = http://pastebin.com/Fw7FCncA
 
 main.html = http://pastebin.com/HTBH3y5T
 
 All other files are just small files for appengine that don't carry
 sufficient code for this. Hope you guys can help.
 
 Thanks in advance :)


Hello,

Very broadly speaking, you need to add a post method to the MirrorHandler  
class, and in that method:

 - mung the request in a similar fashion to the get method
 - avoid caching the request (POST requests are not idempotent)
 - forward the altered request to the destination server
 - return the response to the original client


The labnol google-proxy githubpage lists a twitter account for support 
contact - http://twitter.com/labnol - so you could try asking there for more 
help.  Also check the docs for webapp2 and and Google App Engine 
(http://developers.google.com/appengine).  

Have fun,

Kev 

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


Re: login: optional

2014-07-30 Thread Kev Dwyer
John Bliss wrote:

 Noob here:
 
 Started new Python project via Google AppEngine which produced project
 files including:
 
 \app.yaml
 
 handlers:
 - url: /.*
   script: main.app
   secure: always
 
 Currently, navigating to project root forces me to authenticate with
 Google oAuth2 process. I'd like to turn that off so that I can navigate to
 project root without authenticating. Per:
 
 
https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Requiring_login_or_administrator_status
 
 ...I added:
 
 login: optional
 
 ...but that did not seem to make a difference. What am I doing wrong?

Hello,

I can't reproduce your problem on the dev server using this minimal setup:

app.yaml


application: test
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.* 
  script: main.app
  secure: always
  login: optional


main.py

import webapp2


class IndexHandler(webapp2.RequestHandler):

def get(self):
self.response.write('Hello world!')


app = webapp2.WSGIApplication([('/', IndexHandler)], debug=True)


Are you sure that there's nothing in your code or environment that could be 
causing the authentication challenge?

Cheers,

Kev



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


Re: Sorting list alphabetically

2014-04-29 Thread Kev Dwyer
Terry Reedy wrote:

 On 4/28/2014 2:33 AM, Kev Dwyer wrote:
 
 Hello Terry,

 Regarding your second point, my mistake in not checking the link:
 I'd seen a similar one elsewhere and assumed they were the same.

 This link should work:
 http://msdn.microsoft.com/en-us/library/hzz3tw78


 As to your first point, you're right, it seems setlocale(locale.LC_ALL,
 'en_US.UTF-8') doesn't work on Windows.
 
  From what I read of the link above and
 http://msdn.microsoft.com/en-US/goglobal/bb896001.aspx
 given therein, I am going to guess that .UTF-8 is not supported for any
 language.
 
 It seems the locale name needs to be one of the aliases provided
 at http://msdn.microsoft.com/en-us/library/39cwe7zf, so for example
 locale.setlocale(locale.LC_ALL, 'usa') returns
 'English_United States.1252'.

 Do you know if this is something people programming on Windows
 should just be aware of, or is there a case for a hint of some
 kind in the locale module documentation?
 
 *Definitely the latter. Perhaps you could open an issue with a specific
 suggestion.
 

Thanks! I'll try to write something up this weekend.

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


Re: Sorting list alphabetically

2014-04-28 Thread Kev Dwyer
Terry Reedy wrote:

 On 4/27/2014 6:40 AM, Kev Dwyer wrote:
 Igor Korot wrote:

 Hi, ALL,
 I need to perform a subj.
 Looking at the Google I found following thread with explanation:

 http://stackoverflow.com/questions/36139/how-do-i-sort-a-list-of-
strings-
 in-python

 However, doing this in my python shell produces an error:

 C:\Documents and Settings\Igor.FORDANWORK\My
 Documents\GitHub\webapppython Python 2.7.5 (default, May 15 2013,
 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
 Type help, copyright, credits or license for more information.
 import locale
 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
 Traceback (most recent call last):
File stdin, line 1, in module
File c:\python27\lib\locale.py, line 547, in setlocale
  return _setlocale(category, locale)
 locale.Error: unsupported locale setting


 What is wrong with this?

 Thank you.


 Hello Igor,

 Windows maintains it's own names for locales, so you need to
 supply the Windows name if you're workong on Windows.

 You might find these links helpful:

 http://stackoverflow.com/questions/19709026/how-can-i-list-all-available-
 windows-locales-in-python-console
 
 This one says to look at locale.locala_alias, but that is not helpful.
 
   for k, v in la.items():
 if v.startswith ('en') and 'UTF' in v:
 print(k,  # , v)
 
 universal.utf8@ucs4  #  en_US.UTF-8
 
 But that local does not work on my machine.
 
   locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
 Traceback (most recent call last):
File pyshell#20, line 1, in module
  locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
File C:\Programs\Python34\lib\locale.py, line 592, in setlocale
  return _setlocale(category, locale)
 locale.Error: unsupported locale setting
 
 locale.locale_alias must not be machine limited.
 
 https://mail.python.org/pipermail/python-list/2009-February/525427.html
 
 This merely says to look at a now dead link.
My mistake for not checking the link; this one works: 
http://msdn.microsoft.com/en-us/library/hzz3tw78
 

Hello Terry,

Regarding your second point, my mistake in not checking the link:
I'd seen a similar one elsewhere and assumed they were the same.

This link should work:
http://msdn.microsoft.com/en-us/library/hzz3tw78


As to your first point, you're right, it seems setlocale(locale.LC_ALL, 
'en_US.UTF-8') doesn't work on Windows.

It seems the locale name needs to be one of the aliases provided 
at http://msdn.microsoft.com/en-us/library/39cwe7zf, so for example
locale.setlocale(locale.LC_ALL, 'usa') returns 
'English_United States.1252'.

Do you know if this is something people programming on Windows
should just be aware of, or is there a case for a hint of some
kind in the locale module documentation?

Cheers,

Kev


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


Re: Sorting list alphabetically

2014-04-27 Thread Kev Dwyer
Igor Korot wrote:

 Hi, ALL,
 I need to perform a subj.
 Looking at the Google I found following thread with explanation:
 
 http://stackoverflow.com/questions/36139/how-do-i-sort-a-list-of-strings-
in-python
 
 However, doing this in my python shell produces an error:
 
 C:\Documents and Settings\Igor.FORDANWORK\My
 Documents\GitHub\webapppython Python 2.7.5 (default, May 15 2013,
 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
 Type help, copyright, credits or license for more information.
 import locale
 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
 Traceback (most recent call last):
   File stdin, line 1, in module
   File c:\python27\lib\locale.py, line 547, in setlocale
 return _setlocale(category, locale)
 locale.Error: unsupported locale setting

 
 What is wrong with this?
 
 Thank you.


Hello Igor,

Windows maintains it's own names for locales, so you need to 
supply the Windows name if you're workong on Windows.

You might find these links helpful:

http://stackoverflow.com/questions/19709026/how-can-i-list-all-available-
windows-locales-in-python-console

https://mail.python.org/pipermail/python-list/2009-February/525427.html

Cheers,

Kev

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


Re: extract from json

2014-03-07 Thread Kev Dwyer
teddyb...@gmail.com wrote:

 I can't find any example on how to do this.
 I have a json file like so:
 {bostock:
[{url:http://bl.ocks.org/mbostock/9360565,title:titleplaceholder,date:dateplaceholder},
 
{url:http://bl.ocks.org/mbostock/9265674,title:titleplaceholder,date:dateplaceholder},
 
{url:http://bl.ocks.org/mbostock/9265467,title:titleplaceholder,date:dateplaceholder},
 
{url:http://bl.ocks.org/mbostock/9234731,title:titleplaceholder,date:dateplaceholder},
 
{url:http://bl.ocks.org/mbostock/9232962,title:titleplaceholder,date:dateplaceholder},
 
 this goes on for more than 700 entries. only thing unique is the number at
 the end of the url. I am going to load the url in python, get the date and
 title and write it in the json itself. Right now I am stuck on just
 reading the url in the json. Here is my code:
 
 import json
 
 with open(bostock.json) as json_file:
 json_data = json.load(json_file)
 print(json_data)
 
 I have tried json_data[0], json_data.url and a few others I forget right
 now and it does not seem to work.
 
 I have already figured out how to get the title and date.
 First things first: How can i just get the url for each line of the above
 json file?


Hello 

Try:

Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2   

Type help, copyright, credits or license for more information.  


 import  json
 with open('/tmp/bostock.json') as f:
... json_data = json.load(f)
... 
 json_data
{u'bostock': [{u'url': u'http://bl.ocks.org/mbostock/9360565', u'date': 
u'dateplaceholder', u'title': u'titleplaceholder'}, {u'url': 
u'http://bl.ocks.org/mbostock/9265674', u'date': u'dateplaceholder', 
u'title': u'titleplaceholder'}, {u'url': 
u'http://bl.ocks.org/mbostock/9265467', u'date': u'dateplaceholder', 
u'title': u'titleplaceholder'}, {u'url': 
u'http://bl.ocks.org/mbostock/9234731', u'date': u'dateplaceholder', 
u'title': u'titleplaceholder'}, {u'url': 
u'http://bl.ocks.org/mbostock/9232962', u'date': u'dateplaceholder', 
u'title': u'titleplaceholder'}]}

 urls = [x['url'] for x in json_data['bostock']]
 urls
[u'http://bl.ocks.org/mbostock/9360565', 
u'http://bl.ocks.org/mbostock/9265674', 
u'http://bl.ocks.org/mbostock/9265467', 
u'http://bl.ocks.org/mbostock/9234731', 
u'http://bl.ocks.org/mbostock/9232962']

Python loads the json in the file into a dictionary.  In this case, the 
dictionary has a single key, 'bostock', and the value in the dictionary for 
that key is a list (of dictionaries).  

To get the urls, you need to get the list 

json_data['bostock']

 and then iterate over it's elements, getting the value for the key url for 
each one.  
This is what the list comprehension 

[x['url'] for x in json_data['bostock']]

does.

I hope that helps,

Kev


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


Re: Google app engine database

2014-02-23 Thread Kev Dwyer
glenn.a.is...@gmail.com wrote:

 Is there a way to make sure that whenever you're making google engine app
 iterations to a database that that info does not get wiped/deleted. 
 Please advise

It's not clear what you mean here; I'll guess that by iterations you mean
changes by database you mean the db or ndb datastore and by info you 
mean data stored in the datastore.  Apologies if this isn't so.

Appengine doesn't document any migration utilities to handle changes in your 
datastore schema, so you need to manage the effects of such changes 
yourself.

To ensure that you do not lose data when changing your model code, avoid 
making destructive changes to your models, i.e.

 - don't delete properties from a model
 - don't rename properties on a model 

If you must make these changes for some reason, you'll need to migrate the 
data somehow.

In my experience with Appengine, data is not actaully lost if you make 
destructive changes to your models, it becomes inaccessible becuae the 
property names it was stored under no longer exist on the model.  In theory 
you could access the data by adding the proprties back to the model or 
(maybe) by loading a different model definition in the remote shell, but 
this is not something that you would want to rely on in a production 
environment.

tl,dr: it's ok to add new properties to you models, but don't remove or 
rename properties.

Hope that helps,

Kev

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


Re: gotta love radio buttons

2014-01-05 Thread Kev Dwyer
eneskri...@gmail.com wrote:

 So, I'm having this radio button issue in tkinter:
 First I assign the IntVar:
 var = []
 while i  self.something:
 var.append(IntVar())
 i += 2
 Later on I use them, but I get this error:
 for r in var:
 helper = var[r].get()
 self.something_else[helper] += 1
 Then, this happens:
 Traceback (most recent call last):
   File F:\Portable Python 3.2.5.1\App\lib\tkinter\__init__.py, line
   1456, in __call__
 return self.func(*args)
   File (Not giving this), line 26, in submit_data
 helper = var[r].get()
 TypeError: list indices must be integers, not IntVar
 I'm willing to give additional info. Thank you in advance.


(untested)
for r in var:
helper = var[r.get()]

I think you need to call get on the IntVar instance to get an int that can 
be used to index the list.



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


Re: UTF-EBCDIC encoding?

2013-07-15 Thread Kev Dwyer
Joel Goldstick wrote:

 On Fri, Jul 12, 2013 at 3:12 PM, Skip Montanaro s...@pobox.com wrote:
 
  I can't help you.  I'm astonished.  Trying to imagine the work
 environment
  where this technology would be necessary

 http://www.iseriespython.com/app/ispMain.py/Start?job=Home

 Skip

 I remember the AS400 series.. although I never worked with one.  What kind
 of business still use that stuff? Is it for large corporation accounting,
 MIS stuff?
 
 

Some banks still run legacy systems on AS/400s, and I've seen them used for 
airline booking systems and retail POS.  



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


Re: splinter web browser simulator causing constant BSODs

2013-04-13 Thread Kev Dwyer
matt.topolin...@gmail.com wrote:

 Hello,
 
 I'm trying to torubleshoot this issue for a user I support. He is running
 the splinter web browser simulator trough Google Chrome, and it appears to
 be causing his workstation to constantly BSOD.
 
 His machine has the following hardware:
 
 Dual Xeon E5-2637 Processors
 NVIDIA Quadro 600 - connected to 3 24 LCDs via displayport
 24GB DDR3 ECC RAM
 Seagate ST2000DM001 2TB Data Drive
 Crucial 512GB SSD CT5-CT512M4SSD1 Boot drive
 Windows 7 x64 Enterprise
 
 We have experienced absolutely no BSODs when troubleshooting this machine
 ourselves, however we're obviously not running the software he uses. We've
 swapped out the motherboard and the video card, as the BSODs suggest an
 issue related to the PCI bus. I think this script is somehow causing his
 display driver to crash, or maybe the dual CPUs is an issue, but I don't
 know much about Python.
 
 Does anyone have any experience with this? Any additional help would be
 greatly appreciated.


Hello,

You might be better off asking at the splinter user list on Google Groups 
(https://groups.google.com/forum/?fromgroups#!forum/splinter-users).

I expect they might like to see some sopecifics on the BSOD too.

Cheers,

Kev

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


Re: Interesting list() un-optimization

2013-03-06 Thread Kev Dwyer
Roy Smith wrote:

 I stumbled upon an interesting bit of trivia concerning lists and list
 comprehensions today.
 
 We use mongoengine as a database model layer.  A mongoengine query
 returns an iterable object called a QuerySet.  The obvious way to
 create a list of the query results would be:
 
 my_objects = list(my_query_set)
 
 and, indeed, that works.  But, then I found this code:
 
my_objects = [obj for obj in my_query_set]
 
 which seemed a bit silly.  I called over the guy who wrote it and asked
 him why he didn't just write it using list().  I was astounded when it
 turned out there's a good reason!
 
 Apparently, list() has an optimization where it calls len() on its
 argument to try and discover the number of items it's going to put into
 the list.  Presumably, list() uses this information to pre-allocate the
 right amount of memory the first time, without any resizing.  If len()
 fails, it falls back to just iterating and resizing as needed.
 Normally, this would be a win.
 
 The problem is, QuerySets have a __len__() method.  Calling it is a lot
 faster than iterating over the whole query set and counting the items,
 but it does result in an additional database query, which is a lot
 slower than the list resizing!  Writing the code as a list comprehension
 prevents list() from trying to optimize when it shouldn't!


Interesting discovery.  Yet isn't this as much an issue with the mongoengine 
library as with list()?  Queryset.count() can be called if the length of a 
resultset needs to be retrieved, so the __len__() methd seems redundant.  
And given that it's not unheard of to call list() on iterables, perhaps the 
library designers should either optimise the __len__() method, or document 
the performance implications of calling list on the queryset? 

Anyway, thanks for this thought-provoking post.

Cheers,

Kev 

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


Re: test failed: test_urlwithfrag

2013-01-19 Thread Kev Dwyer
Terry Reedy wrote:

 On 1/7/2013 1:26 PM, Elli Lola wrote:
 
 $ ./python -m test -v test_urlwithfrag

 == CPython 3.3.0 (default, Jan 4 2013, 23:08:00) [GCC 4.6.3]
 ==   Linux-3.2.0-35-generic-pae-i686-with-debian-wheezy-sid little-endian
 ==   /home/me/Programme/Python/Python-3.3.0/build/test_python_30744
 Testing with flags: sys.flags(debug=0, inspect=0, interactive=0,
 optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
 ignore_environment=0, verbose=0, bytes_warning=0, quiet=0,
 hash_randomization=1)
 [1/1] test_urlwithfrag
 test test_urlwithfrag crashed -- Traceback (most recent call last):
File /home/me/Programme/Python/Python-3.3.0/Lib/test/regrtest.py,
 line 1213, in runtest_inner
  the_package = __import__(abstest, globals(), locals(), [])
 ImportError: No module named 'test.test_urlwithfrag'

 1 test failed:
  test_urlwithfrag
 
 Read the message I sent you before.
 
 (To everyone else, I already explained that the error message means
 exactly what it says and listed the test_url files that do exist. No
 need to repeat a third time.)
 

I encountered the OP's error message while building Python 3.3 today.

$ make test
snip

FAIL: test_urlwithfrag (test.test_urllib2net.OtherNetworkTests) 
 
--  
 
Traceback (most recent call last):  
 
  File /usr/src/packages/BUILD/Python-3.3.0/Lib/test/test_urllib2net.py, 
line 165, in test_urlwithfrag   
   
http://docs.python.org/glossary.html#glossary;)
 
AssertionError: 'http://docs.python.org/2/glossary.html' != 
'http://docs.python.org/glossary.html#glossary' 
  
- http://docs.python.org/2/glossary.html
 
?-- 
 
+ http://docs.python.org/glossary.html#glossary 
 
? +  

 

 
--  
 
Ran 15 tests in 15.307s 
 

 
FAILED (failures=1, skipped=1)  
 
test test_urllib2net failed 
 
make: *** [test] Error 1  


$ ./python -m test -v test_urllib2net   

== CPython 3.3.0 (default, Jan 19 2013, 13:46:53) [GCC 4.6.2]   
 
==   Linux-3.1.10-1.16-desktop-x86_64-with-SuSE-12.1-x86_64 little-endian   
 
==   /usr/src/packages/BUILD/Python-3.3.0/build/test_python_10447   
 
Testing with flags: sys.flags(debug=0, inspect=0, interactive=0, optimize=0, 
dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, 
verbose=0, bytes_warning=0, quiet=0, hash_randomization=1)  
  
[1/1] test_urllib2net   
 
test_urllib2net skipped -- Use of the 'network' resource not enabled
 
1 test skipped: 
 
test_urllib2net 
 
Those skips are all expected on linux. 


$ ./python -m test -v test_urlwithfrag  

== CPython 3.3.0 (default, Jan 19 2013, 13:46:53) [GCC 4.6.2]   
 
==   Linux-3.1.10-1.16-desktop-x86_64-with-SuSE-12.1-x86_64 little-endian   
 
==   /usr/src/packages/BUILD/Python-3.3.0/build/test_python_10453   
 
Testing with flags: sys.flags(debug=0, inspect=0, interactive=0, optimize=0, 
dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, 
verbose=0, bytes_warning=0, quiet=0, hash_randomization=1)  
  
[1/1] test_urlwithfrag  
 
test test_urlwithfrag crashed -- Traceback (most recent call last): 
 
  File /usr/src/packages/BUILD/Python-3.3.0/Lib/test/regrtest.py, line 
1213, in runtest_inner  
 
the_package = __import__(abstest, globals(), locals(), [])  
 
ImportError: No module named 'test.test_urlwithfrag'
 

 
1 test failed:   

Re: Regarding Jython support in IBM and HP platforms

2012-12-27 Thread Kev Dwyer
Naresh Kumar wrote:

 
 
 
 Hello,
 
 I am trying to use the Jython in IBM AIX and HP machines to test our
 framework which is based on JAVA. when trying to run our python and jython
 based testcases using system test framework we are getting below errors in
 jython.err file
 
 
 
 Error: could not find libjava.so
 
 Error: could not find Java 2 Runtime
 Environment.” (Shared library of java)
 
 
 
 Trying to find in online whether jython is supported on these two
 platforms HP and IBM and i could not able to get proper info. so could you
 please provide me the info like what are all platforms it
 supports(jython)? If not when do you guys are supporting on HP and IBM
 because java is pretty much support on all platforms and machine
 independent, so jython is similar like java.
 
 Thanks in advance,
 Naresh


Hello,

Jython is an implementation of the Python language in Java, so it will run 
on any platform that can run a JVM.

From the information that you have provided, it seems that Jython cannot 
find libjava.so.

The Jython docs suggest that Jython's behaviour can be influenced by the 
value of the environmental variable JAVA_HOME 
(http://www.jython.org/docs/using/cmdline.html#environment-variables).

Have you checked that $JAVA_HOME is set to a suitable value for the user 
that is running Jython?

My JAVA_HOME:

kev@pluto ~/Download  echo $JAVA_HOME   
  
/usr/lib64/jvm/java  

If I download the jython 2.5.3 jar and run a simple test script I get:

kev@pluto ~/Download  java -jar jython.jar jtest.py 
  
*sys-package-mgr*: processing new jar, '/home/kev/Download/jython.jar'  
  
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/resources.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/rt.jar'   
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/jsse.jar' 
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/jce.jar'  
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/charsets.jar' 
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/rhino.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/pulse-java.jar'   
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/gnome-java-bridge.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/sunpkcs11.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/localedata.jar'   
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/dnsns.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/swt.jar'  
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/sunjce_provider.jar'  
Hello Jython world!  

So I think you need to check your environment.

Cheers,

Kevin

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


Re: Suitable software stacks for simple python web service

2012-11-24 Thread Kev Dwyer
Steve Petrie wrote:

 On Thursday, November 22, 2012 1:42:42 AM UTC-5, Kev Dwyer wrote:
 Steve Petrie wrote:
 
 
 
  On Wednesday, November 21, 2012 2:32:40 AM UTC-5, Kev Dwyer wrote:
 
  Hello List,
 
  
 
  
 
  
 
  I have to build a simple web service which will:
 
  
 
  
 
  
 
   - receive queries from our other servers
 
  
 
   - forward the requests to a third party SOAP service
 
  
 
   - process the response from the third party
 
  
 
   - send the result back to the original requester
 
  
 
  
 
  
 
  From the point of view of the requester, this will happen within the
 
  scope
 
  
 
  of a single request.
 
  
 
  
 
  
 
  The data exchanged with the original requester will likely be encoded
  as
 
  
 
  JSON; the SOAP service will be handled by SUDS.
 
  
 
  
 
  
 
  The load is likely to be quite light, say a few requests per hour,
  though
 
  
 
  this may increase in the future.
 
  
 
  
 
  
 
  Given these requirements, what do you think might be a suitable
  software
 
  
 
  stack, i.e. webserver and web framework (if a web framework is even
 
  
 
  necessary)?
 
  
 
  
 
  
 
  Candidates should be compatible with Python2.7, though I'd be happy to
 
  
 
  consider Python 3 if anyone knows of a Python3 SOAP library that has
  good
 
  
 
  WSDL support.
 
  
 
  
 
  
 
  Cheers,
 
  
 
  
 
  
 
  Kev
 
  
 
  I'm using the Bottle web framework (http://bottlepy.org) to integrate
 
  requests and replies originating in a Drupal site, a Beanstream
  (payment
 
  processor) account, and a Salesforce instance.
 
  
 
  Communication with Salesforce is done through the Salesforce Python
 
  Toolkit (http://code.google.com/p/salesforce-python-toolkit/), which
  uses
 
  Suds.
 
  
 
  Communication with the Drupal site uses Python's (and PHP's on the
  Drupal
 
  side) native JSON support.
 
  
 
  This is under Python 2.6.8 and Apache 2.2.23 running on an AWS EC2
 
  instance.
 
  
 
  No (major) problems so far, though still in the early stages of this
 
  project.
 
  
 
  Steve
 
  
 
  
 
  
 
  I chose Bottle after trying a few other frameworks because, well, I
  can't
 
  remember exactly why, though thinking back it's probably because of the
 
  clarity of Bottle's approach and the simplicity of the documentation.
 
 
 
 
 
 Hello Steve,
 
 
 
 Thanks for  your comment.
 
 
 
 I'm curious, did you consider any web servers other than Apache?
 
 
 
 Kev
 
 You're telling me that there are other web servers? ;)
 
 I didn't try any others seriously, no.  My experience is with Apache and
 IIS, and I try to stay away from Windows.
 
 I should mention, given Dieter Maurer's comment, that Bottle is a (fairly
 thin) layer built over WSGI.  I've built applications directly over WSGI
 as well; that's another way to go, it's quite straightforward.  mod_python
 is no longer supported:
 http://blog.dscpl.com.au/2010/05/modpython-project-soon-to-be-
officially.html.


Based on Dieter's comment I'm using Bottle as a framework, with gunicorn 
(behind nginx) as the webserver.  Even Bottle is probably overkill for my 
use case, but my time is rather limited, so I'm happy to use an off the 
shelf solution.  And I must say, configuring gunicorn and nginx contrasted 
pleasantly with my memories of struggling with httpd.conf :)



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


Re: Suitable software stacks for simple python web service

2012-11-22 Thread Kev Dwyer
Dieter Maurer wrote:

snip
 
 From your description (so far), you would not need a web framework
 but could use any way to integrate Python scripts into a web server,
 e.g. mod_python, cgi, WSGI, 
 Check what ways your web server will suport.

Hello Dieter

Thanks for your comment.  I certainly want a lightweight solution so 
CGI or one of the micro-frameworks are what I am considering. 

Cheers

Kev

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


Re: Suitable software stacks for simple python web service

2012-11-21 Thread Kev Dwyer
Steve Petrie wrote:

 On Wednesday, November 21, 2012 2:32:40 AM UTC-5, Kev Dwyer wrote:
 Hello List,
 
 
 
 I have to build a simple web service which will:
 
 
 
  - receive queries from our other servers
 
  - forward the requests to a third party SOAP service
 
  - process the response from the third party
 
  - send the result back to the original requester
 
 
 
 From the point of view of the requester, this will happen within the
 scope
 
 of a single request.
 
 
 
 The data exchanged with the original requester will likely be encoded as
 
 JSON; the SOAP service will be handled by SUDS.
 
 
 
 The load is likely to be quite light, say a few requests per hour, though
 
 this may increase in the future.
 
 
 
 Given these requirements, what do you think might be a suitable software
 
 stack, i.e. webserver and web framework (if a web framework is even
 
 necessary)?
 
 
 
 Candidates should be compatible with Python2.7, though I'd be happy to
 
 consider Python 3 if anyone knows of a Python3 SOAP library that has good
 
 WSDL support.
 
 
 
 Cheers,
 
 
 
 Kev
 
 I'm using the Bottle web framework (http://bottlepy.org) to integrate
 requests and replies originating in a Drupal site, a Beanstream (payment
 processor) account, and a Salesforce instance.
 
 Communication with Salesforce is done through the Salesforce Python
 Toolkit (http://code.google.com/p/salesforce-python-toolkit/), which uses
 Suds.
 
 Communication with the Drupal site uses Python's (and PHP's on the Drupal
 side) native JSON support.
 
 This is under Python 2.6.8 and Apache 2.2.23 running on an AWS EC2
 instance.
 
 No (major) problems so far, though still in the early stages of this
 project.
 
 Steve
 
 
 
 I chose Bottle after trying a few other frameworks because, well, I can't
 remember exactly why, though thinking back it's probably because of the
 clarity of Bottle's approach and the simplicity of the documentation.


Hello Steve,

Thanks for  your comment.

I'm curious, did you consider any web servers other than Apache? 

Kev

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


Suitable software stacks for simple python web service

2012-11-20 Thread Kev Dwyer
Hello List,

I have to build a simple web service which will:

 - receive queries from our other servers
 - forward the requests to a third party SOAP service
 - process the response from the third party
 - send the result back to the original requester

From the point of view of the requester, this will happen within the scope 
of a single request.  

The data exchanged with the original requester will likely be encoded as 
JSON; the SOAP service will be handled by SUDS.

The load is likely to be quite light, say a few requests per hour, though 
this may increase in the future.

Given these requirements, what do you think might be a suitable software 
stack, i.e. webserver and web framework (if a web framework is even 
necessary)?  

Candidates should be compatible with Python2.7, though I'd be happy to 
consider Python 3 if anyone knows of a Python3 SOAP library that has good 
WSDL support.

Cheers,

Kev

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


Re: One of my joomla webpages has been hacked. Please help.

2012-09-22 Thread Kev Dwyer
Νίκος Γκρεεκ wrote:

 Τη Σάββατο, 22 Σεπτεμβρίου 2012 10:26:05 π.μ. UTC+3, ο χρήστης Peter Otten
 έγραψε:
 Νίκος Γκρεεκ wrote:
 
 
 
  One webpage of mine, http://www.varsa.gr/ has been *hacked* 15 mins
  ago.
 
 
 
  Please visit my web page varsa.gr and view the source code and maybe
  you
 
  can tell me what has happened.
 
 
 
 Do you use a password that was exposed in the other thread,
 
 
 
 http://mail.python.org/pipermail/python-list/2012-September/630779.html
 
 
 
 ?
 No, that was for another web page of mine utilizing python mysql
 connection, this was joomla only website which remind me to also ask if i
 can embed somwhow python code to joomla cms.


This is only speculation, as I don't know exactly how your web page has been 
hacked, but if your page somehow exposes a database connection, and the 
hack involves changing the contents of the database then you should read up 
on SQL injection attacks and how to prevent them. 

Cheers,

Kev

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


Re: How does python bytecode works?

2012-06-17 Thread Kev Dwyer
gmspro wrote:

 We know python is written in C.
 C is not portable.
 So how does python work on a webserver like apache/httpd for a python
 website? How does the intermediate language communicate with server
 without compiling python code? Or how does python interpreted code work
 with webserver for python based websites?
 
 Please elaborate/explain this topic with example.
 
 Thanks.

http://en.wikipedia.org/wiki/Bytecode

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


Re: How can i build python3 without optimization?

2012-06-17 Thread Kev Dwyer
gmspro wrote:

 I tried this:
 CFLAG=-g ./configure --prefix=/home/user/localdir
 
 But during debugging python i get:
 
 (gdb)next
 (gdb)print variable
 (gdb)$1 = value optimized out
 
 What should i do?
 How can i get the value of a variable instead of value optimized out ?
 
 Thanks.


Maybe try: http://docs.python.org/devguide/setup.html#compiling-for-
debugging

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


Re: Is there a custom fields plugin or component of django

2012-05-25 Thread Kev Dwyer
kevon wang wrote:

 I want to find a plugin of django what it can custom fields in the form.
 The functions include custom fields in web page and create the fields in
 database.
 
snip

You might have more luck getting an answer to this question on the django 
list (django-us...@googlegroups.com if you're using Google Groups).

Cheers

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


Re: How can I catch misnamed variables?

2012-02-10 Thread Kev Dwyer
John Gordon wrote:

 Recently I was been bitten by some stupid errors in my code, and I'm
 wondering if there's a simple way to catch them.
 
snip


Pyflakes is another static checker that can catch these sorts of errors.

Cheers,

Kev 


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


Re: log and figure out what bits are slow and optimize them.

2012-02-10 Thread Kev Dwyer
sajuptpm wrote:

 Hi,
 
 Yes i saw profile module,
 I think i have to do function call via
 
 cProfile.run('foo()')
 
 I know, we can debug this way.
 
 But, i need a fixed logging system and want to use it in production.
   I think, we can't permanently include profile's debugging code
 in source code,
  will cause any performance issue ??

*Any* instrumentation code is going to affect performance.

It's a trade-off that you need to analyse and manage in the context of your 
application.

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


Re: problem:emulate it in python with mechanize

2012-01-15 Thread Kev Dwyer
contro opinion wrote:

 you can do it by hand ,
 1.open
 http://www.flvcd.com/'
 2.input
 http://v.163.com/movie/2008/10/O/Q/M7F57SUCS_M7F5R3DOQ.html
 3.click  submit
 you can get
 http://mov.bn.netease.com/movie/2012/1/V/7/S7MKQOBV7.flv
 
 i want to  emulate it  in python with  mechanize,here is my code ,why i
 can't get  the  right result:
  http://mov.bn.netease.com/movie/2012/1/V/7/S7MKQOBV7.flv
 
 
 
 import mechanize
 import cookielib
 import lxml.html
 br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US;
 rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
 br = mechanize.Browser()
 br.set_handle_robots(False)
 
 r = br.open('http://www.flvcd.com/')
 for f in br.forms():
 print f
 br.select_form(nr=0)
 
br.form['kw']='http://v.163.com/movie/2008/10/O/Q/M7F57SUCS_M7F5R3DOQ.html'
 print  br.submit().read()
 
 why??

Hello,

I think the page uses javascript to submit the form, so mechanize may not 
work with it directly.

See 
http://stackoverflow.com/questions/3798550/python-mechanize-javascript-
submit-button-problem

for a similar problem and suggested workaround.

Cheers,

Kev

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


Re: About instance.name look up order

2011-12-29 Thread Kev Dwyer
Prim wrote:

 First, sorry about my poor english.
 Put these in IPython under ubuntu.
 
-
 class C:
 def __init__(self):
 self.x = 1
 def print(self):
 print self.x
 c = C()
 c.x -- 1, so c.x mean a attr of c named 'x'
 c.print() -- pirnt 1, so c.print mean a method of c named 'print'
 
-
 class C:
 def __init__(self):
 self.x = 1
 def x(self):
 print 'x method'
 def y(self):
 print 'y method'
 c = C()
 c.x -- 1
 c.x() -- TypeError: 'int' object is not callable
 c.y -- bound method C.y
 #Q1: instance.name will get the attr first, than method?
 
-
 class C:
 def x(self):
 print 'x method'
 def __getattr__(self, attr):
 print 'in __getattr__ method'
 return attr
 c = C()
 c.x -- print in __getattr__ method, then throw TypeError: 'str'
 object is not callable
 c.x() -- print in __getattr__ method, x method 2 lines
 #Q2: why c.x would get a exception?
 
 t = c.x
 t -- print in __getattr__ method, then throw TypeError: 'str' object
 is not callable
 t() -- print x method
 t = c.x() -- print x method, t == None
 #Q3 why t=c.x() and c.x() output different?
 
 #Q4, if when I define the class use property too, then instance.name
 look up order would be?
 
 Thanks for your reply.

Hello,

Python always looks for attributes in the instance first, then in the class,
and then in the class's superclasses.  In your first example, by defining
x in C.__init__ you are creating an instance attribute named x.  When 
the attribute c.x is requested, Python finds an attribute x in the 
instance and returns it; the method x is found in the class, but the 
attribute lookup does not proceed this far.

Try looking at C.__dict__ and c.__dict__ in the interpreter to see how the 
attributes are stored.  

See also 
http://docs.python.org/reference/datamodel.html#customizing-attribute-access

Cheers

Kev


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


Re: Bug in multiprocessing.reduction?

2011-12-18 Thread Kev Dwyer
Yaşar Arabacı wrote:

 You can see my all code below, theoritically that code should work I
 guess. But I keep getting this error:
 [SUBWARNING/MainProcess] thread for sharing handles raised exception :
 
---
 Traceback (most recent call last):
 File /usr/lib/python2.7/multiprocessing/reduction.py, line 127, in
 _serve send_handle(conn, handle_wanted, destination_pid)
 File /usr/lib/python2.7/multiprocessing/reduction.py, line 80, in
 send_handle
 _multiprocessing.sendfd(conn.fileno(), handle)
 OSError: [Errno 9] Bad file descriptor
 
---
 
 Do you see an error in my side, or is this a bug in Python?
 

Hello,

I don't know much about the multiprocessing module, so I won't speculate 
about bugs ;) however I can tell you that your code works with error on my 
machine:

kev@pluto:~ python mtest.py 
[DEBUG/MainProcess] created semlock with handle 140252275732480
[DEBUG/MainProcess] created semlock with handle 140252275728384
[DEBUG/MainProcess] created semlock with handle 140252275724288
[DEBUG/MainProcess] Queue._after_fork()
[DEBUG/Process-1] Queue._after_fork()
[INFO/Process-1] child process calling self.run()
[DEBUG/Process-2] Queue._after_fork()
[INFO/Process-2] child process calling self.run()
[DEBUG/Process-3] Queue._after_fork()
[INFO/Process-3] child process calling self.run()
[DEBUG/Process-4] Queue._after_fork()
[INFO/Process-4] child process calling self.run()
[DEBUG/Process-5] Queue._after_fork()
[INFO/Process-5] child process calling self.run()
[DEBUG/MainProcess] starting listener and thread for sending handles
[INFO/MainProcess] created temp directory /tmp/pymp-J3UxCe
[DEBUG/MainProcess] Queue._start_thread()
[DEBUG/MainProcess] doing self._thread.start()
[DEBUG/MainProcess] starting thread to feed data to pipe
[DEBUG/MainProcess] ... done self._thread.start()
Here socket._socketobject object at 0x87f980


Here was added to your print line by me.  Otherwise I ran your code as is, 
and sent the string Hello world to port 9090 from another console.

Hope that helps,

Kev

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


Re: how to run python-script from the python promt? [absolute newbie]

2011-12-18 Thread Kev Dwyer
nukeymusic wrote:

 How can I load a python-script after starting python in the
 interactive mode?
 I tried with
load 'myscript.py'
myscript.py
myscript
 
 but none of these works, so the only way I could work further until
 now was copy/paste line per line of my python-script to the
 interactive mode prompt
 I do know how to run the script non-interactively, but what I want to
 do is adding lines to the code I have written thus far in interactive
 mode.
 
 thanks in advance
 nukey

Hello,

You can make the code in your script available to the interpreter by typing 

import myscript

(assuming that you are running the interpreter in the same directory that 
contains myscript.py)

You can access functions, classes and other top-level objects in your script 
by prefixing their names with myscript and a dot (.) e.g. 
myscript.myfunc, myscript.MyClass, myscript.myvar

You can't really edit your script in the interpreter, but you can edit and 
save in a text editor and then type 

reload(myscript) 

in the interpreter to refresh its version of the myscript code.

N.B. when you import/reload your script the interpreter will immediately 
execute any code that is not enclosed in a function or class definition.

Cheers,

Kev

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


Re: Fwd: os.statvfs bug or my incompetence ?

2011-10-15 Thread Kev Dwyer
Peter G. Marczis wrote:

snip

Hello Peter,

Welcome to the list.

Have you tried calling statvfs from a C program?  What happens if you do?

Best regards,

Kev




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


Re: parse html:what is the meaning of //?

2011-09-16 Thread Kev Dwyer
alias wrote:

snip



 Highlighted options are in-the-money.
 (omit  something)
 there is only one difference between   code1 and code2  :
 in code1 is :   tds=table.xpath(tr[@valign='top']//td)
 in code2 is:   tds=table.xpath(//tr[@valign='top']//td)
 
 i want to know  why  the  //  make output  different?


This is an XPATH question, not really Python-related.

See http://www.w3schools.com/xpath/xpath_syntax.asp

Cheers,

Kev

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


Re: pairwise combination of two lists

2011-08-17 Thread Kev Dwyer
Yingjie Lin wrote:

 Hi Python users,
 
 I have two lists:
 
 li1 = ['a', 'b']
 li2 = ['1', '2']
 
 and I wish to obtain a list like this
 
 li3 = ['a1', 'a2', 'b1', 'b2']
 
 Is there a handy and efficient function to do this, especially when li1
 and li2 are long lists.
 I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly
 what I am looking for.
 
 Thank you.
 
 
 - Yingjie

Hello Yingjie,

This isn't exactly handy, but...

 import itertools
 a = ('a', 'b')
 b = (1, 2)
 [x + str(y) for (x, y) in itertools.product(*(a, b))]
['a1', 'a2', 'b1', 'b2']


Cheers,

Kev


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


Re: regarding session in python

2011-06-07 Thread Kev Dwyer
vipul jain wrote:

 hey i am new to python and i want to make a website using python .
 so for that i need a login page. in this login page i want to use the
 sessions... but i am not getting how to do it

The Python standard library doesn't include a session framework, but you 
can either use a web framework written in Python (Django is the most 
popular).

Cheers,

Kev


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


Re: IDLE doesn't start

2011-03-11 Thread Kev Dwyer
Ceonn Bobst wrote:

snip
 
 When I open a command prompt, and type:
 c:\python32\python.exe -m idlelib.idle
 
 The message that comes is as follows:
 
 Microsoft Windows XP [Version 5.1.2600]
 (C) Copyright 1985-2001 Microsoft Corp.
 C:\Documents and Settings\Ceonnc:\python32\python.exe -m 
idlelib.idle
 Traceback (most recent call last):
 File c:\python32\lib\runpy.py, line 160, in _run_module_as_main
 __main__, fname, loader, pkg_name)
 File c:\python32\lib\runpy.py, line 73, in _run_code
 exec(code, run_globals)
 File c:\python32\lib\idlelib\idle.py, line 11, in module
 idlelib.PyShell.main()
 File c:\python32\lib\idlelib\PyShell.py, line 1374, in main
 root = Tk(className=Idle)
 File c:\python32\lib\tkinter\__init__.py, line 1674, in __init__
 self.tk = _tkinter.create(screenName, baseName, className, 
interactive,
 want objects, useTk, sync, use)
 _tkinter.TclError: Can't find a usable init.tcl in the following
 directories: {C:\IBMTOOLS\Python22\tcl\tcl8.4}
 C:/IBMTOOLS/Python22/tcl/tcl8.5 c:/python3 2/lib/tcl8.5 
c:/lib/tcl8.5
 c:/lib/tcl8.5 c:/library c:/library c:/tcl8.5.9/libra ry
 c:/tcl8.5.9/library C:/IBMTOOLS/Python22/tcl/tcl8.4/init.tcl: 
version
 conflict for package Tcl: ha ve 8.5.9, need exactly 8.4
 version conflict for package Tcl: have 8.5.9, need exactly 8.4
 while executing
 package require -exact Tcl 8.4
 (file C:/IBMTOOLS/Python22/tcl/tcl8.4/init.tcl line 19)
 invoked from within
 source C:/IBMTOOLS/Python22/tcl/tcl8.4/init.tcl
 (uplevel body line 1)
 invoked from within
 uplevel #0 [list source $tclfile]
 
 Someone told me: “You certainly have a TCL_LIBRARY environment 
variable
 set on your system, it should be removed”.
 
 How do I remove TCL_LIBRARY, or do I change some numbers somewhere, 
and
 isn’t it risky to tinker with the Python settings already on my 
computer?
 
 Thanks for any help, I really would like to get going with Python!

Hello,

You have an older version of Python on your machine in C:/IBMTOOLS.  
It's likely that the TCL_LIBRARY is pointing to the version of TCL 
installed there, and this is causing problems for your more modern 
Python install.

You change change Windows environment variables using the instructions 
here: http://support.microsoft.com/kb/310519.  Changing the 
environment variable is the documented solution for this - see 
http://bugs.python.org/issue5528.

If you keep a note of the environment variable you can always 
reinstate it later.

You can find some comments about the purpose of the IBMTOOLS folder at 
http://forum.thinkpads.com/viewtopic.php?f=8t=216.

All the best,

Kev

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


Re: pyWin32 attempted installation; Error message: Skipping exchdapi: No library 'Ex2KSdk'

2011-01-02 Thread Kev Dwyer
On Sat, 01 Jan 2011 20:53:47 -0800, marceepoo wrote:

 I just downloaded pyWin32 (https://sourceforge.net/projects/pywin32/)
 and started to install it.
 
 I get these error msgs:
 
 Skipping exchange: No library 'Ex2KSdk' Skipping exchdapi: No library
 'Ex2KSdk' Skipping directsound: The header 'dsound.h' can not be located
 
 Does anyone have any suggestions about how to address this?
 
 Thanks,Marceepoo

Are you using the binary installer or building from source?

Cf 
http://stackoverflow.com/questions/4476764/pywin32-support-trouble-while-building-syntax-error

Cheers,

Kev

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


Re: **** httplib.InvalidURL: nonnumeric port ****

2010-12-20 Thread Kev Dwyer
On Tue, 21 Dec 2010 00:01:44 +0530, Anurag Chourasia wrote:

 import httplib
 help(httplib.HTTP)
Help on class HTTP in module httplib:

class HTTP
 |  Compatibility class with httplib.py from 1.5.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, host='', port=None, strict=None)

The constructor doesn't take a complete URL as an argument.  

Also, shouldn't you be using httplib.HTTPConnection?  The docs
 state that httplib.HTTP is for backward compatibility only.

Kev

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


Re: **** httplib.InvalidURL: nonnumeric port ****

2010-12-20 Thread Kev Dwyer
On Tue, 21 Dec 2010 01:00:36 +0530, Anurag Chourasia wrote:

Anurag,

HTTPConnection takes a host and a port number as arguments, not just a URL.

So you could construct your connection request like this:
conn = httplib.HTTPConnection('joule', 8041)

then use the request() method on the connection to make a PUT or GET request:
conn.request('PUT', url, body, headers)

Please read the documentation for the httplib module, and perhaps some basic 
material on how HTTP requests work.

Cheers,

Kev

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


Re: If/then style question

2010-12-17 Thread Kev Dwyer
On Thu, 16 Dec 2010 21:49:07 +, John Gordon wrote:

 (This is mostly a style question, and perhaps one that has already been
 discussed elsewhere.  If so, a pointer to that discussion will be
 appreciated!)
 
 When I started learning Python, I wrote a lot of methods that looked
 like this:
 
 
   def myMethod(self, arg1, arg2):
 
 if some_good_condition:
 
   if some_other_good_condition:
 
 if yet_another_good_condition:
 
   do_some_useful_stuff()
   exitCode = good1
 
 else:
   exitCode = bad3
 
   else:
 exitCode = bad2
 
 else:
   exitCode = bad1
 
 return exitCode
 
 

Another way to look at this is as question of object-oriented style, as you
 are using a method in your example...

Arguably, rather than branching your code based on the arguments being 
passed to your method, you can embody the required behaviour in subclasses
of your class, and at runtime just use an object that does the right 
thing.  Of course, you end up writing the same branching in some factory 
object instead, but at least it isn't cluttering up your business logic 
any longer.  Trying to write an OO-style program without using any if 
statements in the business logic can be an interesting exercise, albeit 
not a terribly realistic one.

Apologies if your choice of a method for your example was entirely
incidental to your question :)

Kev

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


Re: python test frameworks

2010-11-08 Thread Kev Dwyer
On Sun, 07 Nov 2010 09:01:42 -0800, rustom wrote:

 On Nov 7, 7:09 pm, Kev Dwyer kevin.p.dw...@gmail.com wrote:
 On Sun, 07 Nov 2010 10:56:46 +0530, Rustom Mody wrote:
  There are a large number of test frameworks in/for python.  Apart
  from what comes builtin with python there seems to be nose, staf,
  qmtest etc etc.

  Is there any central place where these are listed with short
  descriptions? 'Test framework' means widely different things in
  different contexts. Any explanations/tutorials around?

  [Disclaimer: I was educated a couple of decades before the TDD rage]

 Hello,

 You could start
 withhttp://pycheesecake.org/wiki/PythonTestingToolsTaxonomy

 Kev
 
 Thanks -- that looks like a comprehensive resource.  But it does not
 have staf
 http://staf.sourceforge.net/current/STAFPython.htm. Is that merely an
 item missing or a category?

I'm afraid I couldn't say with any certainty - I'd throw that question 
at the python testing newsgroup, to whom I am cross-posting in the hope 
that they can help.

Kev

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


Re: python test frameworks

2010-11-07 Thread Kev Dwyer
On Sun, 07 Nov 2010 10:56:46 +0530, Rustom Mody wrote:

 There are a large number of test frameworks in/for python.  Apart from
 what comes builtin with python there seems to be nose, staf, qmtest etc
 etc.
 
 Is there any central place where these are listed with short
 descriptions? 'Test framework' means widely different things in
 different contexts. Any explanations/tutorials around?
 
 [Disclaimer: I was educated a couple of decades before the TDD rage]

Hello,

You could start with http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy

Kev

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


Re: What people are using to access this mailing list

2010-11-06 Thread Kev Dwyer
On Wed, 03 Nov 2010 11:17:32 +, Steven D'Aprano wrote:

 On Wed, 03 Nov 2010 08:02:29 +, John Bond wrote:
 
 Hope this isn't too O/T - I was just wondering how people read/send to
 this mailing list, eg. normal email client, gmane, some other software
 or online service?
 
 Usenet via my ISP, on comp.lang.python.

news.gmane.org, using Pan.

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


Re: Simple logging example doesn't work!

2010-10-18 Thread Kev Dwyer
On Mon, 18 Oct 2010 11:52:36 -0700, robinsieb...@gmail.com wrote:

 Here is an example straight out of the help, and for some reason, it is
 not working. I get the error messages in the log, but I do not get the
 info messages in the console.
 

Hello,

I don't see this code in the help; nevertheless, your code will work 
if you set the logging level in the logging.basicConfig() call to 
logging.INFO or lower.

I suggest that you start by trying to output to just one handler,
and play around with that before trying to configure multiple
handlers.

Sorry not to be more helpful, but it's late here.

Cheers (apologetically),

Kev

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


Re: Making logging.getLogger() simpler

2010-09-19 Thread Kev Dwyer
On Sun, 19 Sep 2010 02:35:15 +1000, Lie Ryan wrote:

 I was expecting this to work:
 
   import logging
   logger = logging.getLogger(__name__)
   logger.warn('this is a warning')
 
 instead it produced the error:
 
   No handlers could be found for logger __main__
 
 
 However, if instead I do:
 
   import logging
   logging.warn('creating logger')
   logger = logging.getLogger(__name__)
   logger.warn('this is a warning')
 
 then it does work.
 
 Is there any reason why getLogger()-created logger shouldn't
 automatically create a default handler?

Hello Lie,

Calling logging.warn(), or logging.debug() etc. before handlers 
have been assigned to the root logger will result in 
logging.basicConfig() being called automatically.  By default a 
StreamHandler will be created on the root logger and your logger 
inherits the StreamHandler.  So you can avoid the No handlers...
warning by calling logging.basicConfig() before your program
does any logging.

I don't know why getLogger() doesn't so something similar when
it's called.  Perhaps so that the logger is explicitly 
initialised with basic, file or dictConfig?

Cheers,

Kev


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


Re: develop for Windows on GNU/Linux, using Python

2010-09-19 Thread Kev Dwyer
On Sun, 19 Sep 2010 12:55:43 -0500, Default User wrote:

 Consider:
 
 Can someone do development of programs for use on Windows systems, but
 developed totally on a GNU/Linux system, using standard, contemporary 32
 and / or 64-bit PC hardware?
 
 This would be for someone who can not or will not use Windows, but wants
 to create software for those who do.
 
 This might not include the use of VM for developing on GNU/Linux, as
 that would seem to require a Windows installation disk, which the
 developer may not be able or willing to obtain and use.
 
 Is the correct answer:
 1)  no.
 2) yes.
 3) yes, a Hello World program will run just fine on the Windows Python
 interpreter.
 4) other.

Hello,

The answer is it depends, or 4 on your list of responses.

You can write pure python on a Linux machine and it will run fine on 
Windows as long as you've taken care to program in a portable fashion.

However, writing the code isn't everything.  To be confident that your
code is good you need to test it on a Windows box (we all test, right?).
If you want to distribute your application to non-developers you'll 
need to wrap it in a Windows installer; if you have C-extensions in
your code you'll need to compile them over Windows.  If you want to
program against the Windows API you'll need access to a Windows box.

So, if you really want to develop code for Windows (or cross-platform
code) I think you need to bite the bullet and get access to a Windows 
(virtual) machine.

Cheers,

Kev  

PS - You might be able to get away with using an emulator like WINE,
but given the ubiquity of Windows in business/home computing I think
you're better of testing on the real thing.

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


Re: question about pdb assignment statements

2010-08-16 Thread Kev Dwyer
On Mon, 16 Aug 2010 08:17:20 -0700, Steve Ferg wrote:

 In this little script:
 
  pre
  import pdb
  pdb.set_trace()
  def main():
  xm = 123
  print(Hello,world!)
  main()
  /pre
 
 When I run this, I use pdb to step through it until I reach the point in
 main() where the xm variable has been initialized, and then I try to use
 pdb to reset the value of xm, and I can't.
 
 Does anybody know why?
 
 As I understand the documentation, 
 http://docs.python.org/library/pdb.html I *should* be able to do this.
 
  [!]statement
  Execute the (one-line) statement in the context of the current stack
 frame.
 
 Is there something about in the context of the current stack frame
 that I don't understand?  Or is it a bug (or a limitation) in pdb?

I think this may be the issue raised in bug 5215
(http://bugs.python.org/issue5215), committed in r71006.  Displaying a 
changed variable using the p command reverts the variable to its
previous value.

If you try

pdb.set_trace()
def main():
xm = 123
print(Hello,world!)
print xm

and change xm before it's printed (but do not display using p)
it seems to work as expected.

Hope that helps,

Kev




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


Re: question about pdb assignment statements

2010-08-16 Thread Kev Dwyer
On Mon, 16 Aug 2010 08:17:20 -0700, Steve Ferg wrote:

 In this little script:
 
  pre
  import pdb
  pdb.set_trace()
  def main():
  xm = 123
  print(Hello,world!)
  main()
  /pre
 
 When I run this, I use pdb to step through it until I reach the point in
 main() where the xm variable has been initialized, and then I try to use
 pdb to reset the value of xm, and I can't.
 
 Does anybody know why?
 
 As I understand the documentation, 
 http://docs.python.org/library/pdb.html I *should* be able to do this.
 
  [!]statement
  Execute the (one-line) statement in the context of the current stack
 frame.
 
 Is there something about in the context of the current stack frame
 that I don't understand?  Or is it a bug (or a limitation) in pdb?

I should have added my version:

Python 2.6.2 (r262:71600, Jun 17 2010, 13:37:45) 
[GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2

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


Re: Is it possible to use re2 from Python?

2010-03-15 Thread Kev Dwyer
On Sun, 14 Mar 2010 14:40:34 -0700, _wolf wrote:

 There's a recent thread about this on the python-dev list,
 
 pointers? i searched but didn’t find anything.

http://mail.python.org/pipermail/python-dev/2010-March/098354.html

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


Re: Is it possible to use re2 from Python?

2010-03-14 Thread Kev Dwyer
On Sun, 14 Mar 2010 08:57:36 -0700, _wolf wrote:


 
 how can i use re2 from Python?
 

Hello Wolf,

There's a recent thread about this on the python-dev list, 
Unfortunately it seems to suggest that there are no Python
bindings at present.

Cheers,

Kev



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


Re: Python 2.6 and modules dbi AND odbc

2010-03-11 Thread Kev Dwyer
On Wed, 10 Mar 2010 16:17:29 -0800, robert somerville wrote:

 hi;
  i am trying to get some legacy python code (which i no nothing about)
 working with tries to import dbi and odbc (the import fails ...) it
 looks like these modules are deprecated ?? if so is there a work around
 , if not deprecated, what am i doing wrong ?? i see no Ubuntu packages
 that look promising ..
 
Hello Robert,

These modules are distributed as part of the PyWin32 Python for Windows
 extensions, so they need to run on a Windows box.  They'll run fine 
there regardless of the deprecation of dbi (though import dbi will 
provide a useful warning message).

Pyodbc is a possible alternative.

Cheers,

Kev

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


Re: Configuring apache to execute python scripts using mod_python handler

2010-02-12 Thread Kev Dwyer
On Fri, 12 Feb 2010 13:08:59 -0400, Juan Carlos Rodriguez wrote:

Hello Juan Carlos,

You're better off raising this on the mod_python list, however...

Python is looking for a module called mptest, and cannot find it.

Have you created the mptest.py module? (It should contain the handler function 
in your item (2)).

Is it on the python path used by the webserver?  See for example the last post
at 
http://forums.devshed.com/apache-development-15/installing-python-on-apache-42184.html
 
which shows how you can set up the path.

Cheers, 

Kev


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


Re: Checking the coding style

2010-02-07 Thread Kev Dwyer
On Sun, 07 Feb 2010 19:36:10 +0100, Pablo Recio Quijano wrote:

 Hi!
 
 I'm finishing a project writen in Python, and I realize about the
 document PEP8 - Style Guide for Python Code [1].
 
 Is there any app or script that checks if my project pass that style
 guide? I also worked with Drupal, and I know there is some modules and
 scripts that checks its coding standars [2] and it's very usefull to
 clean the code.
 
 Thanks in advance!
 
 [1] http://www.python.org/dev/peps/pep-0008/ [2]
 http://drupal.org/coding-standards

Hello Pablo,

The pep8 package (http://pypi.python.org/pypi/pep8) can do this, though 
I have never used it myself.  PyLint is a customisable static analysis
program that checks style among other things.

Cheers,

Kev

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


Re: Nim game being created, no GUI used... Need tips...

2010-02-06 Thread Kev Dwyer
On Fri, 05 Feb 2010 21:54:48 -0600, Jordan Uchima wrote:

Hello Jordan,

You could try something like this (not tested, and maybe I don't 
quite get the rules):


Nim game.

In response to question on c.l.p.



# Start with pot of thirteen pieces and two players.
# Each player takes 1 - 4 pieces each turn.
# Player who takes the last piece loses.


# Declare constants.
NUMBER_OF_PLAYERS = 2
TOTAL_PIECES_AT_START = 13

# Declare functions.

def rules():
Print the rules of the game.
print 'Some rules'

def get_players():
Get the names of the players.
# Let's put the player's names in a list.
players = []
# Looping like this saves us repeating lines of code for each player.
for player in range(NUMBER_OF_PLAYERS):
name = raw_input(Hello Player %d, what is your name?\n % player)
players.append(player)
return players

def take_turn(player):
Handle a player's turn.
# Turn logic goes here.
# Left as an exercise :)
the_remaining_number_of_pieces_after_this_turn = 1
return the_remaining_number_of_pieces_after_this_turn


def main():
Run the game.
# Display the rules by calling rules function.
rules()
# Get the players by calling the get_players function.
players = get_players()
# Set up the game.
remaining_pieces = TOTAL_PIECES_AT_START
playing = True
# Main loop - let's play!
while playing:
# Take turns.
for player in players:
remaining_pieces = take_turn(player)
# Check if this player has lost.
if remaining_pieces == 0:
# Player has taken last piece.
print 'Sorry %s, you have lost.' % player
# Break out of the loop
playing = False
break


# Automatically run main function if we're run as a script.
if __name__ == '__main__':
main()

# End.

The while loop in the main function runs the game until a winner
(or loser in this case) is declared.  The for loop within the while 
loop handles the alternation of turns.  Have a look at the python 
tutorial at http://docs.python.org/tutorial/index.html for more on 
while and for statements.

Use functions to break up the code into related sections.  Check out 
the tutorial material for functions too.

This skeleton should give you a starting structure for your program.

Have fun :)

Kev


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


Re: Importing bitly.py in twitter-gedit.py

2009-12-31 Thread Kev Dwyer
On Thu, 31 Dec 2009 10:28:55 +0530, Vikash Dhankar wrote:

 Hi,
 I am newbie in the python, I am stuck into a small problem.
 
 Me and my friend are working on the gedit based Twitter plugin.
 http://code.google.com/p/gedit-twitter-plugin/
 
 Now I want to add the tiny URL thing into this. I am using the bitly API
 for this.
 Its is already available in the python bitly.py
 http://code.google.com/p/python-bitly/
 
 now i want to use this bitly.py into the main file ( importing the
 bitly.py to the twitter_gedit.py) .
 
 One thing more, bitly.py uses the django.utils so you can download that
 from http://www.djangoproject.com/download/
 
 Thanks. its open

snip

Hello Vikash,

Perhaps you could tell exactly what the problem is?

Best regards,

Kevin

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


Re: Help with invoking standard mail app in windows

2009-12-19 Thread Kev Dwyer
On Sat, 19 Dec 2009 06:36:32 +1100, Astan Chee wrote:

 Kev Dwyer wrote:
 Hello Astan,

 Your code executes without error for me on Win98 (!) with Python 2.5 or
 XP with Python 2.6.

 It would help people to help you if you could provide the *exact*
 console output from when you try to execute the code, *including* the
 traceback. That way we can work out which line of code is hitting the
 exception.

 Cheers,

 Kev


 Hi,
 My mistake. The length of body is over 1400 characters. Here is my
 updated code and result:
 
 import urllib, webbrowser, win32api
 def mailto_url(to=None,subject=None,body=None,cc=None):
 
 encodes the content as a mailto link as described on
 http://www.faqs.org/rfcs/rfc2368.html  url = mailto:  +
 urllib.quote(to.strip(),@,) sep = ?
 if cc:
 url+= sep + cc= + urllib.quote(cc,@,) sep = 
 if subject:
 url+= sep + subject= + urllib.quote(subject,) sep = 
 if body:
 # Also note that line breaks in the body of a message MUST be #
 encoded with %0D%0A. (RFC 2368)
 body=\r\n.join(body.splitlines())
 url+= sep + body= + urllib.quote(body,) sep = 
 return url
 
 txtTo = t...@com.com
 txtSubject = Test Subject
 body = Test body
 for t in range(278):
 body+=test 
 txtCC = cc_t...@com.com
 
 url = mailto_url(txtTo,txtSubject,body,txtCC)
 #win32api.ShellExecute(0,'open',url,None,None,0)
 webbrowser.open(url,new=1)
 # os.startfile(url)
 
 result:
 
 Traceback (most recent call last):
   File C:/stanc_home/python/mail_test.py, line 32, in module
 webbrowser.open(url,new=1)
   File C:\Python25\lib\webbrowser.py, line 61, in open
 if browser.open(url, new, autoraise):
   File C:\Python25\lib\webbrowser.py, line 518, in open
 os.startfile(url)
 WindowsError: [Error 5] Access is denied: 'mailto:
 t...@com.com?cc=cc_test@com.comsubject=Test%20Subjectbody=Test%
snip
 
 Is there some sort of limitation here? If I shorten the string, it works
 fine. You're right, but I'm wondering if there is a way to go around
 this limitation.
 Thanks again
 Cheers
 Astan


Hello Astan,

After a bit of experimentation I find I get the same problem on XP using 
2.6 for len(body)  1973, using the os.startfile method.  Some light 
googling suggests this is probably a limit within Outlook itself.

If you just want a way to start Outlook programmatically you may be able 
to work around this by automating Outlook - try googling python outlook 
automation.

If you want to start a default mail client on any machine using the 
mailto protocol then you'll have to limit the size of your message 
bodies.  You may find that other mail clients have limits too - I doubt 
that any client (or browser) will accept urls of unlimited size.

Cheers,

Kev

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


Re: Help with invoking standard mail app in windows

2009-12-18 Thread Kev Dwyer
On Sat, 19 Dec 2009 04:56:34 +1100, Astan Chee wrote:

 Hi,
 I don't know if my last mail made it or not but here it is again. I'm
 trying to launch standard mail app in windows and after looking around
 most look like this:
 
 import urllib, webbrowser, win32api
 def mailto_url(to=None,subject=None,body=None,cc=None):
 
 encodes the content as a mailto link as described on
 http://www.faqs.org/rfcs/rfc2368.html 
 url = mailto:  + urllib.quote(to.strip(),@,) sep = ?
 if cc:
 url+= sep + cc= + urllib.quote(cc,@,) sep = 
 if subject:
 url+= sep + subject= + urllib.quote(subject,) sep = 
 if body:
 # Also note that line breaks in the body of a message MUST be #
 encoded with %0D%0A. (RFC 2368)
 body=\r\n.join(body.splitlines())
 url+= sep + body= + urllib.quote(body,) sep = 
 return url
 
 url = mailto_url(txtTo,txtSubject,body,txtCC) #
 win32api.ShellExecute(0,'open',url,None,None,0)
 webbrowser.open(url,new=1)
 # os.startfile(url)
 
 all of these are having WindowsError : [Error 5] Access is denied
 errors. I'm using windows xp and python 2.5. I have outlook 2007
 installed as a default mail client. Clicking on any mailto links in html
 brings up the normal write mail from the mail client. Any ideas why this
 is happening or how do I debug what access is being denied? Thanks for
 any help
 Astan

Hello Astan,

Your code executes without error for me on Win98 (!) with Python 2.5 or 
XP with Python 2.6.  

It would help people to help you if you could provide the *exact* console 
output from when you try to execute the code, *including* the traceback.  
That way we can work out which line of code is hitting the exception.

Cheers,

Kev

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


Re: Help with invoking standard mail app in windows

2009-12-18 Thread Kev Dwyer
On Sat, 19 Dec 2009 06:36:32 +1100, Astan Chee wrote:

 Kev Dwyer wrote:
 Hello Astan,

 Your code executes without error for me on Win98 (!) with Python 2.5 or
 XP with Python 2.6.

 It would help people to help you if you could provide the *exact*
 console output from when you try to execute the code, *including* the
 traceback. That way we can work out which line of code is hitting the
 exception.

 Cheers,

 Kev


 Hi,
 My mistake. The length of body is over 1400 characters. Here is my
 updated code and result:
 
 import urllib, webbrowser, win32api
 def mailto_url(to=None,subject=None,body=None,cc=None):
 
 encodes the content as a mailto link as described on
 http://www.faqs.org/rfcs/rfc2368.html  url = mailto:  +
 urllib.quote(to.strip(),@,) sep = ?
 if cc:
 url+= sep + cc= + urllib.quote(cc,@,) sep = 
 if subject:
 url+= sep + subject= + urllib.quote(subject,) sep = 
 if body:
 # Also note that line breaks in the body of a message MUST be #
 encoded with %0D%0A. (RFC 2368)
 body=\r\n.join(body.splitlines())
 url+= sep + body= + urllib.quote(body,) sep = 
 return url
 
 txtTo = t...@com.com
 txtSubject = Test Subject
 body = Test body
 for t in range(278):
 body+=test 
 txtCC = cc_t...@com.com
 
 url = mailto_url(txtTo,txtSubject,body,txtCC)
 #win32api.ShellExecute(0,'open',url,None,None,0)
 webbrowser.open(url,new=1)
 # os.startfile(url)
 
 result:
 
 Traceback (most recent call last):
   File C:/stanc_home/python/mail_test.py, line 32, in module
 webbrowser.open(url,new=1)
   File C:\Python25\lib\webbrowser.py, line 61, in open
 if browser.open(url, new, autoraise):
   File C:\Python25\lib\webbrowser.py, line 518, in open
 os.startfile(url)
 WindowsError: [Error 5] Access is denied: 'mailto:
 t...@com.com?cc=cc_test@com.comsubject=Test%20Subjectbody=Test%
20bodytest%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20t
  est%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20te
  st%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20tes
  t%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test
%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test
  %20test%20test%20test%20test%20test%20'
 
 Is there some sort of limitation here? If I shorten the string, it works
 fine. You're right, but I'm wondering if there is a way to go around
 this limitation.
 Thanks again
 Cheers
 Astan

Hmmm.

For me, body  1400 opens an outlook message form, body  1400 opens IE7.

No time to look into this right now, but perhaps this is a windows thing.

Don't know why you get windowserror, perhaps permissions???

I'll try and look again later/tomorrow.

Cheers,

Kev

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


Re: Problem w/ smtplib

2009-11-21 Thread Kev Dwyer
On Sat, 21 Nov 2009 08:19:52 -0500, Victor Subervi wrote:

Hello Victor,

The information that you have sent comes from the client side of the 
transaction, so it isn't possible to tell why the server disconnected.  
Assuming that there is an SMTP server listening on port 25, you need to 
check the SMTP server logs.  You might need to crank up the logging to 
get useful output.  

If the information that you pasted in comes from a Django traceback then 
you could check the Django page on e-mail at 
http://docs.djangoproject.com/en/dev/topics/email/#topics-email
(dev version, you might need to view an older version).

Cheers,

Kev

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


Re: Problem w/ smtplib

2009-11-21 Thread Kev Dwyer
2009/11/21 Victor Subervi victorsube...@gmail.com

 On Sat, Nov 21, 2009 at 12:04 PM, Kev Dwyer kevin.p.dw...@gmail.comwrote:

 On Sat, 21 Nov 2009 08:19:52 -0500, Victor Subervi wrote:

 Hello Victor,

 The information that you have sent comes from the client side of the
 transaction, so it isn't possible to tell why the server disconnected.
 Assuming that there is an SMTP server listening on port 25, you need to
 check the SMTP server logs.


 There wasn't anything in /var/log/maillog. Is that where I should have
 checked?


 You might need to crank up the logging to
 get useful output.


 How?
 Look at the output below:

 [r...@13gems stcroixresort]# netstat -tulp
 Active Internet connections (only servers)
 Proto Recv-Q Send-Q Local Address   Foreign Address
 State   PID/Program name
 tcp0  0 *:mysql *:*
 LISTEN  24488/mysqld
 tcp0  0 *:pop3  *:*
 LISTEN  5278/tcpserver
 tcp0  0 *:ftp   *:*
 LISTEN  26564/vsftpd
 tcp0  0 localhost.localdomai:domain *:*
 LISTEN  11845/named
 tcp0  0 *:smtp  *:*
 LISTEN  5274/tcpserver
 tcp0  0 localhost.localdomain:rndc  *:*
 LISTEN  11845/named
 tcp0  0 *:http  *:*
 LISTEN  5201/httpd
 tcp0  0 localhost:domain*:*
 LISTEN  11845/named
 tcp0  0 *:ssh   *:*
 LISTEN  15509/sshd
 tcp0  0 localhost:rndc  *:*
 LISTEN  11845/named
 udp0  0 localhost.locald:domain
 *:* 11845/named
 udp0  0 localhost:domain
 *:* 11845/named
 [r...@13gems stcroixresort]# qmailctl stat
 /service/qmail-send: up (pid 5266) 594565 seconds
 /service/qmail-send/log: up (pid 5271) 594565 seconds
 /service/qmail-smtpd: up (pid 5274) 594565 seconds
 /service/qmail-smtpd/log: up (pid 5276) 594565 seconds
 /service/qmail-pop3d: up (pid 5278) 594565 seconds
 /service/qmail-pop3d/log: up (pid 5279) 594565 seconds
 messages in queue: 0
 messages in queue but not yet preprocessed: 0

 Please advise.
 TIA,
 V


Hello Victor,

 I'm afraid I don't know much about mail servers, you need to check the
server docs or ask on a qmail mailing list.

If you really think this is a python issue, then you could try:
 import smtplib
 server = smtplib.SMTP()
 server.set_debuglevel(1)
 server.connect()
connect: ('localhost', 25)
connect: (25, 'localhost')
reply: '220 pluto.site ESMTP Postfix\r\n'
reply: retcode (220); Msg: pluto.site ESMTP Postfix
connect: pluto.site ESMTP Postfix
(220, 'pluto.site ESMTP Postfix')
 server.quit()
send: 'quit\r\n'
reply: '221 2.0.0 Bye\r\n'
reply: retcode (221); Msg: 2.0.0 Bye
(221, '2.0.0 Bye')


and see if there are any error messages/tracebacks in the output; but if you
still get a disconnect exception then it's unlikely that this is a python
issue.

Cheers,

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


Re: Python Will Not Send Email!!

2009-11-20 Thread Kev Dwyer
On Fri, 20 Nov 2009 07:58:55 -0500, Victor Subervi wrote:

 On Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer kevin.p.dw...@gmail.com
 wrote:
 
 On Thu, 19 Nov 2009 11:28:37 -0400, Victor Subervi wrote:

 Hello Victor,

 There are some pages on the internet that suggest that this problem my
 be caused by a module named email.py (or email.pyc) in your pythonpath.
  If you try import smtplib in the interpreter do you get this error
 message? If so, start a new interpreter session and try import email -
 is the email module imported from the stdlib?


 Both of these import just fine.
 
 
 If these steps don't help, it might be useful if you can tell us which
 Linux distribution you are using.


 Python 2.4.3
 [r...@13gems ~]# uname -a
 Linux 13gems.com.13gems.com 2.6.18-028stab064.8 #1 SMP Fri Nov 6
 11:28:25 MSK 2009 x86_64 x86_64 x86_64 GNU/Linux CentOS 5.4 final
 TIA,
 V
 div class=gmail_quoteOn Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer
 span dir=ltrlt;a
 href=mailto:kevin.p.dw...@gmail.com;kevin.p.dw...@gmail.com/agt;/
span
 wrote:brblockquote class=gmail_quote style=margin:0 0 0
 .8ex;border-left:1px #ccc solid;padding-left:1ex; On Thu, 19 Nov 2009
 11:28:37 -0400, Victor Subervi wrote:br br
 Hello Victor,br
 br
 There are some pages on the internet that suggest that this problem my
 bebr caused by a module named email.py (or email.pyc) in your
 pythonpath.  Ifbr you try import smtplib in the interpreter do you get
 this error message?br If so, start a new interpreter session and try
 import email - is thebr email module imported from the
 stdlib?br/blockquotedivbr/divdivBoth of these import just
 fine. /divblockquote class=gmail_quote style=margin:0 0 0
 .8ex;border-left:1px #ccc solid;padding-left:1ex; br
 If these steps don#39;t help, it might be useful if you can tell us
 whichbr Linux distribution you are
 using.br/blockquotedivbr/divdivPython
 2.4.3/divdivdiv[r...@13gems ~]# uname -a/divdivLinux a
 href=http://13gems.com.13gems.com;13gems.com.13gems.com/a
 2.6.18-028stab064.8 #1 SMP Fri Nov 6 11:28:25 MSK 2009 x86_64 x86_64
 x86_64 GNU/Linux/div divCentOS 5.4
 final/divdivTIA,/divdivV/div/div/div

Hello Victor,

I ran your script on a CentOS vm (5.2 server 32bit, not quite the same as 
yours but also running python 2.4.3).  It ran without error.  So I 
suspect that either you have a rogue email module/package on your machine 
or there's something wrong with the python install.

You could try:

import email
email.__version__

My interpreter responds 3.0.1  If you get a different response that 
suggests a dodgy module somewhere - try email.__file__ and see where it's 
located (my interpreter returns /usr/lib/python2.4/email/__init__.pyc).

If the version number is 3.0.1 on your machine then I would check the 
contents of /usr/lib64/python2.4/email/.  Perhaps the base64MIME module 
is missing.

Cheers,

Kev

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


Re: Python Will Not Send Email!!

2009-11-20 Thread Kev Dwyer
On Fri, 20 Nov 2009 11:58:00 -0400, Victor Subervi wrote:

Hello Victor,

Carsten's well-specified instruction has identified your problem.

[r...@13gems globalsolutionsgroup.vi]# python -c import email; print 
email
module 'email' from 'email.pyc'

There is a file named email.pyc, most likely in your current directory, 
that is masking the email package in the standard library.  Remove/rename 
email.pyc and email.py, if it exists.

Cheers,

Kevin

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


Re: Python Will Not Send Email!!

2009-11-19 Thread Kev Dwyer
On Thu, 19 Nov 2009 11:28:37 -0400, Victor Subervi wrote:

Hello Victor, 

There are some pages on the internet that suggest that this problem my be 
caused by a module named email.py (or email.pyc) in your pythonpath.  If 
you try import smtplib in the interpreter do you get this error message?  
If so, start a new interpreter session and try import email - is the 
email module imported from the stdlib?

If these steps don't help, it might be useful if you can tell us which 
Linux distribution you are using.

Cheers,

Kev

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


Re: my recursive function call is wrong?

2009-08-16 Thread Kev Dwyer
On Sun, 16 Aug 2009 16:57:41 +0900, Chang Min Jeon wrote:


Hello,

You have placed recursive calls to the function in a number of different 
locations; when len(macro) becomes zero control will return to the 
calling function, but this calling function may have more code to 
execute, including further calls to start_parse(), and further attempts 
to index macro.

I like to keep recursive calls at the end of a function, so that there is 
a clean path back to the top level caller once the terminal condition is 
reached.  You can do it differently, but you need to bear in mind the 
execution paths through your code.

Cheers,

Kev

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


Re: XPath support?

2009-08-16 Thread Kev Dwyer
On Sun, 16 Aug 2009 20:29:15 +, kj wrote:

 I'm looking for a XML parser that produces an object with full XPath
 support.  What I've been using up to now, xml.etree.ElementTree, fails
 to support Xpath predicates, as in sp...@eggs='3']/ham.
 
 What I'm trying to do is to read-in a large XML string, and parse it
 into an object from which I can extract nodes matching selectors that
 include such predicates.
 
 Any suggestions would be greatly appreciated.
 
 TIA!
 
 kynn


Have you tried lxml (http://codespeak.net/lxml/)?

Kev

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