Re: [Tutor] issues with urllib and loading a webpage

2011-08-24 Thread Sander Sweers
On Wed, 24 Aug 2011, 00:03:23 CEST, Robert Sjoblom  
wrote:

> > > Are you using Python 3 and urllib, and not using httplib2? Because I
> > > honestly can't get urllib.request.urlopen to work with
> > > http://www.boursorama.com/ -- I only get b'' from there.
> > 
> > Yes, Python 3.2 which version one are you using? I tried both with
> > debug and without.
> 
> Python 3.2.1 64 bit on win 32. This is really quite weird.

You are running 64bit on a 32bit operating system, did you meant to say 32bit 
python on win64? If you actually do have 64bit python installed remove it and 
install the 32bit version. 

> There
> should be something there, because the headers alone doesn't account
> for the 7kb that's received.

How large is the page when dowloading from the browser? Is it comparable in 
size?

Greets
Sander___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] cPickle and shjelving

2011-08-24 Thread Warren P. Jones
Hi,

I am new to python. I am having slight issue in using the cPickle and shelving 
function.

Here is what i want the program need to do:

Open an file with employees in it with relevant information like: employee 
number, surname and department. I also need to add an employee with the 
relevant information without rewriting the current data.

I have tried the code but not completely sure what i am doing wrong.

Here is the code that i tried:

# Defines
pickles["employee_num"]

pickle_file = shelve.open("empl.dat")
   print "Add new Employee"
   employee_num = raw_input("\nEmployee number: ")
   surname = raw_input("Surname: ")
   name = raw_input("Name: ")
   department = raw_input("Department: ")

   
   #Storing DATA  #
   

   cPickles.dump(employee_num, emp1.dat)

   print key, "-",pickles[key]
   pickles.sync () # Makes sure date is written

Can you please help me in solving this issue?


Kind regards
Warren  Jones





This E-mail and any attachment(s) to it are for the addressee's use only.
It is strictly confidential and may contain legally privileged information. No 
confidentiality or privilege is waived or lost by any mis-transmission. If you 
are not the intended addressee, then please delete it from your system and 
notify the sender immediately. You are hereby notified that any use, 
disclosure, copying or any action taken in reliance on it is strictly 
prohibited and may be unlawful.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cPickle and shjelving

2011-08-24 Thread Hugo Arts
On Wed, Aug 24, 2011 at 11:26 AM, Warren P. Jones  wrote:
> Hi,
>
> I am new to python. I am having slight issue in using the cPickle and
> shelving function.
>
> Here is what i want the program need to do:
>
> Open an file with employees in it with relevant information like: employee
> number, surname and department. I also need to add an employee with the
> relevant information without rewriting the current data.
>
> I have tried the code but not completely sure what i am doing wrong.
>
> Here is the code that i tried:
>
> # Defines
> pickles["employee_num"]
>
>     pickle_file = shelve.open("empl.dat")
>    print "Add new Employee"
>    employee_num = raw_input("\nEmployee number: ")
>    surname = raw_input("Surname: ")
>    name = raw_input("Name: ")
>    department = raw_input("Department: ")
>
>    
>
>    #    Storing DATA  #
>
>    
>
>    cPickles.dump(employee_num, emp1.dat)
>    print key, "-",pickles[key]
>    pickles.sync () # Makes sure date is written
>
> Can you please help me in solving this issue?
>
> Kind regards
>
> Warren  Jones
>

That code makes very little sense. The indentation is wrong, and some
variables are never declared. Is that the full code? Also, shelve
already uses cPickle internally, so you don't need to use it
separately. Once you open a shelf, you can use it as a regular
dictionary object afterward:

shelf = shelve.open("empl.dat")
employee_num = raw_input("\nEmployee number: ")
shelf[employee_num] = {
"surname": raw_input("Surname: "),
"name": raw_input("Name: "),
"department": raw_input("Department: ")
}
shelf.close()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tutorials on csv module??

2011-08-24 Thread Khalid Al-Ghamdi
Hi everyone,

can anyone point me to a good tutorial on using the csv module?

also, is there a module that can help me check data in a excel file other
than the csv module?

thanks a lot

khaild
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutorials on csv module??

2011-08-24 Thread Steven D'Aprano

Khalid Al-Ghamdi wrote:

Hi everyone,

can anyone point me to a good tutorial on using the csv module?


Search engines are a wonderful thing.

http://duckduckgo.com/?q=python+csv+tutorial



also, is there a module that can help me check data in a excel file other
than the csv module?


http://duckduckgo.com/?q=python+excel
http://duckduckgo.com/?q=python+xls

Try the xlwt and xlrd libraries.

http://www.python-excel.org/


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval func with floating...

2011-08-24 Thread Christopher King
>
> If the user ever sees an AssertionError, your code is buggy.
>
Well you saw that I caught the AssertionError, so the user
wouldn't technically see it. For the other stuff, I didn't know
the etiquette for assertion statements.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Speech

2011-08-24 Thread Christopher King
 how do you unzip a gz on windows?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Speech

2011-08-24 Thread Alan Gauld

On 24/08/11 18:09, Christopher King wrote:

  how do you unzip a gz on windows?



Pretty much any zip tool (Qzip, Winzip etc) will
handle gz files too.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Speech

2011-08-24 Thread Christopher King
On Tue, Aug 23, 2011 at 8:46 PM, Alex Hall  wrote:

> Depending on what you want, you could try accessible_output.

It requires platform_utils. Anything else?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Syntax error with if statement

2011-08-24 Thread Ray Parrish

Hello,

I haven't been programming for a while and today I 
am working on something and have encountered an 
error I cannot figure out.


Here is my code:

  thisFile = column[6]
  if thisFile == "/Images/My%20Face.JPG"
   CallCount += 1
   print CallCount

And here is the error message:

ray@RaysComputer:~$ python 
/home/ray/EmailCount/CountEmails.py

  File "/home/ray/EmailCount/CountEmails.py", line 41
if thisFile == "/Images/My%20Face.JPG"
  ^
SyntaxError: invalid syntax

Any help you can be will be much appreciated.

Later, Ray Parrish

--
The Unknown Lead Player, Ray Parrish
http://www.facebook.com/pages/The-Unknown-Lead-Player/123388551041130?sk=wall
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax error with if statement

2011-08-24 Thread Andre Engels
On Wed, Aug 24, 2011 at 7:40 PM, Ray Parrish  wrote:

> Hello,
>
> I haven't been programming for a while and today I am working on something
> and have encountered an error I cannot figure out.
>
> Here is my code:
>
>  thisFile = column[6]
>  if thisFile == "/Images/My%20Face.JPG"
>   CallCount += 1
>   print CallCount
>
> And here is the error message:
>
> ray@RaysComputer:~$ python /home/ray/EmailCount/**CountEmails.py
>  File "/home/ray/EmailCount/**CountEmails.py", line 41
>if thisFile == "/Images/My%20Face.JPG"
>  ^
> SyntaxError: invalid syntax
>
> Any help you can be will be much appreciated.
>

There has to be a : at the end of an if statement, or more generally, any
statement that is to be followed by an indented block.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Speech

2011-08-24 Thread Jeff Johnson



On 08/24/2011 10:17 AM, Alan Gauld wrote:

On 24/08/11 18:09, Christopher King wrote:

  how do you unzip a gz on windows?



Pretty much any zip tool (Qzip, Winzip etc) will
handle gz files too.



7 zip works great on Windows for most formats.

http://www.7-zip.org/

Jeff

---

Jeff Johnson
j...@dcsoftware.com



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with a class

2011-08-24 Thread John
Hello, I have a class that has an attribute that is a dict which I
fill with more dicts. I've created a function to return those
dictionaries if a key is provide, otherwise, it returns the 'default'
dictionary.

I have the following methods (see below), it seems the update_options
method is fine, but I'm not sure about the override_options method...
and for that matter, I'm not sure this is the best approach overall...
any comments, critiques?

Thank you,
john

class Runner(object):
""" Initiate with an optional dictionary of settings.

Defaults are set in the options dictionary, which can be overridden.

"""
# Simplest default:
default_options = {
  'file' : '../data/input.dat',
  'wavelength' : '310.0 310.0'
  }


def __init__(self, **kwargs):

if 'options' not in kwargs:
self.options = copy(self.default_options)
self.run_queue = {}

def _get_from_queue(self, queue_key):
""" internal method to set options """

if queue_key:
if queue_key not in self.run_queue:
raise ValueError('queue_key: {0} not in
queue'.format(queue_key))
else:
return self.run_queue[queue_key]
else:
return self.options


def update_options(self, options, queue_key=None):
""" update the options dictionary using a dict """
assert isinstance(options, dict), "update options requires a dict"
old_options = self._get_from_queue(queue_key)
old_options.update(options)


def overide_options(self, options, queue_key=None):
""" completely overide the options dict """

assert isinstance(options, dict), "override options requires a dict"
old_options = self._get_from_queue(queue_key)
old_options = options

--
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with a class

2011-08-24 Thread Hugo Arts
On Wed, Aug 24, 2011 at 8:34 PM, John  wrote:
> Hello, I have a class that has an attribute that is a dict which I
> fill with more dicts. I've created a function to return those
> dictionaries if a key is provide, otherwise, it returns the 'default'
> dictionary.
>
> I have the following methods (see below), it seems the update_options
> method is fine, but I'm not sure about the override_options method...
> and for that matter, I'm not sure this is the best approach overall...
> any comments, critiques?
>

You've identified the problem point correctly, override_options will
not work as expected. What it does is:

1) retrieve a dict through _get_from_queue()
2) point the name old_options toward that dict
3) point the name old_options toward a different dict (the one that
options points to)

as you can see, the dict that is inside self.run_queue isn't actually
changed just by making old_options point towards the new dict. What
you need to do is actually assign the new dict to the place in the
queue, like so:

self.run_queue[queue_key] = options

of course, this will also just create a new entry in the dict if there
wasn't one previously, which isn't exactly an 'override.' So if you
want that behavior, check for it and raise an error by yourself.

One other thing, inside _get_from_queue(). If a key isn't present in a
dictionary, you generally raise a KeyError, not a ValueError. A
ValueError is for when a function argument is of the correct type, but
has an inappropriate value, and the error isn't more accurately
described by another exception like an IndexError. For example,
math.sqrt(-1) raises a ValueError because negative numbers don't make
sense for square roots, even though the argument is of the correct
type (yes, the math module doesn't have support for imaginary numbers
built in, even though the language does ಠ_ಠ There is cmath though).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with a class

2011-08-24 Thread John
Thank you. I've corrected the KeyError, and changed the function to:

def overide_options(self, options, run_id=None):
""" completely overide the options dict """

assert isinstance(options, dict), "override options requires a dict"
if run_id in self.run_queue:
self.run_queue[run_id] = options
else:
self.options = options
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with a class

2011-08-24 Thread Prasad, Ramit
I was under the impression that asserts are more for testing than for 
production code (especially since they can be removed when running from python 
from command line). Instead I removed the assert and replaced it to raise an 
error. 

def overide_options(self, options, run_id=None):
""" completely overide the options dict """

if not isinstance(options, dict): 
raise TypeError("override options requires a dict")
if run_id in self.run_queue:
self.run_queue[run_id] = options
else:
self.options = options

Do you really care if it is a dict versus defaultdict or something else that is 
dict-like? This will fail if I pass in a dict-like class (i.e. if I wrote dict 
from scratch) that does not inherit from dict.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423




This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with a class

2011-08-24 Thread Alan Gauld

On 24/08/11 21:03, Prasad, Ramit wrote:

I was under the impression that asserts are more for testing

> than for production code

That's true.


def overide_options(self, options, run_id=None):

 if not isinstance(options, dict):
 raise TypeError("override options requires a dict")


This is good if you want to keep the check in for production.
But using an assert here while testing then removing it from production 
would be a valid use too. The typecheck is not required for the function 
to work if you are confident of the data being passed in. assert checks 
the data while you are gaining that confidence.


So either approach is valid.
It all depends on how variable your input data is going to be.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Speech

2011-08-24 Thread Christopher King
I got the speech module to work actually, except for input. Only say works.
Here's a traceback on speech.input.
Traceback (most recent call last):
  File "C:\Python26\test.py", line 6, in 
print speech.input()
  File "C:\Python26\speech.py", line 162, in input
listener = listenforanything(response)
  File "C:\Python26\speech.py", line 193, in listenforanything
return _startlistening(None, callback)
  File "C:\Python26\speech.py", line 222, in _startlistening
context = _recognizer.CreateRecoContext()
  File
"C:\Python26\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00
C04F8EE628x0x5x0.py", line 2457, in CreateRecoContext
ret = self._oleobj_.InvokeTypes(10, LCID, 1, (9, 0), (),)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0,
-214722
1164), None)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Confirmation if command worked

2011-08-24 Thread Johan Geldenhuys
Hi all,


I have the following code that uses pexpect to execute a system command. My
problem is, I don't know how to identify if the command was successfully
executed.
The code works as it is to execute the SCP command, but it executes
regardless if the SCP session can actually connect to something.

Thanks

def doScp(files):


logger.log("Files to get: " + `files`)
fNames = ' '.join(files)

cmd = 'scp %s %s@%s:%s%s' % (fNames,
SCP_USERNAME,
SCP_HOST,
SCP_IMG_FILE_DIR,
SCP_IMG_FILE_PATH)

logger.log("Sending: " + cmd)

child = pexpect.spawn(cmd)

i = child.expect(['assword:', 'yes/no'], timeout=30)
if i == 0:
child.sendline(SCP_PASSWD)

elif i == 1:
child.sendline("yes")
child.expect("assword:", timeout=30)
child.sendline(SCP_PASSWD)

data = child.read()

if data != None:
success = True
else:
success = False
child.close()

logger.log("Files sent to SCP host")

return success





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Confirmation if command worked

2011-08-24 Thread Christian Witts

On 2011/08/25 07:51 AM, Johan Geldenhuys wrote:

Hi all,


I have the following code that uses pexpect to execute a system command. My
problem is, I don't know how to identify if the command was successfully
executed.
The code works as it is to execute the SCP command, but it executes
regardless if the SCP session can actually connect to something.

Thanks

def doScp(files):


 logger.log("Files to get: " + `files`)
 fNames = ' '.join(files)

 cmd = 'scp %s %s@%s:%s%s' % (fNames,
 SCP_USERNAME,
 SCP_HOST,
 SCP_IMG_FILE_DIR,
 SCP_IMG_FILE_PATH)

 logger.log("Sending: " + cmd)

 child = pexpect.spawn(cmd)

 i = child.expect(['assword:', 'yes/no'], timeout=30)
 if i == 0:
 child.sendline(SCP_PASSWD)

 elif i == 1:
 child.sendline("yes")
 child.expect("assword:", timeout=30)
 child.sendline(SCP_PASSWD)

 data = child.read()

 if data != None:
 success = True
 else:
 success = False
 child.close()

 logger.log("Files sent to SCP host")

 return success





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




Once you call child.close() the exit and signal status will be stored in 
.exitstatus and .signalstatus, for a normal exit of the program 
.exitstatus will store the return code from SCP as per [1] [2] [3] and 
.signalstatus will be None.  If SCP was terminated with a signal then 
.exitstatus will be None and .signalstatus will contain the signal 
value.  Info found in the docs [4].


So the changes to your code will be:


data = child.read()
child.close()

if child.exitstatus and child.exitstatus == 0:
success = True
else:
success = False


I'll leave putting in handling of failed error codes and abnormal 
termination to you.


[1] http://support.attachmate.com/techdocs/2116.html
[2] http://support.attachmate.com/techdocs/2487.html
[3] http://support.attachmate.com/techdocs/2285.html
[4] http://pexpect.sourceforge.net/pexpect.html

--

Christian Witts
Python Developer

//
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Confirmation if command worked

2011-08-24 Thread Johan Geldenhuys
Hi Christian,

 

Thanks for that. I'll give it a shot and see if I can catch the error.

 

Lekker dag

 

 

Johan

 

From: Christian Witts [mailto:cwi...@compuscan.co.za] 
Sent: Thursday, 25 August 2011 4:25 PM
To: Johan Geldenhuys
Cc: tutor@python.org
Subject: Re: [Tutor] Confirmation if command worked

 

On 2011/08/25 07:51 AM, Johan Geldenhuys wrote: 

Hi all,
 
 
I have the following code that uses pexpect to execute a system command. My
problem is, I don't know how to identify if the command was successfully
executed.
The code works as it is to execute the SCP command, but it executes
regardless if the SCP session can actually connect to something.
 
Thanks
 
def doScp(files):


logger.log("Files to get: " + `files`)
fNames = ' '.join(files)

cmd = 'scp %s %s@%s:%s%s' % (fNames,
SCP_USERNAME,
SCP_HOST,
SCP_IMG_FILE_DIR,
SCP_IMG_FILE_PATH)

logger.log("Sending: " + cmd)

child = pexpect.spawn(cmd)

i = child.expect(['assword:', 'yes/no'], timeout=30)
if i == 0:
child.sendline(SCP_PASSWD)

elif i == 1:
child.sendline("yes")
child.expect("assword:", timeout=30)
child.sendline(SCP_PASSWD)

data = child.read()

if data != None:
success = True
else:
success = False
child.close()

logger.log("Files sent to SCP host")

return success
 
 
 
 
 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
 
 


Once you call child.close() the exit and signal status will be stored in
.exitstatus and .signalstatus, for a normal exit of the program .exitstatus
will store the return code from SCP as per [1] [2] [3] and .signalstatus
will be None.  If SCP was terminated with a signal then .exitstatus will be
None and .signalstatus will contain the signal value.  Info found in the
docs [4].

So the changes to your code will be:


data = child.read()
child.close()

if child.exitstatus and child.exitstatus == 0:
success = True
else:
success = False


I'll leave putting in handling of failed error codes and abnormal
termination to you.

[1] http://support.attachmate.com/techdocs/2116.html
[2] http://support.attachmate.com/techdocs/2487.html
[3] http://support.attachmate.com/techdocs/2285.html
[4] http://pexpect.sourceforge.net/pexpect.html

-- 

Christian Witts
Python Developer

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor