Re: [Tutor] File renaming using os.rename problem (spir)

2009-12-09 Thread spir
Roy Hinkelman royh...@gmail.com dixit:

 Why don't you simply print out fname? This should point you to the error.
 
 Denis
 
 
 I did here:
  if fname == old_name:
  print fname # test
 
 and it looks correct.
 
 On an WinXP, should I use shutil instead?
 
 Roy

Sorry Roy, I read your post too fast.

Denis


la vita e estrany

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


Re: [Tutor] duplication in unit tests

2009-12-09 Thread spir
Serdar Tumgoren zstumgo...@gmail.com dixit:

 Hi everyone,
 I'm trying to apply some lessons from the recent list discussions on
 unit testing and Test-Driven Development, but I seem to have hit a
 sticking point.
 
 As part of my program, I'm planning to create objects that perform
 some initial data clean-up and then parse and database the cleaned
 data. Currently I'm expecting to have a FileCleaner and Parser
 classes. Using the TDD approach, I've so far come up with the below:
 
 class FileCleaner(object):
 def __init__(self, datastring):
 self.source = datastring
 
 def convertEmDashes(self):
 Convert unicode emdashes to minus signs
 self.datastring = self.source.replace(u'\u2014','-')
 
 def splitLines(self):
 Generate and store a list of cleaned, non-empty lines
 self.data = [x.strip() for x in
 self.datastring.strip().split('\n') if x.strip()]
 
 
 My confusion involves the test code for the above class and its
 methods. The only way I can get splitLines to pass its unit test is by
 first calling the convertEmDashes method, and then splitLines.
 
 class TestFileCleaner(unittest.TestCase):
 def setUp(self):
 self.sourcestring = uThisline   has an em\u2014dash.\n
 So   does this  \u2014\n.
 self.cleaner = FileCleaner(self.sourcestring)
 
 def test_convertEmDashes(self):
 convertEmDashes should remove minus signs from datastring
 attribute
 teststring = self.sourcestring.replace(u'\u2014','-')
 self.cleaner.convertEmDashes()
 self.assertEqual(teststring, self.cleaner.datastring)
 
 def test_splitLines(self):
 splitLines should create a list of cleaned lines
 teststring = self.sourcestring.replace(u'\u2014','-')
 data = [x.strip() for x in teststring.strip().split('\n') if 
 x.strip()]
 self.cleaner.convertEmDashes()
 self.cleaner.splitLines()
 self.assertEqual(data, self.cleaner.data)
 
 Basically, I'm duplicating the steps from the first test method in the
 second test method (and this duplication will accrue as I add more
 cleaning methods).
 
 I understand that TestCase's setUp method is called before each test
 is run (and therefore the FileCleaner object is created anew), but
 this coupling of a test to other methods of the class under test seems
 to violate the principle of testing methods in isolation.
 
 So my questions -- Am I misunderstanding how to properly write unit
 tests for this case? Or perhaps I've structured my program
 incorrectly, and that's what this duplication reveals? I suspected,
 for instance, that perhaps I should group these methods
 (convertEmDashes, splitLines, etc.) into a single larger function or
 method.
 
 But that approach seems to violate the best practice of writing
 small methods. As you can tell, I'm a bit at sea on this.  Your
 guidance is greatly appreciated!!
 
 Regards,
 Serdar
 
 ps - recommendations on cleaning up and restructuring code are also welcome!

Hello,

I guess you're first confused at the design level of your app. Test and design 
both require you to clearly express your expectations. Here, the cleanup phase 
may be written as follow (I don't mean it's particuliarly good, just an 
example):

plain source data = input   --   output = ready-to-process data

As you see, this requirement is, conceptually speaking, a purely function-al 
one; in the plain sense of the word function. At least, this is the way I see 
it.
Building an object to implement it is imo a wrong interpretation of OO design. 
(It's also writing java in python ;-) I would rather chose to write it as a 
method of a higher-level object. Possibly, this method would split into smaller 
ones if needed.

Then, expressing your tests is in a sense translating the requirement above 
into code: feeding the piece of code to be tested with raw input data and 
checking the output is as expected. As well expressed by Kent, you should test 
with typical, edge, *and wrong* input; in the latter case the test is expected 
to fail.
You will have to hand-write or automatically produce input strings for each 
test. If the func is split, then you will have to do it for each mini-func to 
be tested. This can be rather unpleasant, especially in cases like yours where 
funcs look like logically operating in sequence, but there is no way to escape. 
Actually, the several cleanup tasks (translating special chars, skipping blank 
lines, etc...) are rather orthogonal: they don't need to be tested in sequence.


Denis


la vita e estrany

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Che M



 My problem, though, is I still find it difficult to write meaningful code or 
 use the built in libraries 

 effectively and/or correctly because I can't find example code to mimic. I 
 tried sifting through 

 ActiveState recipes page, but most of the code seems uninteresting or useful 
 only if utilized 

 in a bigger project. 

What do you mean by meaningful code?  I think that might be your issue.  



What I'd recommend is to figure out *what you want to accomplish*.  Python is 
just a means

to accomplish something, but what matters is the accomplishment.  You may want 
to write a 

GUI desktop app for a specific purpose.  You may want to create a web-based 
app.  You may

want to write code to process information, scrape web sites...create a game, 
create some

kind of tool.  



Once you decide on that, you will be more focused on what you need to learn.  
If, for

example, you need to have persistent storage of information, you then might 
want to

read up on databases and perhaps SQLite in Python.  Etc.  Then you will find 
code that

will be applicable to your concerns, and help you learn.  I feel that learning 
something 

in a vacuum, unrelated to some personal creative goal, just doesn't work well.



Che

  
_
Get gifts for them and cashback for you. Try Bing now.
http://www.bing.com/shopping/search?q=xbox+gamesscope=cashbackform=MSHYCBpubl=WLHMTAGcrea=TEXT_MSHYCB_Shopping_Giftsforthem_cashback_1x1___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] win32com and ocx with properties

2009-12-09 Thread John
I realize that some may consider this an advance question.  But there are many 
here that are advance.  So I'm hoping some nice soul will help me.

I'm attempting to use a OCX designed to talk with QuickBooks.  I'm using 
win32com for the first time and have discovered an issue that I'm sure others 
have run into.  But researching google etc.  has not helped.

obj = win32com.client.Dispatch(InQB.Invoice.1)
#In the VB code 
#obj.ItemName(0) = 'string' 

#in python I'm trying 
obj.ItemName[0] = 'string'
#error is Instancemethod object does not support item assignment

I found and ran makepy.py and here is the code it created dealing with my obj.

# The method ItemName is actually a property, but must be used as a method
to correctly pass the arguments
def ItemName(self, ItemIndex=defaultNamedNotOptArg):
        Line item property: Reference to the kind of item.
        # Result is a Unicode object
        return self._oleobj_.InvokeTypes(19, LCID, 2, (8, 0), 
((3,1),),ItemIndex )

As I read the above code it can only return a string not assign anything. I'm 
not sure what InvokeTypes does.

So the question is how can I get around this issue?  I'm sure others need to 
set properties in com objects.

BTW does anyone know of a win32com forum or list?

Johnf

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Weidner, Ronald

 My problem, though, is I still find it difficult to write meaningful code or 
 use the built in libraries
 effectively and/or correctly because I can't find example code to mimic. I 
 tried sifting through
 ActiveState recipes page, but most of the code seems uninteresting or useful 
 only if utilized
 in a bigger project.

What do you mean by meaningful code?  I think that might be your issue.

What I'd recommend is to figure out *what you want to accomplish*.  Python is 
just a means
to accomplish something, but what matters is the accomplishment.  You may want 
to write a
GUI desktop app for a specific purpose.  You may want to create a web-based 
app.  You may
want to write code to process information, scrape web sites...create a game, 
create some
kind of tool.

Once you decide on that, you will be more focused on what you need to learn.  
If, for
example, you need to have persistent storage of information, you then might 
want to
read up on databases and perhaps SQLite in Python.  Etc.  Then you will find 
code that
will be applicable to your concerns, and help you learn.  I feel that learning 
something
in a vacuum, unrelated to some personal creative goal, just doesn't work well.

Che


I agree with Che.  For me, picking a project then completing it is the best way 
for me to learn a language.
That said this link is a great resource in my opinion...

http://www.diveintopython.org/

The book there is fantastic and all the links on the right side of the page 
lead to other great resources.
The only resource that I feel was left out was this one.  I've learned a lot 
from this site too.

http://www.uselesspython.com/

Good luck...

--
Ronald Weidner



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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Serdar Tumgoren
 I wan't to buy some books about python 3. Do you have any recommendations?
 I started with no previous programming experience, and I've finished a few
 tutorials  and I guess I can be considered a beginner.

 My problem, though, is I still find it difficult to write meaningful code or
 use the built in libraries effectively and/or correctly because I can't find
 example code to mimic. I tried sifting through ActiveState recipes page, but
 most of the code seems uninteresting or useful only if utilized in a bigger
 project.

You might want to check out the 2nd Edition of Beginning Python,
published in Sept. 2008.
http://hetland.org/writing/beginning-python-2/

It includes the standard coverage of core Python syntax with a forward
look at core Python 3 features (it was forward at the time). It also
contains a number of project chapters at the end that span everything
from text processing, to GUI building to network programming. They're
not industrial strength apps, but I'd say a level above the typical
toy examples.

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


[Tutor] Append mode dilemma

2009-12-09 Thread biboy mendz

Hello all!
I'm trying to use the append mode when opening and writing to a file
but i cant get it to work my way. When run in the present code,
the user inputs are expectedly 'appended' but not in a newline below the 
last

line of the existing file. Instead it starts from where the last line end. I
want the append to start on a newline of its own. Can you please let me
know what am I missing? I dont quite get it what my book reference states:

Any file opened with 'a' will be opened for append. All writes to files 
opened
with 'a' will be from end-of-file, even if you seek elsewhere during 
access. If
the file does not exist it will be created, making it the same as if you 
opened

the file in 'w' mode.



#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Chapter 3.1 :
Core Python Programming 2nd Edition by Wesley Chun
Filename: appendFile.py
Created: 09-Dec-2009
v1.0: append user input to existing file
'''

import os, sys

def main():
while True:
fname = raw_input('Enter filename to APPEND your input lines: ')
if os.path.isdir(fname):
print('%s is a directory!') % fname
elif not os.path.exists(fname):
print 'this is APPEND mode; select CREATE to create new file'
elif fname.isspace():
print 'Space is not allowed'
else:
#os.path.exists(fname):
#found candidate for edit
break

all = [] # container list to hold user input lines
print(file '%s' will be appended by your input\n) % fname
quit_prompt = [start your input to quit enter 1 dot]-- 

while True:
entry = raw_input(quit_prompt)
if entry == '.':
break
else:
all.append(entry)

confirm = raw_input('save file to disk?(y/N)')
confirm = confirm.lower() #convert to lowercase
if confirm == 'y':
fobj = open(fname, 'a')
fobj.write('\n'.join(all))
fobj.close()
print('DONE! open %s to view your file') % fname
else:
print 'not saving to disk!'

if __name__ == '__main__':
main()

--
Regards,
bibs M.

Host/Kernel/OS  cc02695 running Linux 2.6.31-5.slh.4-sidux-686 
[sidux 2009-02 Αιθήρ - kde-full - (200907141427) ]

www.sidux.com

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Albert Sweigart
I'd recommend Doug Hellman's Python Module of the Week blog (PyMOTW)
at http://www.doughellmann.com/projects/PyMOTW/

He goes into each of the standard library modules and gives examples
of them in use.

Dive Into Python 3 by Mark Pilgrim is also good for getting up to
speed on Python 3. http://diveintopython3.org/

And I recommend my book, Invent Your Own Computer Games with Python
which is freely available at http://inventwithpython.com
It doesn't go into the standard library modules, but it does have
several complete programs that are easy to read and understand. The
book is aimed at complete beginners and young adults (but is not
kidsy).

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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Luke Paireepinart
On Wed, Dec 9, 2009 at 12:11 PM, biboy mendz bibsmen...@gmail.com wrote:

 Hello all!
 I'm trying to use the append mode when opening and writing to a file
 but i cant get it to work my way. When run in the present code,
 the user inputs are expectedly 'appended' but not in a newline below the
 last
 line of the existing file.

That's because there is NOT a new line at the end of the file.
It's a file you're appending to, it's up to YOU to create that new line.
 And all files should end with newlines anyway (on linux).
So modify your code so that you output a new line at the end of your
outputs.

 fobj = open(fname, 'a')
 fobj.write('\n'.join(all))
 fobj.close()

 Are you aware of how 'join' works?
try
print #.join(['a','b','c'])
at the interactive prompt and see if you can't figure out why you're missing
a newline at the end of your output.


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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread biboy mendz



Luke Paireepinart wrote:
On Wed, Dec 9, 2009 at 12:11 PM, biboy mendz bibsmen...@gmail.com 
mailto:bibsmen...@gmail.com wrote:


Hello all!
I'm trying to use the append mode when opening and writing to a file
but i cant get it to work my way. When run in the present code,
the user inputs are expectedly 'appended' but not in a newline
below the last
line of the existing file.

That's because there is NOT a new line at the end of the file.
It's a file you're appending to, it's up to YOU to create that new 
line. And all files should end with newlines anyway (on linux).
So modify your code so that you output a new line at the end of your 
outputs.


fobj = open(fname, 'a')
fobj.write('\n'.join(all))
fobj.close()

Are you aware of how 'join' works?
try
print #.join(['a','b','c'])
at the interactive prompt and see if you can't figure out why you're 
missing a newline at the end of your output.



HTH,
-Luke


Hi Luke,

Thank you. To be honest I'm confused of the different string methods 
like join(), split(), etc. Anyway I will practice them to see how they work.


--
Regards,
bibs M.

Host/Kernel/OS  cc02695 running Linux 2.6.31-5.slh.4-sidux-686 
[sidux 2009-02 Αιθήρ - kde-full - (200907141427) ]

www.sidux.com


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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Luke Paireepinart
On Wed, Dec 9, 2009 at 12:49 PM, biboy mendz bibsmen...@gmail.com wrote:


 Are you aware of how 'join' works?

 Hi Luke,

 Thank you. To be honest I'm confused of the different string methods like
 join(), split(), etc. Anyway I will practice them to see how they work.


 It's very important to practice these string methods, you should get
intimately acquainted with all the builtin objects and functions, they're
extremely flexible and usually very fast as well.

The main problem with your 'join' is that join takes an interable and
creates a new string with the LHS argument in between each iterated item.
So if you join 'a' 'b' 'c', with # you will get 'a#b#c'.
Note that there is no # at the beginning or end.

In your case, you are outputting to a file, and you want every file to end
with a newline, so you simply need to append another newline to the end.
#.join(['a','b','c']) + # would do the trick for the # example.  The
result would be a#b#c#.

Just to be clear, make sure you have your extra newline at the end, not the
beginning of the print.  Otherwise your first line in the file will be
blank.  So it does matter where you put the newline.


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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread biboy mendz



Luke Paireepinart wrote:
That's because there is NOT a new line at the end of the file.
It's a file you're appending to, it's up to YOU to create that new 
line. And all files should end with newlines anyway (on linux).
So modify your code so that you output a new line at the end of your 
outputs.


fobj = open(fname, 'a')
fobj.write('\n'.join(all))
fobj.close()



Quickie hack just to achieve the newline. Doesn't python have a function 
that adds newline automatically in append mode?



fobj = open(fname, 'a')
fobj.write('\n'.join(all))
print
fobj.close()

--
Regards,
bibs M.

Host/Kernel/OS  cc02695 running Linux 2.6.31-5.slh.4-sidux-686 
[sidux 2009-02 Αιθήρ - kde-full - (200907141427) ]

www.sidux.com



Are you aware of how 'join' works?
try
print #.join(['a','b','c'])
at the interactive prompt and see if you can't figure out why you're 
missing a newline at the end of your output.



HTH,
-Luke


Hi Luke,

Thank you. To be honest I'm confused of the different string methods 
like join(), split(), etc. Anyway I will practice them to see how they 
work.



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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Luke Paireepinart
On Wed, Dec 9, 2009 at 1:02 PM, biboy mendz bibsmen...@gmail.com wrote:


  Luke Paireepinart wrote:
 That's because there is NOT a new line at the end of the file.
 It's a file you're appending to, it's up to YOU to create that new line.
 And all files should end with newlines anyway (on linux).
 So modify your code so that you output a new line at the end of your
 outputs.

fobj = open(fname, 'a')
fobj.write('\n'.join(all))
fobj.close()


 Quickie hack just to achieve the newline. Doesn't python have a function
 that adds newline automatically in append mode?


Why would it need a function for this?  Some people might not want a
newline, so it can't be automatically enabled.




 fobj = open(fname, 'a')
 fobj.write('\n'.join(all))
 print
 fobj.close()


This won't work unless you have STDOUT redirected to your file.  It would be
better just to do
 fobj.write('\n'.join(all) + '\n')

which is shorter than a function call that would enable this feature anyway.
This isn't a hack, this is how you're supposed to do this.

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Alan Gauld


Khalid Al-Ghamdi emailkg...@gmail.com wrote

I wan't to buy some books about python 3. Do you have any 
recommendations?


There are very few Python 3 books out there.
The only one I've used and can recommend is Programming in Python3 by 
Summerfield


Other general Python books that will still be effective albeit written for 
Python 2

are all specialised topic guides such as:

Python Network Programming - APress
WxPython in Action - Manning
Python Programming on Win32 - OReilly

Otherwise try to get a cheap/secondhand copy of Python in a 
Nutshell(OReilly)


HTH,

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



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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Albert Sweigart
Your problem is on this line:

fobj.write('\n'.join(all))

This puts a newline in between each line in all, but not at the end.
The fix is simple:

fobj.write('\n'.join(all) + '\n')

This will make sure that the last line has a newline at the end of it,
so that when you later append data, it will appear on a fresh line.

-Al Sweigart
You should check out my free beginner's Python book, Invent Your Own
Computer Games with Python
http://inventwithpython.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Serdar Tumgoren
To Alan's list, I'd also add Learning Python 4th Edition. It came out
in October and covers Python 3 and 2.6, though I'm not sure if it
includes the heftier code samples the OP was interested in...

On Wed, Dec 9, 2009 at 2:13 PM, Alan Gauld alan.ga...@btinternet.com wrote:

 Khalid Al-Ghamdi emailkg...@gmail.com wrote

 I wan't to buy some books about python 3. Do you have any recommendations?

 There are very few Python 3 books out there.
 The only one I've used and can recommend is Programming in Python3 by
 Summerfield

 Other general Python books that will still be effective albeit written for
 Python 2
 are all specialised topic guides such as:

 Python Network Programming - APress
 WxPython in Action - Manning
 Python Programming on Win32 - OReilly

 Otherwise try to get a cheap/secondhand copy of Python in a
 Nutshell(OReilly)

 HTH,

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

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

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


Re: [Tutor] duplication in unit tests

2009-12-09 Thread Serdar Tumgoren
 Yes, this is much better. Notice how much less code it is! :-)

Yes, it was amazing to see how much code melted away when I gave up on
the OO design. As you and others suggested, clearly this was not the
correct approach for this portion of my program.

 If you expect unicode input then it makes sense to test for it. If you
 don't expect unicode input, it might make sense to test for an
 expected error - how do you want the function to behave with invalid
 inputs?

For invalid inputs, I'd like to log the error and place the data in a
file for additional review. The input has to be unicode, and if it's
not, it means my initial read and decoding of the source data was not
performed properly. For that case, I'll plan to raise an exception and
abort the program.

You could add other tests as well, for example does it work if
 there are two dashes in a row? Does splitLines() correctly remove
 blank lines?

So it seems I have a healthy list of test cases to start with!

 By the way I applaud your effort, unit testing is a valuable skill.

I'll admit, I learned the hard way on a project earlier this year. I
got that project done (again with the help of folks on this list), but
didn't do any test-writing up front. And now, as the inevitable bugs
crop up, I'm forced to patch them hoping that I don't break something
else. It drove home the fact that I need to get serious about testing,
even if I don't go full-bore TDD on every project.

I suspect an overdose of preparatory TDD reading had my head swirling
a bit. I appreciate you all walking me through this first effort.

No doubt I'll be writing again soon with more questions. Meantime, many thanks!

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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Lie Ryan

On 12/10/2009 6:12 AM, Luke Paireepinart wrote:

This won't work unless you have STDOUT redirected to your file.  It
would be better just to do
  fobj.write('\n'.join(all) + '\n')


except that if you're joining a very long string, you'll have python 
copy the whole string again.


better to just redirect print
print  fobj, '\n'.join(all)

but since this is a file object we're talking about, you can write while 
getting user input.


with open(...) as fobj:
entry = ''
while entry != '.'
fobj.write(raw_input())

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


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Luke Paireepinart
On Wed, Dec 9, 2009 at 2:46 PM, Lie Ryan lie.1...@gmail.com wrote:

 On 12/10/2009 6:12 AM, Luke Paireepinart wrote:

 This won't work unless you have STDOUT redirected to your file.  It
 would be better just to do
  fobj.write('\n'.join(all) + '\n')


 except that if you're joining a very long string, you'll have python copy
 the whole string again.

 better to just redirect print
 print  fobj, '\n'.join(all)


I'm sorry, but this just seems like kind of an unreadable way to do this.
 You're implicitly relying on print adding a newline to the end of every
output.
You could also just append an empty string to the end of all and thus
another newline would be added.
Either approach is less clear than the concatenation.  I guess it just
depends on the size of your string.
The most readable approach while still being efficient would probably be
just to write a newline after the previous write.
fobj.write('\n'.join(all))
fobj.write('\n')

Then it's still absolutely clear that you're trying to get a newline there
and it's not a side-effect of some other function.


 but since this is a file object we're talking about, you can write while
 getting user input.

 with open(...) as fobj:
entry = ''
while entry != '.'
fobj.write(raw_input())

 Again, the file will only have a newline at the end in this situation
because you're relying on the implicit newline created by reading in the
user's string from raw_input.
So I don't think this is a good example to give in this situation, because
as soon as the user starts splitting / stripping / parsing raw_input and
then trying to write it back out
they're going to get confused.

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread wesley chun
 I wan't to buy some books about python 3. Do you have any recommendations?
 I started with no previous programming experience, and I've finished a few
 tutorials  and I guess I can be considered a beginner.


greetings khalid, and welcome to Python!

based on your background, i would like you start with Python 2, and i
have several reasons for making this suggestion:

- most beginner-oriented tutorials and books are still on Python 2
- Python 2 is not obsolete, and 95% of worldwide code still uses it
- knowing Python 2 is not going to stop you from learning Python 3 quickly

with that said, the most well-known books and online tutorials for
true beginners like yourself include (in no particular order):

- hello world!: computer programming for kids and other beginners by
sande http://cp4k.blogspot.com/- how to think like a computer
scientist by downey and elkner http://openbookproject.net//thinkCSpy/
- a byte of python by swaroop (both python 2 and python 3 versions)
http://www.swaroopch.com/notes/Python
- learning to program by gauld http://www.freenetpages.co.uk/hp/alan.gauld/
- python for the absolute beginner by dawson
-livewires course http://www.livewires.org.uk/python/home

you can find more resources here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

some of the books that have been suggested in this thread do require
some programming experience, so i wanted to provide a few specifically
targeted towards non-programmer beginners.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
Python Fundamentals, Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] win32com and ocx with properties

2009-12-09 Thread bob gailer

John wrote:
I realize that some may consider this an advance question.  But there are many 
here that are advance.  So I'm hoping some nice soul will help me.


I'm attempting to use a OCX designed to talk with QuickBooks.  I'm using 
win32com for the first time and have discovered an issue that I'm sure others 
have run into.  But researching google etc.  has not helped.


obj = win32com.client.Dispatch(InQB.Invoice.1)
#In the VB code 
#obj.ItemName(0) = 'string' 

#in python I'm trying 
obj.ItemName[0] = 'string'
  


Try:

obj.ItemName.Item[0] = 'string'

In VB obj.ItemName(0) = 'string' Item is the default property.
obj.ItemName.Item(0) = 'string' will also work in VB



#error is Instancemethod object does not support item assignment

I found and ran makepy.py and here is the code it created dealing with my obj.

# The method ItemName is actually a property, but must be used as a method
to correctly pass the arguments
def ItemName(self, ItemIndex=defaultNamedNotOptArg):
Line item property: Reference to the kind of item.
# Result is a Unicode object
return self._oleobj_.InvokeTypes(19, LCID, 2, (8, 0), 
((3,1),),ItemIndex )


As I read the above code it can only return a string not assign anything. I'm 
not sure what InvokeTypes does.


So the question is how can I get around this issue?  I'm sure others need to 
set properties in com objects.


BTW does anyone know of a win32com forum or list?
  


There is python-wi...@python.org

--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] More on unit testing - tests for external data...

2009-12-09 Thread Modulok
List,

Unit testing functions and methods which rely on passed data is simple
enough. However:

How do I unit test something which relies on external data?

For example, a function which creates a file only if it doesn't exist
on disk, or a unit test for a function which makes an SQL query? If
anyone could point to a few examples of such usage, that would be
great!

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Tim Goddard
I just finished Michael Dawson's Python Programming for the absolute
beginner.  I thought it was pretty good, with only a few minor nit
picks.  My programming background was limited to MATLAB and some
Visual Basic scripting for excel, access etc making me the target
audience.  I liked the examples, and by the end has you put together a
simple asteroid-style game (with livewires and pygame).  If my C class
back in undergrad had promised I'd be making some shooting games in
the end perhaps I'd have kept with it and gone into computer science
or something.

I also encountered a previous posters problem with the pizza not
falling down.  If you use the latest version of livewires the Sprite
class does not accept velocity arguments and you have to invoke a
separate Mover class to make it move.  Considering I had no experience
with python before this book, that I was able to open the games module
and determine what changed says a lot about what can be learned from a
'beginners' book.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fast fourier transform libraries?

2009-12-09 Thread Joe Veldhuis
Hello to all. I'm working on a program that will need to do some simple signal 
analysis (namely, find the frequency of an audio signal) as part of its 
operation.

Something like:
-
samples = list()
for i in range(fft_length):
 samples.append(readSoundCard())

fft_bins = FFT(samples, sample_rate, window_function)

for bin in fft_bins:
 #find strongest bin
 #return frequency in Hz corresponding to that bin
-

My question is, can someone recommend a library that provides an FFT function 
that will do what I want (i.e. take samples and return a list of bins)? Could 
be a binding to FFTW, or something else entirely. A search on PYPI returned 
nothing of interest.

Any advice greatly appreciated!
-Joe
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Append mode dilemma

2009-12-09 Thread Alan Gauld


Lie Ryan lie.1...@gmail.com wrote


with open(...) as fobj:
entry = ''
while entry != '.'
fobj.write(raw_input())


But how does entry change in this example?
I think you need

with open(...) as fobj:
entry = ''
while entry != '.'

fobj.write(entry)

entry = raw_input()



--
Alan Gauld
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] More on unit testing - tests for external data...

2009-12-09 Thread Alan Gauld

Modulok modu...@gmail.com wrote


Unit testing functions and methods which rely on passed data is simple
enough. However:

How do I unit test something which relies on external data?


You have to build a test environment.
This needs to be carefully planned to enable every test condition 
to be tested.



For example, a function which creates a file only if it doesn't exist
on disk, or a unit test for a function which makes an SQL query? 


So you would need a file that exists, one that doesn't(!), 
one that exists but is read-only, one that exists but wrong user 
ownership, and really a binary file and a text file and an 
empty file and a huge file too


For the database it gets tricky, you need to create a database 
full of entries with all the possible scenarios you might encounter.
For a large application with multiple joined tables designing such 
a test database can take a lot of time - but it is invaluable for testing 
and debugging and provided you store a clean copy somewhere 
before using it makes regression testing possible.
Once you have the database you then need to write the test driver 
code that will provide the right keys for each test - database testing 
is one of the biggest challenges in system testing.


And don't forget to test for behaviour with invalid user access on 
the database, and for locking and simultaneous updates etc.
And if its on a separate server that you check behaviour when 
the server or network is down or running slowly (eg by lowering 
server priorioty and running a huge bulk update in the background).


Remember, in testing you are not trying to prove it works but rather 
to demonstrate that it doesn't!


--
Alan Gauld
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] win32com and ocx with properties

2009-12-09 Thread John
On Wednesday 09 December 2009 01:45:38 pm bob gailer wrote:
 John wrote:
  I realize that some may consider this an advance question.  But there are
  many here that are advance.  So I'm hoping some nice soul will help me.
 
  I'm attempting to use a OCX designed to talk with QuickBooks.  I'm using
  win32com for the first time and have discovered an issue that I'm sure
  others have run into.  But researching google etc.  has not helped.
 
  obj = win32com.client.Dispatch(InQB.Invoice.1)
  #In the VB code
  #obj.ItemName(0) = 'string'
 
  #in python I'm trying
  obj.ItemName[0] = 'string'

 Try:

 obj.ItemName.Item[0] = 'string'

 In VB obj.ItemName(0) = 'string' Item is the default property.
 obj.ItemName.Item(0) = 'string' will also work in VB

  #error is Instancemethod object does not support item assignment
 
  I found and ran makepy.py and here is the code it created dealing with my
  obj.
 
  # The method ItemName is actually a property, but must be used as a
  method to correctly pass the arguments
  def ItemName(self, ItemIndex=defaultNamedNotOptArg):
  Line item property: Reference to the kind of item.
  # Result is a Unicode object
  return self._oleobj_.InvokeTypes(19, LCID, 2, (8, 0),
  ((3,1),),ItemIndex )
 
  As I read the above code it can only return a string not assign anything.
  I'm not sure what InvokeTypes does.
 
  So the question is how can I get around this issue?  I'm sure others need
  to set properties in com objects.
 
  BTW does anyone know of a win32com forum or list?

 There is python-wi...@python.org

Someone suggested I use:

obj.SetItemName(0,'test')

And it works (who knew) 

Thanks to all that replied,

Actually thanks to all you tutors...

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


Re: [Tutor] Fast fourier transform libraries?

2009-12-09 Thread Alan Gauld


Joe Veldhuis electrob...@gmail.com wrote

My question is, can someone recommend a library that provides an FFT 
function

that will do what I want (i.e. take samples and return a list of bins)?


I'm no expert of FFT (I stuidied it at uni but can't remember a thing about 
it!)

but a Google search suggests the fftpack in scipy should help.

Alan G. 



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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Alan Gauld


Becky Mcquilling ladymcse2...@gmail.com wrote

Is there a good Tutorial that you guys recommend, where you actually get 
a
useful exercise to try and do and then you can be walked through 
different

solutions?


What an interesting question.
I'm not aware of any tutorials that do this (although mine does in a few 
cases
- eg the address book and myultiplication table examples - its not a 
general

approach). I'll be interested to see if anyone else knows of anything.

Administrator type functions and have to debug stuff and starting to do 
this
on Python, so something not quite so incredibly dense would work better, 
I

just don't know where to start.


There are plenty of beginners tutorials including mine.
I just don't know of any that use multiple solutions to a single problem
as a teaching tool.


--
Alan Gauld
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] What books do you recommend?

2009-12-09 Thread wesley chun
 - learning to program by gauld http://www.freenetpages.co.uk/hp/alan.gauld/

update: alan's latest tutorial lives here: http://www.alan-g.me.uk/tutor/

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Python Web Development with Django, Addison Wesley, (c) 2009
http://withdjango.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What books do you recommend?

2009-12-09 Thread spir
Alan Gauld alan.ga...@btinternet.com dixit:

 
 Khalid Al-Ghamdi emailkg...@gmail.com wrote
 
  I wan't to buy some books about python 3. Do you have any 
  recommendations?
 
 There are very few Python 3 books out there.
 The only one I've used and can recommend is Programming in Python3 by 
 Summerfield
 
 Other general Python books that will still be effective albeit written for 
 Python 2
 are all specialised topic guides such as:
 
 Python Network Programming - APress
 WxPython in Action - Manning
 Python Programming on Win32 - OReilly
 
 Otherwise try to get a cheap/secondhand copy of Python in a 
 Nutshell(OReilly)
 
 HTH,
 

see also: http://inventwithpython.com/ 

Denis


la vita e estrany

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


Re: [Tutor] duplication in unit tests

2009-12-09 Thread spir
Serdar Tumgoren zstumgo...@gmail.com dixit:

 I'll admit, I learned the hard way on a project earlier this year. I
 got that project done (again with the help of folks on this list), but
 didn't do any test-writing up front. And now, as the inevitable bugs
 crop up, I'm forced to patch them hoping that I don't break something
 else. It drove home the fact that I need to get serious about testing,
 even if I don't go full-bore TDD on every project.

The great thing about testing is, once you have test suites for each module (in 
the general sense of the term), for relations between them, for global 
functionality, then you can update, refactor, enhace, etc... with some amount 
of confidence that you're not just adding bugs to bugs.

Denis


la vita e estrany

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Becky Mcquilling
And I did see yours which was great.

But the reason I ask this, is because there are SO many different approaches
you could take to a single problem, how do you know which is correct or why
one is better than the other?  You can dig yourself in to holes with more
complex problems, and not understand why.

Second thing, I'd like the answer to be somewhere, in a tutorial.  If I
really didn't get the solution, it helps to have the solution walked through
and next time, I may be able to solve it (hopefully, anyway).  I'm so new at
this, that sometimes, I'm completely stumped and a few hints would go a long
way, then having the answer presented, with an explanation, even further.

Becky

On Wed, Dec 9, 2009 at 4:19 PM, Alan Gauld alan.ga...@btinternet.comwrote:


 Becky Mcquilling ladymcse2...@gmail.com wrote


  Is there a good Tutorial that you guys recommend, where you actually get a
 useful exercise to try and do and then you can be walked through different
 solutions?


 What an interesting question.
 I'm not aware of any tutorials that do this (although mine does in a few
 cases
 - eg the address book and myultiplication table examples - its not a
 general
 approach). I'll be interested to see if anyone else knows of anything.


  Administrator type functions and have to debug stuff and starting to do
 this
 on Python, so something not quite so incredibly dense would work better, I
 just don't know where to start.


 There are plenty of beginners tutorials including mine.
 I just don't know of any that use multiple solutions to a single problem
 as a teaching tool.


 --
 Alan Gauld

 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

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


Re: [Tutor] What books do you recommend?

2009-12-09 Thread Che M



 But the reason I ask this, is because there are SO many different approaches 
 you could
 take to a single problem, 

I guess that depends a lot on what sorts of problems you are thinking in terms 
of.  At least in many cases, perhaps one of the points of the Zen of Python is 
useful:

There should be one--and preferably only one--obvious way to do it.



I myself have been trying to stick to that for now; to learn some standard ways 
to do certain things, to not reinvent the wheel but instead to use the standard 
library and modules to do what I need done (since someone already needed it 
done before and coded it well then).Yes, gaining more flexibility in how 
you could approach something is also good, but for learning I have tried to 
establish a core of basic approaches first, and alternate approaches second.  I 
feel that if it works, it's readable, simple, and re-usable, I put it in the 
toolbox.

 how do you know which is correct or why one is better than the 
 other?  You can dig yourself in to holes with more complex problems, and not 
 understand 
 why. 

This list is one good resource for comparing notes on correctness of 
approach.  You'll see people ask if something is Pythonic or not, etc.


  
_
Windows 7: Unclutter your desktop. Learn more.
http://www.microsoft.com/windows/windows-7/videos-tours.aspx?h=7secslideid=1media=aero-shake-7secondlistid=1stop=1ocid=PID24727::T:WLMTAGL:ON:WL:en-US:WWL_WIN_7secdemo:122009___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sound problems

2009-12-09 Thread Tim Goddard
I'm still learning, and this may be better served on a pygame mailing
list but I thought I'd try here first.

I'm following the python programming for absolute beginners which uses
livewires and pygame to do some simple games.  My difficulty comes
from not using the module versions used in the book and using the
latest online offerings.

The book creates a simple program to play music and sound in a console
environment.

initially the code was (shortened for brevity):

from livewires import games

# load a sound file
missile = games.load_sound(missile.wav)

#load the music file
games.load_music(theme.mid)

choice == None
while choice != 0:
print 
1 - play missile sound
2 - play music

choice = raw_input(Choose your selection: )
if choice == 1:
missile.play()
elif choice == 2:
games.play_music()

Which gives an error because the load_music is not part of the latest
games.py module.  So after reading through games.py I discovered that
most of it is a pass through to pygames.  Also the sound does not
play.

My modified code which plays music but still not sound is:
from livewires import games
# If I don't keep the above line, I get an error that pygame.mixer is
not initialized properly

import pygame

# load a sound file
missile = pygame.mixer.Sound('pickup.wav')

# load the music file
pygame.mixer.music.load(theme.mid)

menu code

if choice == 1:
missile.play(3)  # loop .wav three times.
print Playing missile sound

elif choice == 2:
pygame.mixer.music.play()
print Playing theme music

My question is why won't the sound play in the console?  When I use
the same code in a program with a screen, it plays normally.

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


Re: [Tutor] Sound problems

2009-12-09 Thread Lie Ryan

On 12/10/2009 4:30 PM, Tim Goddard wrote:

My modified code which plays music but still not sound is:
from livewires import games
# If I don't keep the above line, I get an error that pygame.mixer is
not initialized properly


I haven't inspected your code thoroughly, but did you make any call to 
pygame.init()? Many pygame modules won't work properly unless you do 
that before doing anything else.


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


[Tutor] parsing Spreadsheet document

2009-12-09 Thread Christopher Spears
I want to fill a database with the contents of a spreadsheet.  The spreadsheet 
was created by OpenOffice and is a .sxc document.  What is the best way to do 
this?  I think the best approach is to save the spreadsheet as a .csv document 
and then just parse the file.  Am I on the right track here?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor