Re: [Tutor] Alternatives to append() for growing a list

2013-12-08 Thread Steven D'Aprano
On Sun, Dec 08, 2013 at 04:10:45PM +1000, Amit Saha wrote:

 It didn't have to do with strings. It was a basic example of using
 append() which is to start with an empty list and and then build it
 incrementally:
 
  l = [ ]
  l.append(1)
 # append more

If this is literally what the code does, then it's fat and slow and 
should be replaced with this:

# not this
l = []
l.append(1)
l.append(2)
l.append(x)
l.append(y)

# this is even worse, despite being shorter
l = []
for item in [1, 2, x, y]:
l.append(item)


# this is the way to do it
l = [1, 2, x, y]


But without seeing the specific code in question, it is impossible to 
judge whether you are using append appropriately or not.



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


[Tutor] Suggestion required on python as scripting language

2013-12-08 Thread Shankar Donepudi
Hi All,

I am working as test engineer in Networking in storage domain. We have
decided to automate our testing and have chosen python for the same. We
have basic knowledge on python so can anyone suggest good tutorials for
writing automation scripts using python.

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


[Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-08 Thread Rafael Knuth
Hey there,

I struggle to understand what unit testing specifically means in
practice and how to actually write unit tests for my code (my gut is
telling me that it's a fairly important concept to understand).

Over the last few days I learned how to write and work with classes, I
learned quite a lot about functions, nested loops and I currently walk
through every program in the Python.org wiki Simple Programs
https://wiki.python.org/moin/SimplePrograms ... and here's the unit
test program they provide:

import unittest
def median(pool):
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
return copy[(size - 1) / 2]
else:
return (copy[size/2 - 1] + copy[size/2]) / 2
class TestMedian(unittest.TestCase):
def testMedian(self):
self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
if __name__ == '__main__':
unittest.main()

Also, I went through the Beginning Test-Driven Development in Python
http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/
but I have to admit I still don't fully understand how unit tests work
in practice and how to write my own unit tests.

As it turned out over the last few weeks, the best modus operandi for
me as an absolute beginner is to grab a small program, take it apart
in the first place, understand how each component works through trial
 error, then put all those pieces together and then I kind of get the
big picture. Once I get  it I practice as much as possible to
memorize what I just learned and *then* I start readying as many
blogs, tutorials etc. as possible to deepen my understanding (I
frankly find most tutorials  blogs too complex and confusing from a
beginner's viewpoint, and I learn faster by taking code apart and
learning through trial  error in the first place). So, what I am
specifically searching for is a very simple code sample which I can
take apart and iterate through each component, and I was wondering if
you are aware of resources that might be helpful?

My understanding of unit testing is that I have to embed my code into
a test and then I have to define conditions under which my code is
supposed to fail and pass. Is that assumption correct?

I am a bit lost  confused here .. any help  hing is highly appreciated!

Thank you  all the best,

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


Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-08 Thread Amit Saha
On Sun, Dec 8, 2013 at 8:22 PM, Rafael Knuth rafael.kn...@gmail.com wrote:
 Hey there,

 I struggle to understand what unit testing specifically means in
 practice and how to actually write unit tests for my code (my gut is
 telling me that it's a fairly important concept to understand).

Your gut feeling is right. However, you will only *truly* understand
it's usefulness as you write more programs yourself. No matter how
many articles or blog posts or books you read it in, it's something
which you will yourself have to realize and once you do so, you will
find great value in it. Also, don't fret if you don't realize it. You
will, sooner or latter.  Here is a fairly common use case where you
will really find tests useful (try it!):

Say, you have a fairly big program, single file (module) or spread
across multiple files. Now, as you improve your understanding, you
realize that you can write more efficient/elegant code. So you go on a
wholesale refactoring spree (the technical term for changing your
existing code to cleanup your existing code to write more optimized or
idiomatic code). However, you are not very confident that all the
changes haven't broken any of your existing features. So, what do you
do? When you don't have tests, you have to manually imagine and run
the programs for all possible inputs and check if the output/results
are as expected. On the other hand, if you have a tests, you can
simply run these tests and refactor your code confidently. However, I
have also realized during my own learning adventures and learning from
the existing code base and users' bug reports that the benefit of
tests are solely dependent on the the test cases you have covered in
your tests. If you missed a scenario (a test case) in your tests, then
it is likely that any breakage of functionality in that area of your
program will not be undetected when you run the tests.


 Over the last few days I learned how to write and work with classes, I
 learned quite a lot about functions, nested loops and I currently walk
 through every program in the Python.org wiki Simple Programs
 https://wiki.python.org/moin/SimplePrograms ... and here's the unit
 test program they provide:

 import unittest
 def median(pool):
 copy = sorted(pool)
 size = len(copy)
 if size % 2 == 1:
 return copy[(size - 1) / 2]
 else:
 return (copy[size/2 - 1] + copy[size/2]) / 2

BTW, this program will not work in Python 3, since a division
operation returns a float. so, 4/2 = 2.0 .

 class TestMedian(unittest.TestCase):
 def testMedian(self):
 self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
 if __name__ == '__main__':
 unittest.main()

 Also, I went through the Beginning Test-Driven Development in Python
 http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/
 but I have to admit I still don't fully understand how unit tests work
 in practice and how to write my own unit tests.

I will attempt an explanation with a far simpler function:

# myarith.py
def sum(a,b):
return a+b

Let's say you have saved this function in a module, myarith.py. Now,
how would you really verify if the function actually returns the sum
of the numbers passed to it? By calling the function of course. Here
is one way:

 import myarith
 myarith.sum(1, 2)
3
 myarith.sum(1, 5)
6
 myarith.sum(-11, -5)
-16
test case
So, you are confident that your function works as expected. Now,
instead of calling your function as above, you want to use  the
unittest module. Here is a  test module which tests the above
function:

# test_arith.py

import unittest
import myarith

class ArithTest(unittest.TestCase):

def test_sum(self):
self.assertEqual(myarith.sum(1,2), 1+2)


if __name__ == '__main__':
unittest.main()

We first create a class ArithTest which is a subclass of
unittest.TestCase. This means that, the class ArithTest is a test case
and in it you will have various tests to test the functions in your
myarith module. Right now, there is only one function, sum(). So, we
create a function, test_sum() where we call the sum() function as
above, but we call it inside the assertEqual() method which basically
tests whether the first argument's value is equal to the second
argument. Now, when you run this module, you will see something like:

$ python3 test_arith.py
.
--
Ran 1 test in 0.000s

OK


Now, let us modify the test_sum() method:

import unittest
import myarith

class ArithTest(unittest.TestCase):

def test_sum(self):
self.assertEqual(myarith.sum(1,2), 1+2)

def test_sum_2(self):
self.assertEqual(myarith.sum(2,2), 15)

if __name__ == '__main__':
unittest.main()

A new test has been added, test_sum_2() which is obviously going to
fail. Let's see what happens when we run the module again:

.F
==
FAIL: test_sum_2 

Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-08 Thread spir

On 12/08/2013 11:22 AM, Rafael Knuth wrote:

Hey there,

I struggle to understand what unit testing specifically means in
practice and how to actually write unit tests for my code (my gut is
telling me that it's a fairly important concept to understand).
[...]


Hello Rafael,

This post is quite long, and partly personal. As you guess, testing is in fact 
an important topic, and there is much to say about it. As usual in programming, 
the domain comes with its load of ambiguity, contradictions and 
misunderstandings. Question number 0: why testing? My view is that testing is a 
tool that helps one making good software by finding bugs, or trying to. There 
are at least 2 interpretations of this:
1. Help  finding symptoms (signs) of errors, meaning obviously wrong things: I 
will this a control test
2. Help  finding the source of such symtoms, meaning the actual error: I call 
this a diagnosis test.
What a test has _not_ as purpose is proving your software correct; this is not 
possible (except if it is very simple and runs on a closed set of variable input 
data).


Unit testing means testing a whole, consistent section of source code: 
typically a function, a complex object, a data structtre, or a(nother) class. A 
test is then one or more test functions that try and find bugs in this section 
of code. In languages like Python with a prominent concept of module, there can 
be a module's whole test function, which usually just calls every test func in 
the module. This may look like this:


def test1 ():
...
def test2 ():
...
def test3 ():
...

def test ():
test1()
test2()
test3()

if __name__ == __main__:
test()  # to comment out when running without test
pass

Now, what does each test func do?  Since you just discovered classes, I will use 
as example a simple Class 'Position' (or part of it):


class Position:
def __init__ (self, x=0, y=0):
self.x, self.y = x, y
def move (self, dt):
# dt is delta-time (difference of time)

Move changes the position according to elapsed time and a movement scheme, maybe 
as complicated as linear in time (I'm joking); maybe when reaching a border (eg 
screen limit), an object bounces or magically jumps to the other side; or maybe 
position also holds vx  vy speed coordinates (velocity vector), which also change.


To test move, one would provide a series of test data, here a list of dt values. 
Then create a specimen of Position, run move for each dt, and for each case 
_check_ that the resulting position is ok.


# a series of checks like:
pos.move(dt)
ok = (pos.x == correct_x) and (pos.y == correct_y)
if ok:
...
else:
...

You may simplify by providing a Position '==' method (__eq__)

def __eq__ (self, other)
return (self.x == other.x) and (self.y == other.y)
# or just tuple equality:
return (self.x, self.y) == (other.x, other .y)

Which permits checking more simply:

# a series of checks like:
pos.move(dt)
if  (pos == correct_pos):
...
else:
...

Now consider a situation where instead of move we have:

def movement (dt):
...
return (dx, dy)

'move' was an action-function some performs an effect, thus one checks its 
effect. 'movement' is an evaluation function, a function properly speaking 
that computes some value (here, a pair of values), thus we can directly check 
its output result:


# a series of checks like:
if pos.movement(dt) == correct_movement: # a tuple (dx, dy):
...
else:
...

As _simple_ as that. And tests should definitely be simple, stupid. Otherwise we 
would have to test tests (it happened to me ;-). There are several sources of 
error in tests: base objects (here a position), test data (dt values), test 
correct results (new positions), etc... plus test logic if you don't make it 
trivial enough. A wrong test finds false positives, meaning wrong errors where 
there are none, and false negatives, meaning good outcomes which actually are 
bad. One may spoil tons of time because of that... (this also happened to me, in 
fact numerous times). Tests must be very simple.


Another question is: what to check? As you probably guess, all kinds of special 
values, border values, exceptional values, are the ones to test in priority. In 
our case, dt=0, dt=1, dt=big, dt=very_very_big. But there is a whole category of 
checks often completely forgotten, namely failure checks: most methods should 
just fail on wrong or dubious input (which I call anomalies). What happens if dt 
is negative? What if it is is an int instead of a float, or conversely (python 
would happily compute if you don't mind)? What if it's not anumber at all? To 
test that, if failure of a given function translates to raising an exception 
(stop program execution with an error message), your check must catch the 
possible exception. (Maybe you don't know that yet.)


And most importantly, 

Re: [Tutor] Suggestion required on python as scripting language

2013-12-08 Thread spir

On 12/08/2013 07:59 AM, Shankar Donepudi wrote:

Hi All,

I am working as test engineer in Networking in storage domain. We have
decided to automate our testing and have chosen python for the same. We
have basic knowledge on python so can anyone suggest good tutorials for
writing automation scripts using python.


As far as I know, there is no specific Python tutorial for writing automation 
scripts! This would be surprising, wouldn't it be? (For the record, automation 
used to be my job domain.) I would just recommend to:

* first look at the documentation page on the python.org site
* follow one or more of advanced tutorials or guides on python one can find 
online
* search for testing in python and explore what you find, as a source of 
inspiration

(If you you find particularly good and interesting things, maybe bring back 
information here on this mailing list, so that it can serve others.)


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


Re: [Tutor] Alternatives to append() for growing a list

2013-12-08 Thread spir

On 12/08/2013 07:14 AM, Amit Saha wrote:

If all of the bitN are strings:
 bit1 + bit2 + bit3 + bit4 + bit5
actually constructs:
 bit1+bit2
 bit1+bit2+bit3
 bit1+bit2+bit3+bit4
 bit1+bit2+bit3+bit4+bit5
A number of unneeded string object, and a very big useless memory weight.

Thanks Denis, good to know this is how it is done. I hadn't thought
about it simply because, never have probably concatenated strings
beyond the simple adding a new line to a string.


This is only due to catenation being defined in python as a _binary_ operation. 
In principle, there is no reason for this. In a hypothetical language (I will 
here use Lisp-like syntax just to make a visual difference), one may write:

(cat bit1 bit2 bit3 bit4 bit5)
Then cat would catenate all bits in one go, into a sigle total string (sum the 
sizes and make a single whole string of this size).


As a side-note, this is also true for common arthmetic operators like + or *, 
which are not conceptually binary, but we have this impression *due to infix 
notation*:

1 + 2 + 3 + 4 + 5
is usually interpreted as a series of binary operations:
1 + 2) + 3) + 4) + 5)
but there could well be (and in some languages this is the case):
(+ 1 2 3 4 5)
in one go (even if behind the stage there are binary ops, just because the 
machine also knows that).


Think at manual sum for illustration:
   123
   456
   789
   ---
result

Maybe infix notation is just wrong for some operations and misleads into wrong 
thinking. We should reserve for actual binary ops, namely - and /; but prefix 
notation, as illustrated above, would nicely do the job for binary pos as well. 
(The same point applies to logical operators or  and, which are not binary, 
while the case of relational ones [comparisons] is more obscure.)
However, unlike the case of catenation, unjustified binary arithmetic operations 
do not cause any other harm than needlessly multiplying function or method 
lookups  calls (if there is a call, which is the case in python because such 
operators can be overloaded).


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


Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-08 Thread Mark Lawrence

On 08/12/2013 10:22, Rafael Knuth wrote:

Hey there,

I struggle to understand what unit testing specifically means in
practice and how to actually write unit tests for my code (my gut is
telling me that it's a fairly important concept to understand).

Over the last few days I learned how to write and work with classes, I
learned quite a lot about functions, nested loops and I currently walk
through every program in the Python.org wiki Simple Programs
https://wiki.python.org/moin/SimplePrograms ... and here's the unit
test program they provide:

import unittest
def median(pool):
 copy = sorted(pool)
 size = len(copy)
 if size % 2 == 1:
 return copy[(size - 1) / 2]
 else:
 return (copy[size/2 - 1] + copy[size/2]) / 2
class TestMedian(unittest.TestCase):
 def testMedian(self):
 self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
if __name__ == '__main__':
 unittest.main()

Also, I went through the Beginning Test-Driven Development in Python
http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/
but I have to admit I still don't fully understand how unit tests work
in practice and how to write my own unit tests.

As it turned out over the last few weeks, the best modus operandi for
me as an absolute beginner is to grab a small program, take it apart
in the first place, understand how each component works through trial
 error, then put all those pieces together and then I kind of get the
big picture. Once I get  it I practice as much as possible to
memorize what I just learned and *then* I start readying as many
blogs, tutorials etc. as possible to deepen my understanding (I
frankly find most tutorials  blogs too complex and confusing from a
beginner's viewpoint, and I learn faster by taking code apart and
learning through trial  error in the first place). So, what I am
specifically searching for is a very simple code sample which I can
take apart and iterate through each component, and I was wondering if
you are aware of resources that might be helpful?

My understanding of unit testing is that I have to embed my code into
a test and then I have to define conditions under which my code is
supposed to fail and pass. Is that assumption correct?

I am a bit lost  confused here .. any help  hing is highly appreciated!

Thank you  all the best,

Raf


Two pieces of advice from me, one don't overthink it, two why not look 
at Python's own unit tests?  On my Windows 7 box they're here 
C:\Python33\Lib\test, I'm sure you can find the equivalent on your own 
machine.  Perhaps pick some builtin functions and modules from the 
standard library that you've used, and see how the core developers go 
about testing them.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-08 Thread Steven D'Aprano
On Sun, Dec 08, 2013 at 11:22:37AM +0100, Rafael Knuth wrote:
 Hey there,
 
 I struggle to understand what unit testing specifically means in
 practice and how to actually write unit tests for my code (my gut is
 telling me that it's a fairly important concept to understand).

In practice, unit testing is a way to check that your code does what you 
expect it should do. For every function and method (or at least, as many 
of them as you can), you should test that it does what you expect.

What you expect means the following:

- when given good input, does the function return the correct result?

- when given bad input, does the function fail the way it is supposed to 
fail? (e.g. raise an exception, return an error code).

Also, the unit test module is good for writing regression tests. Every 
time you discover a bug in your code, before you fix the bug, you should 
write a test that demonstrates the existence of that bug. Then, if later 
changes to your program bring the bug back (this is called a 
regression), the test will fail and you will discover the regression 
straight away.

A simple example: suppose you have a method, Dog.bark(n) which is 
supposed to return bark! repeated some number of times, and if n is 
zero or negative it should return the empty string. Normally I put my 
unit tests in a separate file. So here's some unit tests for the 
Dog.bark method:


import unittest
from myprogram import Dog

class DogTest(unittest.TestCase):
def test_bark_with_positive_argument(self):
dog = Dog()
self.assertEqual(dog.bark(1), bark!)
self.assertEqual(dog.bark(2), bark! bark!)
self.assertEqual(dog.bark(5), bark! bark! bark! bark! bark!)

def test_bark_with_zero_argument(self):
dog = Dog()
self.assertEqual(dog.bark(0), )

def test_bark_with_negative_argument(self):
dog = Dog()
for i in (-1, -2, -3):
self.assertEqual(dog.bark(i), )

def test_walk(self):
# test the walk method

# and so on

if __name__ == '__main__':
# Only run this part when running this file as a script.
unittest.main()


(Alas, good tests often end up with tediously long names. Fortunately 
you don't have to read the test names very often.)

The tests all pass! Looks good. But here we see the problem with 
testing: tests can only show the existence of bugs, they cannot prove 
that there are no bugs at all. Oh well. At some point, some poor unlucky 
fellow discovers a bug in the Dog class, and reports it to you:

Problem: Dog.bark() returns wrong result

dog = Dog()
dog.bark(-17)

Expected result: 
Actual result: meow!


A fact of life -- you can never (well, hardly ever) test *every* 
possible result from your functions. Occasionally there will be 
surprises like this. Nevermind, this is the job of the program: fix the 
bugs as they are discovered.

So we add an extra test to the unit tests. This one is going to test for 
regressions, so we don't just modify the existing negative argument 
test, but we make sure this is a specific, individual test.

class DogTest(unittest.TestCase):
[...other methods remain the same]

def test_bark_with_negative_argument(self):
dog = Dog()
samples = [1, 2, 3, 4, 5] + random.sample(range(6, 1), 20)
for i in samples:
self.assertEqual(dog.bark(-i), )

def test_regression_bug_id_92(self):
dog = Dog()
self.assertEqual(dog.bark(-17), )


Notice that I've made the negative_argument case a lot more vigorous at 
testing the method. It's a matter of personal judgement how many cases 
you should check, but given that we've missed one bug, that's a good 
sign that we didn't check enough. So now instead of testing just a small 
handful, I test the first five negative values plus another 20 randomly 
choosen ones.

I also add a specific regression test to ensure that this bug can never 
happen again. In this example I've put the Bug Report ID in the test 
name, but that's not compulsary. The important thing is that you have a 
test for the bug.

If I run the DogTest now, test_regression_bug_id_92 fails, because I 
haven't fixed the bug. This proves that the test works as expected.

Now I fix the bug, re-run the DogTest, and hopefully everything passes. 
If so, I can be reasonably sure that there are no obvious bugs in the 
parts of the code I've actually tested.


[...]
 Also, I went through the Beginning Test-Driven Development in Python
 http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/
 but I have to admit I still don't fully understand how unit tests work
 in practice and how to write my own unit tests.

How unit tests work -- the unittest module is a big, complicated package 
that defines a whole lot of classes and methods. The idea is that the 
module defines a class that understands how to perform testing. It knows 
how to run assertSomething methods, or if you prefer, 

Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-08 Thread Alan Gauld

On 08/12/13 10:22, Rafael Knuth wrote:


My understanding of unit testing is that I have to embed my code into
a test and then I have to define conditions under which my code is
supposed to fail and pass. Is that assumption correct?


That's correct for any kind of unit testing, not just using the
unittest module. Others have shown how to get started with it.
Here are some things to think about when testing.

If you have input parameters that are collections, say a list, then 
always test how the function reacts to an empty list, or a different 
type of collection, say a tuple, or a list of data other than the 
expected type (say you expect a list of numbers and get strings 
instead). And a very large list(some function use recursion

which can break with large data sets) In other words think of
what somebody else using your function might to do it that
could break it.

Similarly with numbers that, say, act as indexes into a list.
Check for negative numbers, zero, small positive numbers,
large numbers, floats, non-numbers

Hopefully that gives some idea of the kinds of things you should
test for. In a real-world project the test code is often bigger 
(sometime much bigger) than the code being tested (although also

much more repetitive!).

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

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


Re: [Tutor] Suggestion required on python as scripting language

2013-12-08 Thread bob gailer

On 12/8/2013 1:59 AM, Shankar Donepudi wrote:

Hi All,

I am working as test engineer in Networking in storage domain. We have 
decided to automate our testing and have chosen python for the same. 
We have basic knowledge on python so can anyone suggest good tutorials 
for writing automation scripts using python.
It might help if you were more specific. What are you testing? What in 
your domain does an automation script do?


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


Re: [Tutor] Suggestion required on python as scripting language

2013-12-08 Thread Amit Saha
Hello,

On Sun, Dec 8, 2013 at 4:59 PM, Shankar Donepudi
umasankar.donep...@gmail.com wrote:
 Hi All,

 I am working as test engineer in Networking in storage domain. We have
 decided to automate our testing and have chosen python for the same. We have
 basic knowledge on python so can anyone suggest good tutorials for writing
 automation scripts using python.

As others have mentioned, you will most need to be more specific about
what you are trying to do and any specific problems you are facing. I
am going to take a guess and perhaps a book such Python for Unix and
Linux System Administration [1] may give you some ideas. I also wrote
this article a while ago [2] which is a fairly basic
introduction/treatment of exploring Linux using Python.


 [1] http://shop.oreilly.com/product/9780596515829.do (The reviews
aren't so good, but I did go through it and you will likely find
useful things there)
 [2] http://amitsaha.github.io/site/notes/articles/python_linux/article.html

Best,
Amit.


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


[Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread Benjamin Fishbein
Hello.
I'm writing a program to draw pictures. I'm using Python 2.7.3 on Mac OSx. I'm 
trying to find a good way to save the canvas as a jpg (or other pic formats). 
The advice I've found on stackoverflow is ImageGrab from PIL, but apparently 
that doesn't work for macs. I get the no module named _grabscreen ImportError.
Can you recommend a good module for saving the canvas into a picture file?
Thank you,
Ben

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


Re: [Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread Joel Goldstick
On Sun, Dec 8, 2013 at 7:14 PM, Benjamin Fishbein bfishbei...@gmail.comwrote:

 Hello.
 I'm writing a program to draw pictures. I'm using Python 2.7.3 on Mac OSx.
 I'm trying to find a good way to save the canvas as a jpg (or other pic
 formats). The advice I've found on stackoverflow is ImageGrab from PIL, but
 apparently that doesn't work for macs. I get the no module named
 _grabscreen ImportError.
 Can you recommend a good module for saving the canvas into a picture file?
 Thank you,
 Ben

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


Have you imported PIL ?  Show a small coding example here with the
traceback. Cut and paste the traceback, don't paraphrase it.

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


[Tutor] No module named '_tkinter'

2013-12-08 Thread pierre dagenais
Hi,
I'm running Ubuntu 10.04 and I've installed python 3.3.3 from the
tarball at http://python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz

Here is the error I get when trying to run tkinter.

pierre@Sprint:~$ python3.3
Python 3.3.3 (default, Dec  2 2013, 11:10:53)
[GCC 4.6.3] on linux
Type help, copyright, credits or license for more information.
 import tkinter
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/local/lib/python3.3/tkinter/__init__.py, line 40, in module
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named '_tkinter'


I've tried installing python3-tk from the Ubuntu repository but it
doesn't help.

Any suggestion on how to install the tkinter module with this version?

Thank you,

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


Re: [Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread Benjamin Fishbein
 Have you imported PIL ?  Show a small coding example here with the traceback. 
 Cut and paste the traceback, don't paraphrase it.

Here's what printed out:

Traceback (most recent call last):
  File pyshell#65, line 1, in module
from PIL import ImageGrab
  File /Library/Python/2.7/site-packages/PIL/ImageGrab.py, line 34, in 
module
import _grabscreen
ImportError: No module named _grabscreen

From what I've seen online, this isn't available for mac...of course everything 
about this module is several years old, and it hasn't been updated with a new 
version in a few years, so I think there must be something better than it.


 I'm writing a program to draw pictures. I'm using Python 2.7.3 on Mac OSx. 
 I'm trying to find a good way to save the canvas as a jpg (or other pic 
 formats). The advice I've found on stackoverflow is ImageGrab from PIL, but 
 apparently that doesn't work for macs. I get the no module named 
 _grabscreen ImportError.
 Can you recommend a good module for saving the canvas into a picture file?
 Thank you,
 Ben
 
 -- 
 Joel Goldstick
 http://joelgoldstick.com

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


Re: [Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread Joel Goldstick
On Sun, Dec 8, 2013 at 8:10 PM, Benjamin Fishbein bfishbei...@gmail.comwrote:

 Have you imported PIL ?  Show a small coding example here with the
 traceback. Cut and paste the traceback, don't paraphrase it.


 Here's what printed out:

 Traceback (most recent call last):
   File pyshell#65, line 1, in module
 from PIL import ImageGrab
   File /Library/Python/2.7/site-packages/PIL/ImageGrab.py, line 34, in
 module
 import _grabscreen
 ImportError: No module named _grabscreen


What happens if you import PIL like this:

import PIL

You will then need to use PIL.ImageGrab in your code


 From what I've seen online, this isn't available for mac...of course
 everything about this module is several years old, and it hasn't been
 updated with a new version in a few years, so I think there must be
 something better than it.


 I'm writing a program to draw pictures. I'm using Python 2.7.3 on Mac OSx.
 I'm trying to find a good way to save the canvas as a jpg (or other pic
 formats). The advice I've found on stackoverflow is ImageGrab from PIL, but
 apparently that doesn't work for macs. I get the no module named
 _grabscreen ImportError.
 Can you recommend a good module for saving the canvas into a picture file?
 Thank you,
 Ben


 --
 Joel Goldstick
 http://joelgoldstick.com





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


Re: [Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread Srinivas Nyayapati
From what I've seen online, this isn't available for mac...of course
everything about this module is several years old, and it hasn't been
updated with a new version in a few years, so I think there must be
something better than it.



You could give Pillow a try. It is a fork of the PIL library and more up to
date.

https://pypi.python.org/pypi/Pillow/

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


Re: [Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread Mark Lawrence

On 09/12/2013 01:10, Benjamin Fishbein wrote:


Here's what printed out:

Traceback (most recent call last):
   File pyshell#65, line 1, in module
 from PIL import ImageGrab
   File /Library/Python/2.7/site-packages/PIL/ImageGrab.py, line 34,
in module
 import _grabscreen
ImportError: No module named _grabscreen

 From what I've seen online, this isn't available for mac...of course
everything about this module is several years old, and it hasn't been
updated with a new version in a few years, so I think there must be
something better than it.



https://pypi.python.org/pypi/Pillow/ is a fork of PIL.  I've never used 
it myself but here's hoping!!!


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


Re: [Tutor] No module named '_tkinter'

2013-12-08 Thread Reuben
Can you try importing the module '_tkinter'
On 09-Dec-2013 6:43 AM, pierre dagenais eq...@ncf.ca wrote:

 Hi,
 I'm running Ubuntu 10.04 and I've installed python 3.3.3 from the
 tarball at http://python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz

 Here is the error I get when trying to run tkinter.

 pierre@Sprint:~$ python3.3
 Python 3.3.3 (default, Dec  2 2013, 11:10:53)
 [GCC 4.6.3] on linux
 Type help, copyright, credits or license for more information.
  import tkinter
 Traceback (most recent call last):
   File stdin, line 1, in module
   File /usr/local/lib/python3.3/tkinter/__init__.py, line 40, in module
 import _tkinter # If this fails your Python may not be configured for
 Tk
 ImportError: No module named '_tkinter'
 

 I've tried installing python3-tk from the Ubuntu repository but it
 doesn't help.

 Any suggestion on how to install the tkinter module with this version?

 Thank you,

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

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


Re: [Tutor] saving Tkinter canvas as jpg

2013-12-08 Thread eryksun
On Sun, Dec 8, 2013 at 8:49 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:

 https://pypi.python.org/pypi/Pillow/ is a fork of PIL.  I've never used it
 myself but here's hoping!!!

ImageGrab has built-in support for Microsoft Windows only:

https://github.com/python-imaging/Pillow/blob/2.2.1/PIL/ImageGrab.py#L29
https://github.com/python-imaging/Pillow/blob/2.2.1/_imaging.c#L3365
https://github.com/python-imaging/Pillow/blob/2.2.1/display.c#L313

A Tk canvas supports saving to a PostScript file, if that suffices
(i.e. if you can render PostScript as an image):

canvas.postscript(file='filename.ps', colormode='color')

http://www.tcl.tk/man/tcl8.5/TkCmd/canvas.htm#M51

OS X includes a screencapture utility that you could call with the
subprocess module:

http://ss64.com/osx/screencapture.html

This answer on Stack Overflow uses the OS X CoreGraphics API:

http://stackoverflow.com/a/13026264/205580
http://pythonhosted.org/pyobjc/apinotes/Quartz.html

Or you could switch to a GUI toolkit with better support for saving
images, such as Qt:

https://qt-project.org/doc/qt-4.8/qpixmap.html
https://qt-project.org/doc/qt-4.8/qpainter.html

Here's a really basic example using PyQt4. Clicking on the Capture
button paints the widget to a pixmap that's then saved to spam.png
and the desktop to screenshot.jpg with 95% quality.

import sys
from PyQt4 import QtCore, QtGui

class Spam(QtGui.QWidget):
def __init__(self):
super(Spam, self).__init__()
self.setGeometry(100, 100, 300, 225)
self.setWindowTitle(Spam)
self.btncap = QtGui.QPushButton(Capture, self)
self.btncap.clicked.connect(self.capture)
self.show()

def paintEvent(self, event):
p = QtGui.QPainter(self)
p.setFont(QtGui.QFont(Times, 20))
flags = QtCore.Qt.AlignBottom | QtCore.Qt.AlignRight
p.drawText(event.rect(), flags, Spam)

def capture(self):
wid = app.desktop().winId()
QtGui.QPixmap.grabWidget(self).save(
spam.png, png)
QtGui.QPixmap.grabWindow(wid).save(
screenshot.jpg, jpg, 95)


if __name__ == __main__:
app = QtGui.QApplication(sys.argv)
spam = Spam()
sys.exit(app.exec_())
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor