Re: [Tutor] Guess my number? Guess what's wrong!

2010-04-17 Thread Jim Byrnes

Matthew Carpenter-Arevalo wrote:

Hi Everyone,

I'm a beginner python programmer, and I've been working on
the perennial 'guess my number' example.

When I run this in my module, I get an infinite loop of 'higher' or 'lower.'
Can anyone see where I'm going wrong herE?

Thanks,

MCA


# Guess my number

# the computer picks a random number between 1 and 100
# the player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

print "\tWelcome to 'Guess my number'!"
print "\nI'm think of a number between 1 and 100."
print "Try to guess it in as few attempts as possible. \n"

# set the initial values
# the number - represents the number the player has to guess
# raw_input = the player's first guess&  converts it into an integer.
# tries = # of guesses so far.

import random

the_number = random.randrange(100) + 1
guess = int(raw_input("Take a guess: "))
tries = 1

# guessing loop
while (guess != the_number):
 if (guess>  the_number):
 print "lower..."
 else:
 print "Higher..."

guess = int(raw_input("Take a guess: "))
tries += 1


Move the above two lines to align with "else" so they become part of the 
while loop.



print "You guessed it! The number was", the_number
print "and it only took you", tries, "tries!\n"

raw_input("\n\nPress the enter key to exit.")


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


[Tutor] PIL problem

2010-05-07 Thread Jim Byrnes
Running Unbuntu 9.10. The Synaptic Pkg Mgr reports python-imaging - 
1.1.6-3ubuntu1 - Python Imaging Library is installed.


But trying to import PhotoImage gives these results:


>>> from ImageTk import PhotoImage
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named ImageTk

What have I gotten wrong?

Thanks, Jim

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


Re: [Tutor] PIL problem

2010-05-07 Thread Jim Byrnes

Martin Walsh wrote:

Jim Byrnes wrote:

Running Unbuntu 9.10. The Synaptic Pkg Mgr reports python-imaging -
1.1.6-3ubuntu1 - Python Imaging Library is installed.

But trying to import PhotoImage gives these results:



from ImageTk import PhotoImage

Traceback (most recent call last):
   File "", line 1, in
ImportError: No module named ImageTk

What have I gotten wrong?



Apparently, ImageTk is part of a separate ubuntu package called
python-imaging-tk.

HTH,
Marty


Thanks, once I installed that separate package it worked.

Regards,  Jim


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


Re: [Tutor] PIL problem

2010-05-07 Thread Jim Byrnes

Alex Clark wrote:

On 2010-05-07, Jim Byrnes  wrote:

Running Unbuntu 9.10. The Synaptic Pkg Mgr reports python-imaging -
1.1.6-3ubuntu1 - Python Imaging Library is installed.

But trying to import PhotoImage gives these results:



from ImageTk import PhotoImage

Traceback (most recent call last):
File "", line 1, in
ImportError: No module named ImageTk

What have I gotten wrong?



Try import PIL.ImageTk

(if you look inside the package, you will notice ImageTk is inside a directory 
called PIL)



I didn't have a necessary package installed.  Once it is installed 
import ImageTk works.


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


Re: [Tutor] Trying to get this to work - attached is the source code

2010-05-17 Thread Jim Byrnes

Walter Prins wrote:

Hi Peter,

We're not familiar with the book, so you'll have to tell us exactly what
you're doing, what you're seeing, and what you're expecting ot see instead.

Suffice it to say, the script seems fine.  When you run it (from an
operating system command prompt) it will print, in the command window, the
output in block letters etc.


Could be this is the problem.  If it is not started at the command 
prompt you won't see anything.  Tripped me up when I first started.



You don't really (I suppose) want to be entering those statements directly
into the interpreter (which is what I'm guessing "typing it manually" might
mean), although they should also work.  Obviously the exact output will be
different because if you enter the lines in the program manually into the
interpreter each line will be executed straight after entry.


I would guess that this means he types the program from the book, saves 
it and then runs it.  I often do this also, I find that it slows me down 
and I tend to pay more attention to what I am reading.



Regards,  Jim


Walter




___
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


[Tutor] OOP clarification needed

2010-06-01 Thread Jim Byrnes
Whenever I teach myself a new language I have great difficulty 
understanding the nuts and bolts of it's OO implementation. Compared to 
some older procedural languages I always end up becoming confused by the 
large number of built in methods.  When reading through code examples I 
many times get hung up on trying to figure out just where some methods 
come from.


Case in point is this code snippet from a chapter on Tkinter.

def viewer(imgdir, kind=Toplevel, cols=None):
"""
make thumb links window for an image directory:
one thumb button per image; use kind=Tk to show
in main  app window, or Frame container (pack);
imgfile differs per loop: must save with a default;
photoimage objs must be saved: erased if reclaimed;
"""
win = kind()
win.title('Viewer: ' + imgdir)
thumbs = makeThumbs(imgdir)


What is the relationship between kind=Toplevel in the first line and 
win=kind() further down.  Isn't "kind" a variable and "kind()" a method? 
 I've probable overlooked something fundamental but  a explanation 
would be appreciated.


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


Re: [Tutor] OOP clarification needed

2010-06-02 Thread Jim Byrnes

Steve Willoughby wrote:

On Tue, Jun 01, 2010 at 03:19:17PM -0500, Jim Byrnes wrote:

def viewer(imgdir, kind=Toplevel, cols=None):
 win = kind()

What is the relationship between kind=Toplevel in the first line and
win=kind() further down.  Isn't "kind" a variable and "kind()" a method?


kind is a variable.  Specifically, the second parameter passed to the viewer()
function defined here.

By saying kind() here, you are invoking it on the assumption that kind's
value is a reference to some kind of callable object.  So in theory you
could pass a function as the "kind" parameter of viewer() and that function
would get called, and its return value stored in "win".

In this case, though, the intent is for "kind" to refer to an object class
(the kind of widget this viewer is contained in or whatever).  Recalling that
object classes are themselves callable objects (specifically, calling them
is how you construct new instances of a class), "win" will end up referring
to a newly-constructed instance of whatever object class was passed as "kind".
If no "kind" parameter was given, it will default to tk.Toplevel.



Thanks for the explanation.  I didn't understand how (or why) "kind" 
could change to "kind()". Sometimes I can manage to trip myself up over 
the silliest things.


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


Re: [Tutor] OOP clarification needed

2010-06-02 Thread Jim Byrnes

Alan Gauld wrote:

"Jim Byrnes"  wrote


Whenever I teach myself a new language I have great difficulty
understanding the nuts and bolts of it's OO implementation.


Do you understand the OO concepts OK?
Is it only the language semantics you struggle with
or the underlying OO concepts?


I believe I understand the theory, but struggle with the actual 
implementation.



some older procedural languages I always end up becoming confused by
the large number of built in methods.


C is one of the simplest procedural languages around
and yet it comes with a huge library of functions (several
hundred in some cases). The size of the library should be easier
to manage using OOP than with older function/procedure based
libraries, because the functions are not just logically grouped
in the documentation but in the code too.


I don't know C, I was thinking more along the lines of Basic or Rexx.I 
could sit down and read through a list of keywords and built in 
functions and it would be compact enough that I would have a good idea 
of what was available.  I can't seem to do that with the OO languages, 
but of course  I am older now also.



Case in point is this code snippet from a chapter on Tkinter.

def viewer(imgdir, kind=Toplevel, cols=None):
"""
make thumb links window for an image directory:
one thumb button per image; use kind=Tk to show
in main app window, or Frame container (pack);
imgfile differs per loop: must save with a default;
photoimage objs must be saved: erased if reclaimed;
"""
win = kind()
win.title('Viewer: ' + imgdir)
thumbs = makeThumbs(imgdir)


What is the relationship between kind=Toplevel in the first line and
win=kind() further down.


kind is a parameter ogf the function with a default value of Toplevel.
Toplevel being a class. Recall that in Python classes are objects
too and can be assigned to variables. This is similar to Smalltalk,
Lisp, Objective C and Delphi(Object Pascal) but different to C++
and Java (actually I'm not sure about Java?).


Isn't "kind" a variable and "kind()" a method?


No kind() is an invocation of a callable object.
In Python callables tend to be either functions
or classes or methods of objects.
In this case it is an instantiation of a class.
In C++ or Java it would look something like:

win = new kind();

Because classes can be treated as objects and passed to functions
this instantiates whatever kind of object was passed into viewer.
As the comment says this could be the top level window Tk or
a generic Frame container or the default Toplevel. So long as the
new object supports all the methods that will be invoked Python
doesn't care. This is polymorphism...



I had completely forgotten about the callable object.  I saw the ()'s 
and wrongly started to think of it as a method.  Thanks for the explanation.


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


Re: [Tutor] OOP clarification needed

2010-06-02 Thread Jim Byrnes

Steven D'Aprano wrote:



Case in point is this code snippet from a chapter on Tkinter.

def viewer(imgdir, kind=Toplevel, cols=None):
  """
  make thumb links window for an image directory:
  one thumb button per image; use kind=Tk to show
  in main  app window, or Frame container (pack);
  imgfile differs per loop: must save with a default;
  photoimage objs must be saved: erased if reclaimed;
  """
  win = kind()
  win.title('Viewer: ' + imgdir)
  thumbs = makeThumbs(imgdir)






In the example you give, you have an argument named "kind". It is
expected to be some sort of function or class, and gets the default
value of TopLevel if not supplied. In the body of the function, this
function or class is called, to produce a value which is then
named "win". Judging by the default value and the name of the inner
variable, I would say it is expected to produce a window object, so any
function or class that returns a window object will be suitable.



I completely overlooked this expectation, which led to my confusion. 
Thanks for the explanation.


Regards,  Jim


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


[Tutor] Tkinter - master attribute

2010-06-08 Thread Jim Byrnes
When reading code examples I see things like 
theframe.master.title('spam) or

def __init__(self, master):
frame = Frame(master)

When I encounter these I tend to get bogged down trying to decide if 
"master" has special meaning or is just a name the author has chosen. 
For example is it similar to Buttton(text='spam) where text in this case 
has special meaning.


I've goolged and found references to "widgets master attributes" but 
nothing to really explain it.  Could someone point me to a good 
reference so that I could better understand it use.


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


Re: [Tutor] Tkinter - master attribute

2010-06-15 Thread Jim Byrnes

Alan Gauld wrote:


"Jim Byrnes"  wrote in


When reading code examples I see things like



theframe.master.title('spam)



def __init__(self, master):
frame = Frame(master)



When I encounter these I tend to get bogged down trying to decide if
"master" has special meaning or is just a name the author has chosen.


In the first case master is an attribute of the frame and as
such is defined by the frame definition.

In the second case master is just an arbitrary name for a
parameter like any other. Because it is being used to correspond
to the master attribute of the Framer(as seen in the call to Frame() )
the author has used the name master too. But other common
names for the same attribute are parent, root, top, etc


For example is it similar to Buttton(text='spam) where text in this
case has special meaning.


In the first example yes, in the second no.
Although 'text' is even more special because it is actually defined in
the underlying Tk code rather than in Tkinter Python code.


I've goolged and found references to "widgets master attributes" but
nothing to really explain it. Could someone point me to a good
reference so that I could better understand it use.


Because Tkinter is a thin wrapper around the underlying Tk tookit
many atttributes of widgets are actually defined in the Tk code
and simply mirrored by Tkinter. In that sense the widget attributes
tend to have fixed names. But in Tkinter code the naming is
essentially arbitrary and follows the usual Python naming
conventions.

HTH,



Alan,

Sorry it took so long for me to get back to this issue.  Thanks to you 
and Steve for your replies.


I still am having trouble understanding the use of "master" in Tkinter. 
I think the problem is I can't find any reference that explains the 
concept around master, like the Button example I gave above.  If I want 
to put the word spam on a Button I found a reference that said you type 
the word text followed by an equal sign followed by spam in quotes.


Let me try another example.  The code snippet below comes from a working 
example out of a book:


class CanvasEventsDemo(canvasDraw.CanvasEventsDemo):
def __init__(self, parent=None):
canvasDraw.CanvasEventsDemo.__init__(self, parent)
self.canvas.create_text(75, 8, text='Press o and r to move shapes')
self.canvas.master.bind('', self.onMoveOvals)
self.canvas.master.bind('', self.onMoveRectangles)
self.kinds = self.create_oval_tagged, self.create_rectangle_tagged


The word master appears only twice in the entire script so it is not 
defined somewhere else in the script.  As an experiment I changed them 
both to masterx.  When I ran the script I got the following error:


Traceback (most recent call last):
  File "canvasDraw_tags.py", line 41, in 
CanvasEventsDemo()
  File "canvasDraw_tags.py", line 16, in __init__
self.canvas.masterx.bind('', self.onMoveOvals)
AttributeError: Canvas instance has no attribute 'masterx'

So the Canvas does not have a masterx attribute but does have one called 
master.  Maybe the bottom line question is where can I look to see a 
list of a widgets attributes?


Sorry to be so dense about this but I just don't get it yet.

Thanks,  Jim

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


Re: [Tutor] Tkinter - master attribute

2010-06-16 Thread Jim Byrnes

ALAN GAULD wrote:




I still am having trouble understanding the use of "master" in
Tkinter. I think the problem is I can't find any reference that explains the
concept around master,


If you read the GUI topic in my tutorial it explains the concept
of a containment tree that is common to ost GUI frameworks
including Tkinter. All widgets belong to a parent or master
widget until you get to some kind of root or main window that
is the master odf all its sub widgets.


I'll make it my next stop.


When you delete a window you delete the master and it deletes
all its children. The children delete their children, and so on until
all the widgets making up the window are deleted. Thats how GUIs work.
Similarly if you add a widget to a window you must tell the new
widget where within the containment tree it sits, you tell it who
its master is. Usually the widget will register itself with its master.


put the word spam on a Button I found a reference that said you type the word
text followed by an equal sign followed by spam in quotes.


That's slightly different in that text is an attribute of the widget itself.
By assigning 'Spam' to the attribute you control the look of that particular
Button widget.


OK.  That was the best example I could come up with to convey my 
confusion concerning master.  I could look at a reference and see that 
in that context the word text had a special purpose, I couldn't do that 
with master.



class CanvasEventsDemo(canvasDraw.CanvasEventsDemo):
def __init__(self, parent=None):
 canvasDraw.CanvasEventsDemo.__init__(self, parent)

Here parent is being used instead of master. Thats quite common.


Its usage like this that tends to confuse me. If I change all 
occurrences of of parent to Xparent the program runs.  If I replace 
parent with master the program runs.  If I replace canvas.master with 
canvas.xmaster I get an error.



self.canvas.master.bind('', self.onMoveOvals)


Here the master attribute is being accessed. That is an attribute
of the canvas widget.


word master appears only twice in the entire script so it is not defined
somewhere else in the script.


It is an inherited attribute and is inherited by all widgets
although from where is a little bit mysterious - see below...


AttributeError: Canvas instance has no attribute
'masterx'

So the Canvas does not have a masterx attribute but does have
one called master.  Maybe the bottom line question is where can I look to
see a list of a widgets attributes?


You can use dir() or help().
However in Tkinter it is further complicated by the mapping of Tkinter
to the underlying Tk widgets. It is not always 1-1 and some attributes
are implemented by the Tk tookit rather than at the Tkinter level and
these do not always show up in dir(). Master appears to be one of these.

However, on digging a little deeper it seems there is a subtle distinction
in Tkinter between the containment hierarchy and the geometry manager
hierarchy. I confess that I've never noticed this before and have only
skimmed the material(Grayson's Tkinter book)  but it seems that master
refers to the GM hierarchy and parent to the containment one. In most
cases they will be the same but they can be different. But because of
this master seems to be implemented somewhere in the GM code
rather than the widget code...

In most cases you can ignore that - as I have been doing for the last 10 years! 
:-)
Just use master as an inherited attribute that is present in all widgets.


OK, good.  This is what I was looking for, an explicit statement of what 
master is.



Sorry to be so dense about this but I just don't get it yet.


You are not being dense but asking rather deep questions which
probably need someone who understands the Tkinter implementatioon
to answer. You probably don't really need to know the detail, just accept
that master will be the attribute and it will be there in each widget class
you use.


I really wasn't trying to delve deep into the innards of Tkinter, it 
just seemed like master was appearing like magic and I just wanted to 
nail it down so I could get on learning Python.



If I get the time I will try to track this down further now that you have
piqued my curiosity.

HTH,


It does, I finally feel like I have a handle on it. Thanks for your time 
and patience.


Regards,  Jim


Alan G.



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


[Tutor] os.startfile?

2010-06-24 Thread Jim Byrnes

I am trying to run an example program that contains the line
os.startfile('socket-nongui.py') which is Windows only.  What would be 
the command to use on Linux?  All files are in the same folder.


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


Re: [Tutor] os.startfile?

2010-06-24 Thread Jim Byrnes

Nethirlon wrote:

On Thu, Jun 24, 2010 at 7:36 PM, Jim Byrnes  wrote:

I am trying to run an example program that contains the line
os.startfile('socket-nongui.py') which is Windows only.  What would be the
command to use on Linux?  All files are in the same folder.

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



Hi Jim,

Is this perhaps what you are looking for?

import os
os.system('ls -lt>  output.txt')

Kind regards,
Nethirlon



I don't think so but it is my fault.  When I asked the question I 
thought I gave enough info but I see now that I didn't.


The os.startfile('socket-nongui.py) line was in a gui program that 
demonstrates how to start and communicate with a non-gui program.  It is 
Windows specific so I looked for but could not find a drop  in 
replacement that works on Linux.


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


Re: [Tutor] Help with choices for new database program

2010-07-03 Thread Jim Byrnes

Jeff Johnson wrote:

On 07/02/2010 11:40 AM, Chris C. wrote: I'm writing this question
because I want, for my own satisfaction, to rewrite one of my Access dbs
(one that does our finances) into a stand-alone Python database program
using SQLite. I know I'll be learning as I go, but that'll work, I'm not
in a big hurry and I'll work on it in my spare time. Right now I'm
trying to get organized and get a game plan, and that's where I need help.

I have been developing database applications for 20 years using FoxPro
and VFP. Now I am developing using Dabo. Dabo is a framework wrapper for
wxPython written totally in Python. I use SQLite for small applications
and PostgreSQL for larger ones. Dabo was written by two of the top
FoxPro developers and is supported by many others all over the world.

http://dabodev.com/

Please check it out. And go to www.leafe.com and subscribe to the
dabo-user email list.



I would like to try out Dabo, but I don't see it in the Ubuntu 
repositories and I would like to avoid using svn if I can.  I didn't 
subscribe to the mailing list but I did read the archives and saw a 
thread about making a deb package.  It seems to have ended in April 
without a clear resolution.


So is there a package available so I can use the Ubuntu package manager 
to install it?


Thanks,  Jim

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


Re: [Tutor] Help with choices for new database program

2010-07-04 Thread Jim Byrnes

Martin Walsh wrote:

On 07/03/2010 10:25 AM, Jim Byrnes wrote:

Jeff Johnson wrote:


[snip]


http://dabodev.com/

Please check it out. And go to www.leafe.com and subscribe to the
dabo-user email list.


I would like to try out Dabo, but I don't see it in the Ubuntu
repositories and I would like to avoid using svn if I can.  I didn't
subscribe to the mailing list but I did read the archives and saw a
thread about making a deb package.  It seems to have ended in April
without a clear resolution.

So is there a package available so I can use the Ubuntu package manager
to install it?


Unfortunately, after poking around a bit it would seem the only reliable
way of installing dabo for Linux at the moment is checking out trunk
from the project's subversion repository. Someone better informed should
feel free to set the record straight, if I am mistaken.

If your interest in a deb package is mainly the ability to uninstall,
then I'd recommend using virtualenv[1] until a suitable deb package is
released. The steps would be roughly this (untested) ...


That's part of it but mainly it's that they are so easy to install.


$ sudo apt-get install python-reportlab python-wxgtk2.8
$ sudo apt-get install subversion python-virtualenv
$ virtualenv daboenv
$ cd daboenv
$ source bin/activate # this is important
# now we install dabo as recommended, adapted from:
#   http://wiki.dabodev.com/InstallationOnLinux
(daboenv)$
(daboenv)$ mkdir src&&  cd src
(daboenv)$ svn co http://svn.dabodev.com/dabo/trunk dabo
(daboenv)$ cd dabo
(daboenv)$ python setup.py install # no sudo!
# and run the demo to verify the installation
(daboenv)$ demo/DaboDemo.py

...

Hmm, this might seem like a lot of work -- but by using this method,
dabo is installed under daboenv and not in the system-wide site-packages
-- particularly useful for evaluation, IMO. YMMV.


I read the website [1] and being new to linux there was a lot I did not 
understand.  I think I will go the svn route on a test machine before I 
put it on my main machine.



HTH,
Marty

[1] http://virtualenv.openplans.org/


Thanks, Jim

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


[Tutor] Path?

2010-07-11 Thread Jim Byrnes
I am running Ubuntu.  I downloaded the source code examples for a book I 
purchased.  Some of the examples load image files located in the same 
directory as the program.  If I go to the current directory in the 
terminal the program can use the image files.  However, if I use a 
launcher or the filemanager it pops up an error dialog saying the file 
does not exist even though it is in the same directory.


The program simply uses the files name.  Is there a way without editing 
the source and inserting the full path to run the program from a 
launcher or the filemanager and allow it to see files in the current 
directory?


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


Re: [Tutor] Path?

2010-07-13 Thread Jim Byrnes

Steven D'Aprano wrote:

My apologizes to Steven and the list, when I replied originally I messed 
up and sent it to him privately which was not my intention.



> On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
>> I am running Ubuntu.  I downloaded the source code examples for a
>> book I purchased.  Some of the examples load image files located in
>> the same directory as the program.  If I go to the current directory
>> in the terminal the program can use the image files.  However, if I
>> use a launcher or the filemanager it pops up an error dialog saying
>> the file does not exist even though it is in the same directory.
>>
>> The program simply uses the files name.  Is there a way without
>> editing the source and inserting the full path to run the program
>> from a launcher or the filemanager and allow it to see files in the
>> current directory?
>
> What file manager are you using? Nautilus? Konqueror? Something else?

Nautilus. I have it configured to run files with the extension .py when 
they are double clicked.


> What do you mean, "use a launcher"? Use a launcher to do what? What sort
> of launcher?

It runs programs and sits on the panel at the top of my Ubuntu desktop. 
 The command it uses is usr/bin/python2.6.  These are wxPython examples 
I am working with.


> What pops up an error dialog? The launcher?

I am assuming Python. The title bar of the dialog says Python2 Error, 
the message is   Can't load image from file 'wxPython.jpg': file does 
not exist.


> Which file does it claim doesn't exist? Python? The Python script? The
> image file? What is the exact error message it gives?

See above.  The line that triggers the error is:  image = 
wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)


> There's probably a way to tell the launcher which working directory to
> use, but of course that depends on the answers to the above questions.
>

If I use the terminal to start the program it has no problem using the 
file.  There are multiple files in multiple directories so I was looking 
for a way to just double click them and have them run.  If it turns out 
that I must make changes to or for each of the files it will be easier 
to just keep using the terminal.  I've only been using Ubuntu for a few 
months so I was surprised that the program could not see a file that is 
in the same directory.


Regards,  Jim

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


Re: [Tutor] Path?

2010-07-13 Thread Jim Byrnes

Adam Bark wrote:

On 13 July 2010 14:43, Jim Byrnes  wrote:


Steven D'Aprano wrote:

My apologizes to Steven and the list, when I replied originally I messed up
and sent it to him privately which was not my intention.




On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:

I am running Ubuntu.  I downloaded the source code examples for a
book I purchased.  Some of the examples load image files located in
the same directory as the program.  If I go to the current directory
in the terminal the program can use the image files.  However, if I
use a launcher or the filemanager it pops up an error dialog saying
the file does not exist even though it is in the same directory.

The program simply uses the files name.  Is there a way without
editing the source and inserting the full path to run the program
from a launcher or the filemanager and allow it to see files in the
current directory?


What file manager are you using? Nautilus? Konqueror? Something else?


Nautilus. I have it configured to run files with the extension .py when
they are double clicked.



What do you mean, "use a launcher"? Use a launcher to do what? What sort
of launcher?


It runs programs and sits on the panel at the top of my Ubuntu desktop.
  The command it uses is usr/bin/python2.6.  These are wxPython examples I am
working with.



What pops up an error dialog? The launcher?


I am assuming Python. The title bar of the dialog says Python2 Error, the
message is   Can't load image from file 'wxPython.jpg': file does not exist.



Which file does it claim doesn't exist? Python? The Python script? The
image file? What is the exact error message it gives?


See above.  The line that triggers the error is:  image =
wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)



There's probably a way to tell the launcher which working directory to
use, but of course that depends on the answers to the above questions.



If I use the terminal to start the program it has no problem using the
file.  There are multiple files in multiple directories so I was looking for
a way to just double click them and have them run.  If it turns out that I
must make changes to or for each of the files it will be easier to just keep
using the terminal.  I've only been using Ubuntu for a few months so I was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim



The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.



OK, I mistakenly thought that double-clicking on file in Nautilus would 
take care of the path info.


In my reply above I also mentioned that I tried by dropping it on a 
Launcher on the top panel and that the command the launcher uses is 
usr/bin/python2.6.  Is there a way that the command can be changed so 
that it will look in the same directory the python script is in for any 
file it needs?


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


Re: [Tutor] Path?

2010-07-13 Thread Jim Byrnes

Adam Bark wrote:




If I use the terminal to start the program it has no problem using the
file.  There are multiple files in multiple directories so I was looking
for
a way to just double click them and have them run.  If it turns out that
I
must make changes to or for each of the files it will be easier to just
keep
using the terminal.  I've only been using Ubuntu for a few months so I
was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim




The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.



OK, I mistakenly thought that double-clicking on file in Nautilus would
take care of the path info.

In my reply above I also mentioned that I tried by dropping it on a
Launcher on the top panel and that the command the launcher uses is
usr/bin/python2.6.  Is there a way that the command can be changed so that
it will look in the same directory the python script is in for any file it
needs?

Thanks,  Jim



Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

HTH,
Adam.



I got it, got sidetracked and then forgot to look at it again.  Thanks 
for reminding me.  Your idea works, but with one little downside.  The 
directories I am working with are chapters in a book.  So as I move from 
chapter to chapter I will need to change the bash script, but this seems 
to be less typing than using the terminal.


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


Re: [Tutor] Path?

2010-07-14 Thread Jim Byrnes

Adam Bark wrote:

On 14 July 2010 02:53, Jim Byrnes  wrote:


Adam Bark wrote:




  If I use the terminal to start the program it has no problem using the

file.  There are multiple files in multiple directories so I was
looking
for
a way to just double click them and have them run.  If it turns out
that
I
must make changes to or for each of the files it will be easier to just
keep
using the terminal.  I've only been using Ubuntu for a few months so I
was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim




The problem is ubuntu doesn't run the script from the directory it's in
so
it's looking for wxPython.jpg somewhere else.


  OK, I mistakenly thought that double-clicking on file in Nautilus would

take care of the path info.

In my reply above I also mentioned that I tried by dropping it on a
Launcher on the top panel and that the command the launcher uses is
usr/bin/python2.6.  Is there a way that the command can be changed so
that
it will look in the same directory the python script is in for any file
it
needs?

Thanks,  Jim




Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as
your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

HTH,
Adam.



I got it, got sidetracked and then forgot to look at it again.  Thanks for
reminding me.  Your idea works, but with one little downside.  The
directories I am working with are chapters in a book.  So as I move from
chapter to chapter I will need to change the bash script, but this seems to
be less typing than using the terminal.


Thanks,  Jim



Ok cool, glad it works. It might be possible to get the path so you don't
have to set it each time, try this:

#!/bin/bash
IFS="/"
path=($1)
cd $(path[0:#path[*]])
python $1


# Warning, I'm not exactly a competent bash programmer so this may not work
:-p

Let me know if you need a hand to fix it,

HTH,
Adam.



I tried the new bash code but when I dropped a file on the launcher it 
just flashed an gave no output.  So I tried running the bash script 
(name=runpython) in a terminal and got this error:


/home/jfb/runpython: line 4: path[0:#path[*]]: command not found
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

I know even less about bash than you do, so I don't where to start to 
debug this.


Thanks,  Jim

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


Re: [Tutor] Path?

2010-07-15 Thread Jim Byrnes

Adam Bark wrote:

On 14 July 2010 17:41, Jim Byrnes  wrote:


Adam Bark wrote:


On 14 July 2010 02:53, Jim Byrnes   wrote:

  Adam Bark wrote:





  If I use the terminal to start the program it has no problem using the


  file.  There are multiple files in multiple directories so I was

looking
for
a way to just double click them and have them run.  If it turns out
that
I
must make changes to or for each of the files it will be easier to
just
keep
using the terminal.  I've only been using Ubuntu for a few months so
I
was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim




The problem is ubuntu doesn't run the script from the directory it's
in
so
it's looking for wxPython.jpg somewhere else.


  OK, I mistakenly thought that double-clicking on file in Nautilus
would


take care of the path info.

In my reply above I also mentioned that I tried by dropping it on a
Launcher on the top panel and that the command the launcher uses is
usr/bin/python2.6.  Is there a way that the command can be changed so
that
it will look in the same directory the python script is in for any file
it
needs?

Thanks,  Jim




Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as
your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

HTH,
Adam.


  I got it, got sidetracked and then forgot to look at it again.  Thanks

for
reminding me.  Your idea works, but with one little downside.  The
directories I am working with are chapters in a book.  So as I move from
chapter to chapter I will need to change the bash script, but this seems
to
be less typing than using the terminal.


Thanks,  Jim



Ok cool, glad it works. It might be possible to get the path so you don't
have to set it each time, try this:

#!/bin/bash
IFS="/"
path=($1)
cd $(path[0:#path[*]])
python $1


# Warning, I'm not exactly a competent bash programmer so this may not
work
:-p

Let me know if you need a hand to fix it,

HTH,
Adam.



I tried the new bash code but when I dropped a file on the launcher it just
flashed an gave no output.  So I tried running the bash script
(name=runpython) in a terminal and got this error:

/home/jfb/runpython: line 4: path[0:#path[*]]: command not found
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.




I know even less about bash than you do, so I don't where to start to debug
this.


Thanks,  Jim

Ok then, this time it's tested and not just improvised, here we go:


#!/bin/bash

script=$1 # Full path for calling the script later
orig_IFS=$IFS # This is to reset IFS so that "script" is correct (otherwise
has spaces instead of /)
IFS="/"
path=( $1 )
IFS=$orig_IFS
last_ind=${#pa...@]} # Works out the length of path
let "last_ind -= 1" # Sets last_ind to index of script name
len_path=${pa...@]:0:last_ind} # Gets the path without the script name
let "len_path=${#len_path[0]} + 1" # This gives the length of the script
string upto just before the last /
cd ${scri...@]:0:len_path} # cds to the path
python script


As pretty much my first non-trivial bash script it's probably horrible but
it seems to work.

HTH,
Adam.



There must be something different in our setups because it did not work 
for me.  If I run it from a terminal I get:


j...@jfb-ubuntu64:~$ /home/jfb/runpython_test bitmap_button.py
/home/jfb/runpython_test: line 12: cd: b: No such file or directory
python: can't open file 'script': [Errno 2] No such file or directory
j...@jfb-ubuntu64:~$

Thanks  Jim

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


[Tutor] Need help with the property function

2011-04-13 Thread Jim Byrnes
I'm trying to teach myself OOP in python (again). The following code 
from Dawson's book runs fine, unaltered [1].


class Critter(object):
""" A virtual pet """
def __init__(self, name):
print "A new critter is born"
self.name = name

def get_name(self):
return self.__name

def set_name(self, new_name):
if new_name == "":
print "A critters name cant be the empty string"
else:
self.__name = new_name
print "Name change successful"


name = property(get_name, set_name) #[1]
# name = property(get_name) #[2]
#different_name = property(get_name) #[3]

def talk(self):
print "Hi. I'm", self.name

If I change [1] to [2] I get:

Traceback (most recent call last):
  File "propertycritter.py", line 26, in 
crit = Critter("Poochie")
  File "propertycritter.py", line 7, in __init__
self.name = name
AttributeError: can't set attribute

If I change [1] to [3] the program runs with no errors.

Could someone please explain why I am seeing these results.

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


Re: [Tutor] Need help with the property function

2011-04-14 Thread Jim Byrnes

Steven D'Aprano wrote:

Jim Byrnes wrote:

I'm trying to teach myself OOP in python (again). The following code
from Dawson's book runs fine, unaltered [1].


What's Dawson's book?



Python Programming for the absolute beginner, by Michael Dawson



Thanks for the explanation.  It was exactly with I was hoping for.  The 
book and a couple of other resources I looked at didn't lay it out so 
completely.  They all assumed I knew more than I did.


Regards,  Jim

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


Re: [Tutor] Need help with the property function

2011-04-14 Thread Jim Byrnes

Dave Angel wrote:

On 01/-10/-28163 02:59 PM, Jim Byrnes wrote:

I'm trying to teach myself OOP in python (again). The following code
from Dawson's book runs fine, unaltered [1].

class Critter(object):
""" A virtual pet """
def __init__(self, name):
print "A new critter is born"
self.name = name

def get_name(self):
return self.__name

def set_name(self, new_name):
if new_name == "":
print "A critters name cant be the empty string"
else:
self.__name = new_name
print "Name change successful"


name = property(get_name, set_name) #[1]
# name = property(get_name) #[2]
#different_name = property(get_name) #[3]

def talk(self):
print "Hi. I'm", self.name

If I change [1] to [2] I get:

Traceback (most recent call last):
File "propertycritter.py", line 26, in 
crit = Critter("Poochie")
File "propertycritter.py", line 7, in __init__
self.name = name
AttributeError: can't set attribute

If I change [1] to [3] the program runs with no errors.

Could someone please explain why I am seeing these results.

Thanks, Jim



In case#2 you're making name a read-only property. So why on earth would
you expect to be able to modify that property?

DaveA




Because I was confused and didn't fully understand the process.  I was 
experimenting and trying understand it to use it something else I was 
writing.


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


[Tutor] Using python 3 on Ubuntu 14.04

2015-12-23 Thread Jim Byrnes
I am in the process of moving from unbutu 12.04 to 14.04. I was doing 
some testing and got this:


jfb@Jims-1404:~$ cd MyProgs
jfb@Jims-1404:~/MyProgs$ cd passwords
jfb@Jims-1404:~/MyProgs/passwords$ python3 passwords.py
Traceback (most recent call last):
  File "passwords.py", line 8, in 
from PythonCard import  model,clipboard
ImportError: No module named 'PythonCard'

If I simply start it with  python passwords.py  it runs fine. There is 
no need to use python 3 on this particular program but if I wanted to 
write for python 3 in the future what do I need to do to run programs 
with it?


Thanks,  Jim

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


Re: [Tutor] OT: How to automate user interactions with GUI elements of closed-source programs?

2015-12-24 Thread Jim Byrnes

On 12/24/2015 08:54 AM, boB Stepp wrote:

My Google-fu is weak on this question.  I keep getting lots of hits on
web scraping, but my interest is actually as follows:

I find myself doing the same boring, repetitive tasks by hand, which
amounts to copying certain information from one program and putting it
into other programs.  None of these programs, to my knowledge, have a
publicly accessible API.  Are there ways to programmatically
accurately click the right buttons (or check boxes, radio buttons,
etc.), copy desired fields and then switch to another program and
paste the desired information into the desired fields, accurately
clicking all things that need to be clicked, etc.?  This is mostly a
Windows-based scenario, but if the techniques (if they exist) can be
abstracted to any OS I can find plenty of uses elsewhere as well!

TIA!
Merry Christmas!!!



I don't know if there is a Python solution, as I am just starting to 
read up on using Python on the web. Either iMarcos or GreaseMonkey could 
probably do what you what you want.


Both are browser extensions.  iMacros is available for both Firefox and 
Chrome, GreaseMonkey is available for Firefox, but I'm not sure about 
Chrome. Both also have user forums.


Regards,  Jim

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


Re: [Tutor] Using python 3 on Ubuntu 14.04

2015-12-24 Thread Jim Byrnes

On 12/23/2015 07:52 PM, Alan Gauld wrote:

On 23/12/15 23:15, Nnamdi Anyanwu wrote:

If you're installing modules with pip, install pip3 and install the
appropriate modules using pip3 instead of using regular pip.


Most v3 modules are also available via the Ubuntu package system
so you can install via synaptic which I tend to find more reliable
than pip.

YMMV,



Thanks for all the info guys. I got myself confused because I thought 
that python 3 was the default for Ubuntu 14.04, but it is just installed 
by default. I realize now that the modules need to be installed in the 
proper environment.


I know Pythoncard is not maintained any more. I have one program I wrote 
using it that I use often so I wanted to see it worked on 14.04. It will 
be a good learning experience to rewrite it for python 3 using something 
else.


Regards,  Jim





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


Re: [Tutor] Using python 3 on Ubuntu 14.04

2015-12-24 Thread Jim Byrnes

On 12/24/2015 04:03 PM, Ben Finney wrote:

Jim Byrnes  writes:


Thanks for all the info guys. I got myself confused because I thought
that python 3 was the default for Ubuntu 14.04, but it is just
installed by default.


Even if that were true, the ‘python’ command will likely still invoke
a Python 2 interpreter. Most systems that install a Python 3 interpreter
will install the command as ‘python3’.


Misunderstanding that was also part of my confusion.


I realize now that the modules need to be installed in the proper
environment.


That also remains true when Python 3 is the default.


I realize that now.


I know Pythoncard is not maintained any more. I have one program I
wrote using it that I use often so I wanted to see it worked on 14.04.
It will be a good learning experience to rewrite it for python 3 using
something else.


Have you considered using Python 3 and the standard Tkinter tookit?
https://docs.python.org/3/library/tkinter.html>
https://docs.python.org/3/library/tkinter.ttk.html>
http://www.tkdocs.com/>



Yes, that is something I plan to look at once I get 14.04 all set up the 
way I want and it becomes my default system.


Thanks,  Jim


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


[Tutor] Variable in tkinter?

2016-07-23 Thread Jim Byrnes
I have been working my way through a Python 3 book and got to the 
chapter on tkinter. The following is a segment of a example program that 
works:


# the views
frame = tkinter.Frame(window)
frame.pack()
button = tkinter.Button(frame, text='Up', command=click_up)
button.pack()
button = tkinter.Button(frame, text='Down', command=click_down)
button.pack()
label = tkinter.Label(frame, textvariable=counter)
label.pack()

when I first looked at it I thought it would not work, thinking that the 
second reference to button = would over write the first one. Obviously 
that is wrong because the program does work.  Could someone explain to 
me why it works?


Regards,  Jim

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


Re: [Tutor] Variable in tkinter?

2016-07-24 Thread Jim Byrnes

On 07/24/2016 02:08 PM, Alan Gauld via Tutor wrote:

On 23/07/16 16:38, Jim Byrnes wrote:


# the views
frame = tkinter.Frame(window)
frame.pack()
button = tkinter.Button(frame, text='Up', command=click_up)
button.pack()
button = tkinter.Button(frame, text='Down', command=click_down)
button.pack()



that is wrong because the program does work.  Could someone explain to
me why it works?


Others have pointed out that a hidden reference to the buttons exists.
In fact Tkinter, in common with most GUIIs, works by building a tree of
objects starting at the top level window and then working down thru'
each lower level.

Usuially in Tkinter we start with  a line like

top = tkinter.Tk()   # create the topmost widget

Then when we create subwidgets, like your frame we
pass the outer widget as the parent:

frame = tkinter.Frame(top)

Then when you create the buttons you pass frame
as the first argument which makes frame the parent
of the buttons.

What happens is that when you create the widget the
parent object adds your new instance to its list of
child widgets. And that's the hidden reference that keeps
your button alive even after you overwrite the button
variable.

You can access the widget tree of any widget using
its 'children' attribute:



import tkinter as tk
top = tk.Tk()
f = tk.Frame(top)
f.pack()
tk.Label(f,text="Hello there!").pack()
f.children

{'140411123026128': }




But it's not very user friendly so if you need to access
a widget after creating it its better to use a unique
variable to store a reference.



Thanks Peter and Alan,

After I proved to myself that it worked and I thought about it, I 
suspected it had to do with a reference.  It's nice to have it confirmed 
is such a clear manner.


Regards,  Jim

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


[Tutor] OOP help needed

2016-07-26 Thread Jim Byrnes
OOP has always driven me crazy.  I read the material and follow the 
examples until I feel I understand them, but when I try to implement it 
I end up with an error filled mess.


So I decided to give it another try.  When I got to the chapter on 
tkinter I decided to solve all the exercises using OOP even though the 
book solutions did not use OOP. The first one went fine:


#exer1.py

import tkinter

class Goodbye:
  def __init__(self):

self.frame = tkinter.Frame(window)
self.frame.pack()

self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
  #command=quit)
  command=lambda: quit() )
self.goodbye_button.pack()

  def quit():
self.window.destroy()

if __name__=='__main__':
  window = tkinter.Tk()
  myapp = Goodbye()
  window.mainloop()

The second one was more trouble but I finally got it to work.

# exer2.py

import tkinter

class Count:

  def __init__(self):
''' Increment a button labeled 0, by 1 with each click '''
self.frame = tkinter.Frame(window)
self.frame.pack()
self.label = tkinter.StringVar()
self.label.set('0')
self.count_btn = tkinter.Button(self.frame, textvariable=self.label,
  command=lambda: self.increment(self.label ))
self.count_btn.pack()

  def increment(self, label):
count = int(self.label.get())
self.label.set(str(count + 1))

if __name__ == '__main__':
  window = tkinter.Tk()
  myapp = Count()
  window.mainloop()

I am having trouble understanding the difference between the two lines 
that contain lambda: command= .In exer1.py I can do command=lambda: 
quit().  In exer2.py if I do command=lambda: increment(self.label) I get 
this error:


Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
return self.func(*args)
  File "exer2.py", line 14, in 
command=lambda: increment(self.label ))
NameError: name 'increment' is not defined

Why do I get this error?  The situations look the same to me but they 
must be different somehow and I just don't see the difference.


Thanks,  Jim

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


Re: [Tutor] OOP help needed

2016-07-27 Thread Jim Byrnes

On 07/26/2016 11:38 PM, Ben Finney wrote:

Jim Byrnes  writes:


So I decided to give it another try. When I got to the chapter on
tkinter I decided to solve all the exercises using OOP even though the
book solutions did not use OOP.


Hmm, that sounds ill advised.

OOP is one tool among many; trying to apply it where it's a poor fit
will result in bad design and probably avoidable errors.

When learning to use a hacksaw, trying to solve everything using that
tool merely to learn it, would be a poor choice.


With anything more complex I would agree.  I am simply trying to get 
myself thinking about how OOP works and there aren't enough exercises in 
the book calling for OOP to give me much repetition.



# exer2.py

import tkinter

class Count:

  def __init__(self):
''' Increment a button labeled 0, by 1 with each click '''
[…]
self.count_btn = tkinter.Button(self.frame, textvariable=self.label,
  command=lambda: self.increment(self.label ))


Here you address the ‘self.increment’ name, which should work.


  def increment(self, label):
count = int(self.label.get())
self.label.set(str(count + 1))


This is the method that an instance will address via ‘self.increment’.


In exer2.py if I do command=lambda: increment(self.label)


The lambda expression creates a function, and that function then behaves
like any other function. Within that function, the name ‘increment’ is
not defined; within the scope where the function was defined, the name
‘increment’ is also not defined. Within the global scope the name
‘increment’ is not defined.

So yes, you'll get NameError from that code.


Why do I get this error?  The situations look the same to me


The difference is that when you invoke ‘self.instance’, the lookup of
‘self’ succeeds because it's defined within the function (you defined it
in the parameters of ‘__init__’, so ‘__init__’ knows that name when it
is running).

You never defined the name ‘increment’ within the function, nor within
the global scope. And you shouldn't because there's no need: you access
the instance's own method by accessing the instance first: you ask for
“the ‘instance’ attribute from the ‘self’ object”: ‘self.instance’.



OK thank you.

Regards,  Jim


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


Re: [Tutor] OOP help needed

2016-07-27 Thread Jim Byrnes

On 07/27/2016 03:12 AM, Peter Otten wrote:

Jim Byrnes wrote:


OOP has always driven me crazy.  I read the material and follow the
examples until I feel I understand them, but when I try to implement it
I end up with an error filled mess.

So I decided to give it another try.  When I got to the chapter on
tkinter I decided to solve all the exercises using OOP even though the
book solutions did not use OOP. The first one went fine:


No, it didn't. The Goodbye.quit() method is missing the self argument and
uses the inexistent self.window attribute.
You don't see these bugs when you run the script because there is a global
quit()... let's say function... that is called instead of the method.

You can put a print() into Goodbye.quit() to verify the above.


OK right.  I ended up concentrating on exer2 when the problem was in 
exer1.  I should have known better than using quit() as a name.



#exer1.py

import tkinter

class Goodbye:
   def __init__(self):

 self.frame = tkinter.Frame(window)
 self.frame.pack()

 self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
   #command=quit)
   command=lambda: quit() )


The lambda is superfluous -- command=quit will already invoke the global
quit(). But what you actually intended is achieved with command=self.quit.
self.quit is called "bound method".


Ok, thanks.


 self.goodbye_button.pack()

   def quit():

   print("you'll never see this")

 self.window.destroy()

if __name__=='__main__':
   window = tkinter.Tk()
   myapp = Goodbye()
   window.mainloop()




Regards,  Jim


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


Re: [Tutor] OOP help needed

2016-07-27 Thread Jim Byrnes

On 07/27/2016 04:04 AM, Alan Gauld via Tutor wrote:

On 27/07/16 04:44, Jim Byrnes wrote:

OOP has always driven me crazy.  I read the material and follow the
examples until I feel I understand them, but when I try to implement it
I end up with an error filled mess.


That suggests that its not the OOP concept thats confusing
you but the language syntax. How to turn the concept into code?


That's exactly my problem, which is why I am solving problems with OOP 
when it's not necessary.  I wanted the practice.



So I decided to give it another try.  When I got to the chapter on
tkinter I decided to solve all the exercises using OOP even though the
book solutions did not use OOP. The first one went fine:


Actually not as fine as you thought. In effect you got lucky by
making a mistake that still resulted in your code doing
approximately what you expected. But it didn't really do
what you thought it did.


import tkinter

class Goodbye:
   def __init__(self):

 self.frame = tkinter.Frame(window)
 self.frame.pack()


You are using a global variable as your parent here. It would be
better to pass that in as an argument. Or better still to make
the call to Tk() inside the __init__ method. That's not really
an OOP thing though just a general good practice issue.
It's best to avoid relying on global variables in your
functions.


Ok thanks.  When I wrote that I was mimicking the style used in the 
book. I have read about avoiding globals if possible, but didn't think 
it through.



 self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
   #command=quit)
   command=lambda: quit() )
 self.goodbye_button.pack()


Here you assign quit to the button's command. That's OK because
there is a top level built-in function called quit which exits
the interpreter. It's a bit of a brutal way to exit your GUI
but it works.

But I guess you really wanted to call your quit method. Remember
to access anything in your class you have to use the self
prefix, so you should have said:

command=self.quit

or

command=lambda: self.quit()

Lambda doesn't really help in this case but it doesn't do
any harm either.


   def quit():
 self.window.destroy()


When you define a method inside a class you need to
explicitly include the self parameter. So this should be:

def quit(self):
  self.window.destroy()

But there's a snag, you don't store the window inside the
class. So self.window will cause an error. You either need
a line like

self.window = window

in your__init__ method

or use the global window variable like

def quit():
  window.destroy()

My preference would be to create a self.window instance variable,
inside init()then access the self.window in quit(). You would also
call mainloop() using self.window in your init()


if __name__=='__main__':
   window = tkinter.Tk()
   myapp = Goodbye()
   window.mainloop()


So if you took my advice this section of code would look like:

if __name__=='__main__':
Goodbye()


and init() would look like:

def __init__(self):
 self.window = tkinter.Tk()
 self.frame = tkinter.Frame(self.window)
 self.frame.pack()

 self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
  command=self.quit)
 self.goodbye_button.pack()

 self.window.mainloop()

If you read through that and understand it, it should give
you the clues as to why the second one behaved as it did.




Ok thanks.  I don't want to belabor the point but I basically had it 
that way because I didn't know any better. Now I know of a 
different/better way to do it.


Regards,  Jim

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


[Tutor] Regex/Raw String confusion

2016-08-03 Thread Jim Byrnes
I am reading Automate The Boring Stuff With Python.  In the chapter on 
Regular Expressions he talks about the python escape character being a 
'\' and regex using alot of backslashes. Then he says,  However, 
by putting an r before the first quote of the string value, you can 
mark the string as a raw sting, which does not escape characters.


He give this example:

import re

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print('Phone number found: ' + mo.group())


A couple of pages later he talks about parentheses having special 
meaning in regex and what to do if they are in your text.


In this case, you need to escape the ( and )  characters with a 
backslash. The \( and \) escape characters in the raw string passed to 
re.compile() will match actual parenthesis characters.


import re

phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My phone number is: (415) 555-4242.')
print(mo.group(1))
print()
print(mo.group(2))

Both examples work, but one place he says you can't escape raw strings 
and the other he says you can.  What am I missing here?


Regards, Jim

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


Re: [Tutor] Regex/Raw String confusion

2016-08-03 Thread Jim Byrnes

On 08/03/2016 06:21 PM, Alan Gauld via Tutor wrote:

On 03/08/16 20:49, Jim Byrnes wrote:


Regular Expressions he talks about the python escape character being a
'\' and regex using alot of backslashes.


In effect there are two levels of escape character, python and
the regex processor. Unfortunately they both use backslash!
Python applies its level of escape first then passes the
modified string to the regex engine which processes the
remaining regex escapes. It is confusing and one reason
you should avoid complex regexes if possible.


by putting an r before the first quote of the string value, you can
mark the string as a raw sting, which does not escape characters.


This avoids python  trying to process the escapes.
The raw string is then passed to the regex which will
process the backslash escapes that it recognises.


A couple of pages later he talks about parentheses having special
meaning in regex and what to do if they are in your text.

In this case, you need to escape the ( and )  characters with a
backslash. The \( and \) escape characters in the raw string passed to
re.compile() will match actual parenthesis characters.


These are regex escape characters. If you did not have the r in front
you would need to double escape them:

\\( and \\)

So by using the raw string you avoid the initial layer of
escaping by the python interpreter and only need to worry
about the regex parser - which is more than enough for anyone
to worry about!



Ok thanks.  The book did not mention 2 levels of escaping.  With what 
you told me in mind I reread that section and the book may have hinted 
at it but I would have never realized it without knowing what you just said.


Is the second example a special case?

phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My phone number is: (415) 555-4242.')
print(mo.group(1))
print()
print(mo.group(2))

I ask because it produces the same results with or without the ' r '.

Regards,  Jim

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


Re: [Tutor] Regex/Raw String confusion

2016-08-04 Thread Jim Byrnes

On 08/04/2016 03:27 AM, Alan Gauld via Tutor wrote:

On 04/08/16 02:54, Jim Byrnes wrote:


Is the second example a special case?

phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')

I ask because it produces the same results with or without the ' r '.


That's because in this specific case there are no conflicts between
the regex escape codes and the Python escape codes. In other
words Python does not treat '\(' or '\d' as special characters
so it doesn't change the string passed to the regex.
(It would be a different story if you had used, say, a
'\x' or '\n' or '\b' in the regex.)

In general you should proceed with caution and assume that
there might be a Python escape sequence lurking in the regex
and use raw just in case.



Ok, thanks again.  I understand what is going on now.

Regards,  Jim

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


[Tutor] tkinter/sqlite3?

2016-08-25 Thread Jim Byrnes

I am working with Python 3.4.3 on Ubuntu 14.04.

I am learning tkinter so I decided to rewrite a program I had written in 
pythoncard in tkinter. I found that a sqlite3 SELECT statement that 
works in pythoncard throws an error in tkinter and am wondering why?


# Fill the accounts listbox from the passwords database
def fill_accounts_lb(category):
  conn = sqlite3Connect()
  cur = conn.cursor()
  #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY 
Account COLLATE NOCASE''', category) (1)
  cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY 
Account COLLATE NOCASE'''

% category)
  result = [row[0] for row in cur.fetchall()]
  clearListbox()
  for account in result:
lb_accounts.insert(END, account)
  conn.close()

(1)
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
return self.func(*args)
  File "tk_pwds.py", line 22, in rbCall
fill_accounts_lb('WebSites')
  File "tk_pwds.py", line 56, in fill_accounts_lb
cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY 
Account COLLATE NOCASE''', category)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The 
current statement uses 1, and there are 8 supplied.


I cut the working statement from pythoncard and pasted it into tkinter 
and am curious why it works in the pythoncard version and not the 
tkinter version. I'm not sure where it is coming up with the 8 bindings 
it said are supplied?


Thanks,  Jim

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


Re: [Tutor] tkinter/sqlite3?

2016-08-26 Thread Jim Byrnes

On 08/26/2016 02:03 AM, Peter Otten wrote:

Jim Byrnes wrote:


I am working with Python 3.4.3 on Ubuntu 14.04.

I am learning tkinter so I decided to rewrite a program I had written in
pythoncard in tkinter. I found that a sqlite3 SELECT statement that
works in pythoncard throws an error in tkinter and am wondering why?

# Fill the accounts listbox from the passwords database
def fill_accounts_lb(category):
   conn = sqlite3Connect()
   cur = conn.cursor()
   #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE''', category) (1)
   cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY
Account COLLATE NOCASE'''
 % category)
   result = [row[0] for row in cur.fetchall()]
   clearListbox()
   for account in result:
 lb_accounts.insert(END, account)
   conn.close()

(1)
Exception in Tkinter callback
Traceback (most recent call last):
   File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
 return self.func(*args)
   File "tk_pwds.py", line 22, in rbCall
 fill_accounts_lb('WebSites')
   File "tk_pwds.py", line 56, in fill_accounts_lb
 cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE''', category)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
current statement uses 1, and there are 8 supplied.

I cut the working statement from pythoncard and pasted it into tkinter
and am curious why it works in the pythoncard version and not the
tkinter version. I'm not sure where it is coming up with the 8 bindings
it said are supplied?


category is probably a string with eight characters. As cursor.execute()
expects a sequence as its second argument it misinterprets this string as 8
distinct arguments. If the string were of length one your code would
(accidentally) work; this might have been the case in your other script.
The correct fix is to put even a single value into a list or tuple:


See my reply to Alan as to my guess why the pythoncard script worked.


cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE''', [category])

If you choose the tuple remember that a one-tuple requires a trailing comma:

cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE''', (category,))



Thanks for showing me the correct way to write that statement.

Regards,  Jim


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


Re: [Tutor] tkinter/sqlite3?

2016-08-26 Thread Jim Byrnes

On 08/26/2016 04:22 AM, Alan Gauld via Tutor wrote:

On 26/08/16 02:34, Jim Byrnes wrote:


Exception in Tkinter callback
Traceback (most recent call last):

...

   File "tk_pwds.py", line 56, in fill_accounts_lb
 cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE''', category)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
current statement uses 1, and there are 8 supplied.

I cut the working statement from pythoncard and pasted it into tkinter
and am curious why it works in the pythoncard version and not the
tkinter version.


Peter has given the solution, but just to be clear this has
nothing whatsoever to do with Tkinter v Pythoncard it is
entirely a Sqlite issue. (As is evidenced in the error message.)
Did you use an older version of Sqlite when you wrote the
Pythoncard code perhaps? You probably also used an older
version of Python?



The real mystery is how it worked in the Pythoncard version,
unless, as Peter suggests, you just got lucky and always
passed a single valued item?


The pythoncard version has been in use for a while so I used a desktop 
launcher to started it. It wasn't until I tried to run it from a 
terminal to see if there were any error messages, that I realized it was 
using python 2.7.6 and I was working with python 3.4.3.


I am guessing that the different version must have caused the problem.


Finally, the string formatting solution is never a good
idea for database queries since it is (a) open to injection
attack and (b) liable to generate an incorrect SQL query
which is hard to debug. (ie the query gets executed but
returns different data to what you expected/wanted)



The DB is local to my machine so I don't think I have had a problem in 
the past, but now that you and Peter have shown me the correct way, I 
will be doing it in the future.


Regards,  Jim


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


[Tutor] pip says no downloads for PyMedia

2016-09-10 Thread Jim Byrnes
I am working on an exercise that needs PyMedia. pypi seems to have the 
package but will not download it.


jfb@Jims-1404:~$ pip3 search PyMedia
pymediafire   - A python package for MediaFire API
ffmpymedia- Wrapper around the FFMPEG utility
PyMedia   - PyMedia is a module/library for manipulating 
mp3, avi, ogg, divx, mpeg, dvd media

files
pymedia2-pyrana   - Package for simple manipulation of 
multimedia files

pymediainfo   - A Python wrapper for the mediainfo library.
PyMediaRSS2Gen- A Python library for generating Media RSS 
2.0 feeds.

jfb@Jims-1404:~$ sudo pip3 install PyMedia
[sudo] password for jfb:
Downloading/unpacking PyMedia
  Could not find any downloads that satisfy the requirement PyMedia
Cleaning up...
No distributions at all found for PyMedia
Storing debug log for failure in /home/jfb/.pip/pip.log
jfb@Jims-1404:~$

From pip.log:


/usr/bin/pip3 run on Sat Sep 10 19:04:34 2016
Downloading/unpacking PyMedia
  Getting page https://pypi.python.org/simple/PyMedia/
  URLs to search for versions for PyMedia:
  * https://pypi.python.org/simple/PyMedia/
  Analyzing links from page https://pypi.python.org/simple/pymedia/
  Could not find any downloads that satisfy the requirement PyMedia
Cleaning up...
  Removing temporary dir /tmp/pip_build_root...
No distributions at all found for PyMedia
Exception information:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, 
in main

status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 
278, in run
requirement_set.prepare_files(finder, 
force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 1178, in 
prepare_files

url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 277, in 
find_requirement
raise DistributionNotFound('No distributions at all found for %s' % 
req)
pip.exceptions.DistributionNotFound: No distributions at all found for 
PyMedia


I am using python3 could that be the problem?  I looked but couldn't 
find any info on what version of python is needed.


Thanks,  Jim

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


Re: [Tutor] pip says no downloads for PyMedia

2016-09-12 Thread Jim Byrnes

On 09/12/2016 06:06 PM, boB Stepp wrote:

On Sep 10, 2016 7:20 PM, "Jim Byrnes"  wrote:



I am using python3 could that be the problem?  I looked but couldn't find

any info on what version of python is needed.



I went to pymedia.org.  The copyright at the bottom of the page is 2004.
The "latest" news entry is February 1, 2006.  So this looks to be from the
Python 2 only days.

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



Thanks. I looked but did not dig as deep as you did.

Regards,  Jim

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


Re: [Tutor] pip says no downloads for PyMedia

2016-09-13 Thread Jim Byrnes

On 09/12/2016 07:59 PM, Jim Byrnes wrote:

On 09/12/2016 06:06 PM, boB Stepp wrote:

On Sep 10, 2016 7:20 PM, "Jim Byrnes"  wrote:



I am using python3 could that be the problem?  I looked but couldn't
find

any info on what version of python is needed.



I went to pymedia.org.  The copyright at the bottom of the page is 2004.
The "latest" news entry is February 1, 2006.  So this looks to be from
the
Python 2 only days.

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



Thanks. I looked but did not dig as deep as you did.

Regards,  Jim




So it looks like I need to use Python 2. On my Ubuntu 14.04 system I 
have vers 2.7.6. I tried that with the below result.



jfb@Jims-1404:~$ pip install PyMedia
Collecting PyMedia
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: 
SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject 
Name Indication) extension to TLS is not available on this platform. 
This may cause the server to present an incorrect TLS certificate, which 
can cause validation failures. You can upgrade to a newer version of 
Python to solve this. For more information, see 
https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.

  SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: 
InsecurePlatformWarning: A true SSLContext object is not available. This 
prevents urllib3 from configuring SSL appropriately and may cause 
certain SSL connections to fail. You can upgrade to a newer version of 
Python to solve this. For more information, see 
https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.

  InsecurePlatformWarning
  Could not find a version that satisfies the requirement PyMedia (from 
versions: )

No matching distribution found for PyMedia
jfb@Jims-1404:~$

So I went to the urllib3 address listed above. It said to do

pip install urllib3[secure} to solve the problem.

So I still get the errors shown above.  What else do I need to do?

Thanks,  Jim

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


Re: [Tutor] pip says no downloads for PyMedia

2016-09-13 Thread Jim Byrnes

On 09/13/2016 04:01 PM, boB Stepp wrote:

On Tue, Sep 13, 2016 at 2:17 PM, Jim Byrnes  wrote:

On 09/12/2016 07:59 PM, Jim Byrnes wrote:


On 09/12/2016 06:06 PM, boB Stepp wrote:


On Sep 10, 2016 7:20 PM, "Jim Byrnes"  wrote:




I am using python3 could that be the problem?  I looked but couldn't
find


any info on what version of python is needed.




I went to pymedia.org.  The copyright at the bottom of the page is 2004.
The "latest" news entry is February 1, 2006.  So this looks to be from
the
Python 2 only days.


I personally know nothing about PyMedia, but if 2004 should be the
release date (The copyright at the bottom of their home page.), then
we are looking at a version of Python prior to Py 2.4.4 which was
released in October of 2006!  If this is correct, then you are
probably going to be unable to use PyMedia with any modern version of
Python.  Is there not something else more modern and compatible that
can meet your needs?




I am following some code in  a Tkinter book I am reading. The author 
says he is using Windows 7 and Python 2.7.3, so I should be good with 
python 2.7.6.


Right now I am more concerned about and trying to fix the urllib3 
warnings.  As a test just now I used python 2.7.3 version of pip  to 
install pyperclip. It gave me the same urllib3 warnings as when I tried 
to install PyMedia, BUT it did go ahead and finish the installation.


So maybe the two problems are not related but I would like to figure out 
and correct the urllib3 problem.


Regards,  Jim

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


[Tutor] Accessing Yahoo with Python?

2016-10-08 Thread Jim Byrnes
I realize that my question is not about the standard library. The only 
reason I am asking here is, if I remember correctly, a regular 
contributor, Danny Yoo, works at Yahoo. I am hoping he, or someone else 
here can help me understand what is happening.


I am writing a program using the yahoo_finance module. Over the past 
week I have been testing and refining it. At first the only errors I was 
seeing were mine.  Lately I have been a lot of these errors.


Traceback (most recent call last):
  File 
"/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 
120, in _request

_, results = response['query']['results'].popitem()
KeyError: 'query'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 75, 
in 

Stocks().run()
  File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 38, 
in run

self.get_stock_info()
  File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 53, 
in get_stock_info

yahoo = Share(stk)
  File 
"/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 
178, in __init__

self.refresh()
  File 
"/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 
142, in refresh

self.data_set = self._fetch()
  File 
"/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 
181, in _fetch

data = super(Share, self)._fetch()
  File 
"/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 
134, in _fetch

data = self._request(query)
  File 
"/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 
123, in _request

raise YQLQueryError(response['error']['description'])
yahoo_finance.YQLQueryError: Query failed with error: "'No definition 
found for Table yahoo.finance.quotes'".


It has gotten to the point where if I run the program 10 times, 9 of 
them will return the above error before I get the data I want. The part 
of my program that retrieves the data from Yahoo has not changed in 
quite a while.


Is it possible that I have exceeded a Yahoo limit on requests from one 
IP address?  Test data I am using gets the historical info on 3 stocks 
over a 3 day period.


Thanks,  Jim

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


[Tutor] comp.lang.python on gmane

2016-10-27 Thread Jim Byrnes

Is comp.lang.python available on gmane?

I've googled and found references to it being on gmane but I can't find 
it there. I'd like to use gmane because Comcast doesn't do usenet anymore.


Thanks,  Jim


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


Re: [Tutor] comp.lang.python on gmane

2016-10-27 Thread Jim Byrnes

On 10/27/2016 08:09 PM, Danny Yoo wrote:

On Thu, Oct 27, 2016 at 5:40 PM, Jim Byrnes  wrote:

Is comp.lang.python available on gmane?

I've googled and found references to it being on gmane but I can't find it
there. I'd like to use gmane because Comcast doesn't do usenet anymore.


Hi Jim,


I think Gmane is still recovering:

https://lars.ingebrigtsen.no/2016/07/28/the-end-of-gmane/


I read that but had forgotten about it because up until now gmane seemed 
to be working normally for me.



http://home.gmane.org/2016/08/29/next-steps-gmane/


It sounds like they're making good progress at recovery so far.  Until
then, you can still get at comp.lang.python via web interface with
Google Groups:

https://groups.google.com/forum/#!forum/comp.lang.python


Besides those, the archive is available at:

http://mail.python.org/pipermail/python-list/



I am trying to solve a problem with Selenium and googling hasn't helped. 
I wanted to ask a question on the list, but wanted to search back 5 or 6 
months first to see it it had already been solved. I have always found 
the web interfaces so cumbersome to use I don't know if I can do a 
search like that on them.


Thanks,  Jim

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


Re: [Tutor] comp.lang.python on gmane

2016-10-28 Thread Jim Byrnes

On 10/27/2016 09:54 PM, Random832 wrote:

On Thu, Oct 27, 2016, at 20:40, Jim Byrnes wrote:

Is comp.lang.python available on gmane?

I've googled and found references to it being on gmane but I can't find
it there. I'd like to use gmane because Comcast doesn't do usenet
anymore.


I don't know about the current viability of gmane in general, but it's
called "gmane.comp.python.general" on gmane.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



That worked.  Not sure how I over looked it the other times I was trying 
to subscribe.  Thanks much.


Regards,  Jim

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


[Tutor] Open a libreoffice calc file in Python

2016-12-21 Thread Jim Byrnes

Python 3.4 on Ubuntu

If I was going to open a libreoffice calc file from the terminal I would 
go: libreoffice --calc /home/path/to/myfile.ods.


How would I do this from Python?

Thanks,  Jim

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


Re: [Tutor] Open a libreoffice calc file in Python

2016-12-22 Thread Jim Byrnes

On 12/22/2016 03:54 AM, Alan Gauld via Tutor wrote:

On 22/12/16 03:37, Jim Byrnes wrote:

Python 3.4 on Ubuntu

If I was going to open a libreoffice calc file from the terminal I would
go: libreoffice --calc /home/path/to/myfile.ods.

How would I do this from Python?


Others have advised how to run the Libreoffice app from
within Python.

If you really want to open the actual spreadsheet file
in Python rather than Libreoffice then its a bit more tricky.
If that is what you really meant get back to us and
we can start on the options available...




First thanks to everyone that responded pointing me in the right direction.

Alan,

I want to open Libreoffice with a particular file loaded.

I started out to write a libreoffice macro in python to go to a website, 
get some info, copy it to the clipboard and then paste it in libreoffice 
calc.


I started out by writing a script using Selenium that successfully did 
what I wanted. Once I had it working the plan was to put it in a macro. 
When I did that I got a large error message where both libreoffice and 
selenium complained.  I seemed to say that the first element of the 
webpage I tried to manipulate was in a state that it could not be 
interacted with, even though outside of libreoffice the script ran fine.


This got me thinking that maybe I should attack the problem from the 
other end, ie run the script and have it load libreoffice at the end. 
Hence my question.


for completeness here is the error msg I received:

com.sun.star.uno.RuntimeExceptionError during invoking function login in 
module 
file:///home/jfb/.config/libreoffice/4/user/Scripts/python/funds/funds.py 
(: 
Message: invalid element state: Element is not currently interactable 
and may not be manipulated

  (Session info: chrome=55.0.2883.87)
  (Driver info: chromedriver=2.25.426924 
(649f9b868f6783ec9de71c123212b908bf3b232e),platform=Linux 
4.4.0-57-generic x86_64)



/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/errorhandler.py:192 
in function check_response() [raise exception_class(message, screen, 
stacktrace)]


/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webdriver.py:236 
in function execute() [self.error_handler.check_response(response)]


/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webelement.py:494 
in function _execute() [return self._parent.execute(command, params)]


/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webelement.py:92 
in function clear() [self._execute(Command.CLEAR_ELEMENT)]
  /home/jfb/.config/libreoffice/4/user/Scripts/python/funds/funds.py:29 
in function login() [username.clear()]
  /usr/lib/libreoffice/program/pythonscript.py:869 in function invoke() 
[ret = self.func( *args )]

)


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


[Tutor] How to interact with the result of subprocess.call()

2016-12-24 Thread Jim Byrnes

subprocess.call(['libreoffice', '/home/jfb/test.ods'])
k.tap_key(k.enter_key)
k.tap_key(k.enter_key)

If I run the above code, libreoffice opens the test.ods spreadsheet then 
just sits there. When I close libreoffice the two enter_keys are 
executed in the terminal that originated the script.


How can I continue to send keystrokes to libreoffice from the script 
once it has been opened by subprocess.call()?


Thanks,  Jim


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


Re: [Tutor] How to interact with the result of subprocess.call()

2016-12-24 Thread Jim Byrnes

On 12/24/2016 05:10 PM, Danny Yoo wrote:

On Sat, Dec 24, 2016 at 2:40 PM, Jim Byrnes  wrote:

subprocess.call(['libreoffice', '/home/jfb/test.ods'])
k.tap_key(k.enter_key)
k.tap_key(k.enter_key)

If I run the above code, libreoffice opens the test.ods spreadsheet then
just sits there. When I close libreoffice the two enter_keys are executed in
the terminal that originated the script.

How can I continue to send keystrokes to libreoffice from the script once it
has been opened by subprocess.call()?



Hi Jim,

You can not use subprocess to automate a GUI application.  This
approach will not work because libreoffice isn't written to pay
attention to the stdin file handle of its process.

That's one of the traditional reasons why GUI applications are
unpopular for programmers: in general, GUI-based applications are not
trivial to automate.

You do have a few options:


* See if the application provides a programming interface (an "API").

In the case of libreoffice, there does appear to be such an API:

http://api.libreoffice.org/examples/examples.html#python_examples

Accessing it is very much outside the domain of Python-tutor: you will
likely need to talk with with the libreoffice folks.  But if you can
do this, it's probably nicer since the interface will use the terms of
libreoffice, rather than in terms of keystrokes, timer delays, and
mouse movement.


* More general automation of GUI applications is possible.  Here is a
link to pyautogui, a third-party library that handles GUI automation:

 http://pyautogui.readthedocs.io/en/latest/

Again, you'll probably need to talk with folks who have experience
with pyautogui; I don't think many of us on Tutor are very familiar
with it.


Good luck!


Danny,


I am not trying to automate libreoffice using subprocess. In an earlier 
message I was told that subprocess was the way to open libreoffice from 
a python script. It does do that but now it seems to be blocking my 
attempts to send keystrokes to libreoffice.


Up until this point in the script I have used a combination of Selenium 
and pykeyboard to log on to a web site and put some info in the 
clipboard. Now I need to send keystrokes to libreoffice to paste from 
the clipboard into the spreadsheet.


I have used pyuno api to automate libreoffice in the past, but it was a 
time consuming and confusing process.  I was trying this approach 
because it looked like I could avoid the uno complexity.  I think it 
would work if I could figure out how to send keystrokes to libreoffice 
after it is opened using subprocess or some alternative that would work 
better.


Regards,  Jim

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


Re: [Tutor] How to interact with the result of subprocess.call()

2016-12-25 Thread Jim Byrnes

On 12/24/2016 07:43 PM, Alan Gauld via Tutor wrote:

On 25/12/16 01:21, Jim Byrnes wrote:


I am not trying to automate libreoffice using subprocess.


No, but you are trying to automate LO from within Python
by sending it keystrokes and that's not easy. That's why I
previously asked whether you really wanted to open the LO
file directly and manipulate it from within Python
- that's (slightly) easier than manipulating LO directly
and much easier than manipulating LO from Python via
keystrokes.




message I was told that subprocess was the way to open libreoffice from
a python script.


Which is true if you want to bring up a LO session for
your user to manipulate. But it's not the way to drive
LO automatically. (One option is to start LO from Python
then use macros within LO to do the automation - there may
even be a command line switch to trigger a macro - I can't
remember off hand)




To drive LO via keystrokes your program needs to inject
key/mouse events into the LO event queue. That's not easy
and not very reliable either(*). There are some libraries that
can help but it should be the path of last resort.

(*)LO remembers its last screen setting and opens with them,
if those screen settings are different than the ones you
programmed for then navigation will be different and so on.
That's easy to deal with for a human who can see the screen
but sending keystrokes programmatically you are effectively
trying to drive the system blindfolded!


I don't think I need to "know where stuff is" to manipulate LO. At first 
I was just using Selenium to get the data from the web page, but the 
focus would end up in the url bar. I forget the exact details but I 
could not get Selenium to manipulate Chrome anymore at that point. I did 
some searching and found pykeyboard. Using it I was able to send Ctrl-A 
and then Ctrl-C to copy the page to the clipboard.


My thinking is if I can get LO to accept keystrokes I can send 
Shift-Ctrl-V to paste special and the two enter keys to answer dialog 
questions and paste the info into a sheet.  I would use the fact that LO 
reopens to where it was closed to my advantage by not having to use a 
macro to navigate to the proper page.



Up until this point in the script I have used a combination of Selenium
and pykeyboard to log on to a web site and put some info in the
clipboard. Now I need to send keystrokes to libreoffice to paste from
the clipboard into the spreadsheet.


Or you could just open the spreadsheet file directly
and insert the data directly into it from Python. I think
there is a library for that - there are several for doing
it in Excel (so if your spreadsheet is in Excel format it
is fairly easy). Or, if you can use CSV format, its just a
standard library module.


I'll look into these alternatives if I can't figure out how to get 
keystrokes into LO using my present approach.



Alternatively you can use the LO API to directly inject
the data into the spreadsheet objects (like using COM
in Microsoft land).


I have used pyuno api to automate libreoffice in the past, but it was a
time consuming and confusing process.


Trust me it is nowhere near as confusing and frustrating
as trying to drive LO (Or any other GUI) via keystrokes!


Based on my success with pykeyboard and Chrome I thought it would be 
easier than diving back into Uno.  However, using subprocess seems to be 
blocking me from sending any keystrokes to LO. I don't understand 
subprocess well enough to know if it is actually blocking my keystrokes. 
I concluded that based on the fact that when I closed LO the two 
enter_keys at the end of the script were executed in the terminal.


Is there a way to terminate subprocess and still keep LO open so 
pykeyboard can send it keystrokes from the script?



I was trying this approach
because it looked like I could avoid the uno complexity.


If there isn't a direct file manipulation library for LO
spreadsheets then UNO is probably the easiest option.




Regards,  Jim


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


[Tutor] Which pip for Ubuntu 12.04

2013-02-08 Thread Jim Byrnes

How important is it to have the latest pip installed?

Initially I want to use it to install the latest pymongo driver for 
mongoDB.  The pip version in the Ubuntu 12.04 repositories is 1.0.1. I 
see on http://www.pip-installer.org/en/latest/ the version is 1.2.1.


It certainly would be easier to install from the repositories but will 
that version work to install the latest python packages?


Thanks,  Jim

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


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread Jim Byrnes

On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote:

- Original Message -


From: Jim Byrnes  To: tutor@python.org Cc:
Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip
for Ubuntu 12.04

How important is it to have the latest pip installed?

Initially I want to use it to install the latest pymongo driver for
mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1.
I see on http://www.pip-installer.org/en/latest/ the version is
1.2.1.

It certainly would be easier to install from the repositories but
will that version work to install the latest python packages?

Thanks,  Jim


You could just try it? And downloading it and then doing sudo tar
-xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is
it?


I usually install from the repositories or maybe a ppa so I don't 
believe I have ever done an install from a tar.  If necessary I will 
familiarize myself with the command you gave (yes I saw your followup 
changing -xvr to -xvf) and install that way.


However, I still wonder if using the outdated pip from the repository 
will allow me to install the latest python packages?  Will trying to use 
an outdated pip cause me problems?



But you're right, I also nnoticed that the Canonical repositories are
a little outdated sometimes. Would be nice if it's possible to add
pypi.org, so updating would be easier.

Albert-Jan



Thanks,  Jim

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


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-11 Thread Jim Byrnes

On 02/10/2013 01:10 PM, Joel Goldstick wrote:

On Sun, Feb 10, 2013 at 1:53 PM, Timo  wrote:


Op 10-02-13 17:01, Jim Byrnes schreef:

  On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote:



- Original Message -

  From: Jim Byrnes  To: tutor@python.org Cc:

Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip
for Ubuntu 12.04

How important is it to have the latest pip installed?

Initially I want to use it to install the latest pymongo driver for
mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1.
I see on 
http://www.pip-installer.org/**en/latest/<http://www.pip-installer.org/en/latest/>the
 version is
1.2.1.

It certainly would be easier to install from the repositories but
will that version work to install the latest python packages?

Thanks,  Jim



You could just try it? And downloading it and then doing sudo tar
-xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is
it?



I usually install from the repositories or maybe a ppa so I don't believe
I have ever done an install from a tar.  If necessary I will familiarize
myself with the command you gave (yes I saw your followup changing -xvr to
-xvf) and install that way.

However, I still wonder if using the outdated pip from the repository
will allow me to install the latest python packages? Will trying to use an
outdated pip cause me problems?


I doubt it will. Have a look at the pip changelog to see what has been
changed.

Timo





  But you're right, I also nnoticed that the Canonical repositories are

a little outdated sometimes. Would be nice if it's possible to add
pypi.org, so updating would be easier.

Albert-Jan




Thanks,  Jim

__**_
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/**mailman/listinfo/tutor<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<http://mail.python.org/mailman/listinfo/tutor>





You can upgrade pip with pip i believe:

jcg@jcg-desktop:~/code/python$ pip install pip
Requirement already satisfied (use --upgrade to upgrade): pip in
/usr/lib/pymodules/python2.7
Cleaning up...
jcg@jcg-desktop:~/code/python$


jcg@jcg-desktop:~/code/python$ pip install --upgrade pip


Be sure to sudo before if you don't have permissions.




I tried this on my laptop with the following results:

jfb@jfb-tp:~$ pip --version
pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7)
jfb@jfb-tp:~$ pip install pip
Requirement already satisfied (use --upgrade to upgrade): pip in 
/usr/lib/python2.7/dist-packages

Cleaning up...

jfb@jfb-tp:~$ sudo pip install --upgrade pip
[sudo] password for jfb:
Downloading/unpacking pip
  Running setup.py egg_info for package pip

warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under 
directory 'docs/_build'
no previously-included directories found matching 
'docs/_build/_sources'

Installing collected packages: pip
  Found existing installation: pip 1.0
Uninstalling pip:
  Successfully uninstalled pip
  Running setup.py install for pip

warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under 
directory 'docs/_build'
no previously-included directories found matching 
'docs/_build/_sources'

Installing pip script to /usr/local/bin
Installing pip-2.7 script to /usr/local/bin
Successfully installed pip
Cleaning up...
jfb@jfb-tp:~$ pip --version
bash: /usr/bin/pip: No such file or directory
jfb@jfb-tp:~$

I not sure what the significance of the missing *.txt and *.html files 
is but it looks like I have a path problem. I would appreciate any 
pointers from anyone who has already solved this.


Thanks,  Jim

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


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-11 Thread Jim Byrnes

On 02/11/2013 09:31 AM, Jim Byrnes wrote:

On 02/10/2013 01:10 PM, Joel Goldstick wrote:

On Sun, Feb 10, 2013 at 1:53 PM, Timo  wrote:


Op 10-02-13 17:01, Jim Byrnes schreef:

  On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote:



- Original Message -

  From: Jim Byrnes  To: tutor@python.org Cc:

Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip
for Ubuntu 12.04

How important is it to have the latest pip installed?

Initially I want to use it to install the latest pymongo driver for
mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1.
I see on
http://www.pip-installer.org/**en/latest/<http://www.pip-installer.org/en/latest/>the
version is
1.2.1.

It certainly would be easier to install from the repositories but
will that version work to install the latest python packages?

Thanks,  Jim



You could just try it? And downloading it and then doing sudo tar
-xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is
it?



I usually install from the repositories or maybe a ppa so I don't
believe
I have ever done an install from a tar.  If necessary I will
familiarize
myself with the command you gave (yes I saw your followup changing
-xvr to
-xvf) and install that way.

However, I still wonder if using the outdated pip from the repository
will allow me to install the latest python packages? Will trying to
use an
outdated pip cause me problems?


I doubt it will. Have a look at the pip changelog to see what has been
changed.

Timo





  But you're right, I also nnoticed that the Canonical repositories are

a little outdated sometimes. Would be nice if it's possible to add
pypi.org, so updating would be easier.

Albert-Jan




Thanks,  Jim

__**_
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/**mailman/listinfo/tutor<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<http://mail.python.org/mailman/listinfo/tutor>






You can upgrade pip with pip i believe:

jcg@jcg-desktop:~/code/python$ pip install pip
Requirement already satisfied (use --upgrade to upgrade): pip in
/usr/lib/pymodules/python2.7
Cleaning up...
jcg@jcg-desktop:~/code/python$


jcg@jcg-desktop:~/code/python$ pip install --upgrade pip


Be sure to sudo before if you don't have permissions.




I tried this on my laptop with the following results:

jfb@jfb-tp:~$ pip --version
pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7)
jfb@jfb-tp:~$ pip install pip
Requirement already satisfied (use --upgrade to upgrade): pip in
/usr/lib/python2.7/dist-packages
Cleaning up...

jfb@jfb-tp:~$ sudo pip install --upgrade pip
[sudo] password for jfb:
Downloading/unpacking pip
   Running setup.py egg_info for package pip

 warning: no files found matching '*.html' under directory 'docs'
 warning: no previously-included files matching '*.txt' found under
directory 'docs/_build'
 no previously-included directories found matching
'docs/_build/_sources'
Installing collected packages: pip
   Found existing installation: pip 1.0
 Uninstalling pip:
   Successfully uninstalled pip
   Running setup.py install for pip

 warning: no files found matching '*.html' under directory 'docs'
 warning: no previously-included files matching '*.txt' found under
directory 'docs/_build'
 no previously-included directories found matching
'docs/_build/_sources'
 Installing pip script to /usr/local/bin
 Installing pip-2.7 script to /usr/local/bin
Successfully installed pip
Cleaning up...
jfb@jfb-tp:~$ pip --version
bash: /usr/bin/pip: No such file or directory
jfb@jfb-tp:~$

I not sure what the significance of the missing *.txt and *.html files
is but it looks like I have a path problem. I would appreciate any
pointers from anyone who has already solved this.

Thanks,  Jim



Apparently I was wrong about the path problem.  I closed the terminal I 
used for the update and opened another session and now I get:


$pip --version
pip 1.2.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

I guess the real test will come when I attempt to use it to install a 
package.


Regards,  Jim


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


[Tutor] Need help with sqlite3 in python

2013-02-17 Thread Jim Byrnes
I am writing a small database CRUD app using python 2.7, pythoncard, 
sqlite3 on Ubuntu 12.04.  So far I can retrieve data fine but I cannot 
do inserts. In my first attempt I used parameter substitution. When that 
did not work I thought I didn't understand it and decided to try a 
simple insert.  I modeled the code after the example on the python 
sqlite3 page.  Here is the code that does not work.  Note: Don't mind 
the title, the delete button had no code yet and seemed to be the 
easiest place to run this simple test.


def on_buttonDelete_mouseClick(self, event):
conn = sqlite3.connect("/home/jfb/MyProgs/Pwds/passwords")
cur = conn.cursor()
	cur.execute("INSERT INTO pwds VALUES ('WebSites', 'xMe', 'me', 'you', 
'here', 'there')")

conn.commit()
conn.close()
print 'done'


When this code is run, done prints in the terminal, there is no error 
message, the row is not inserted and the file modified time is not 
changed.  The permissions set on the file are -rw -rw -rw. Sqlite3 is 
imported and if I mangle the path or execute line it complains. If I run 
the same sql in Sqliteman the row is inserted as expected.


Appreciate it if someone could give me an idea of what I am doing wrong.

Thanks,  Jim

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


Re: [Tutor] Need help with sqlite3 in python

2013-02-17 Thread Jim Byrnes

On 02/17/2013 12:31 PM, Alan Gauld wrote:

On 17/02/13 16:50, Jim Byrnes wrote:


 cur.execute("INSERT INTO pwds VALUES ('WebSites', 'xMe', 'me',
'you', 'here', 'there')")

When this code is run, done prints in the terminal, there is no error


Can you do selects properly?
Can you extract data put in manually? That would prove the connection
from Python to SQLite was working...


Thank you Alan.  Your question led me to the solution. So many times it 
is dumb little mistakes that trip you up. I had moved a copy of the db 
into the directory I was developing in but was inserting in  the working 
copy.  The insertions were there I was just looking at the wrong db with 
Sqliteman.



Usually when I get errors like that its because the values do not match
the number of fields/types in the table definition, but if the manual
sql works with the same query that shouldn't be the issue so I'd suspect
the connection...



Regards,  Jim

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


[Tutor] sqlite3 does it support limit in a delete clause?

2013-02-21 Thread Jim Byrnes

ubuntu 12.04 python 2.7

Does sqlite3 in this version of python support a delete with a limit?

>>> cur.execute("delete from pwds where Account='xMe' limit 1")
Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near "limit": syntax error
>>>
>>> cur.execute("delete from pwds where Account='xMe' limit=1")
Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near "limit": syntax error
>>>

It seems not, but it may be me messing up the syntax so I thought I 
would check.


Thanks,  Jim

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


Re: [Tutor] sqlite3 does it support limit in a delete clause?

2013-02-22 Thread Jim Byrnes

On 02/21/2013 11:10 PM, eryksun wrote:

On Thu, Feb 21, 2013 at 8:47 PM, Jim Byrnes  wrote:



cur.execute("delete from pwds where Account='xMe' limit 1")


If you need a alternate way to limit the delete, try the following,
for which the limit is on a select query:

 cur.execute('''
   delete from pwds where rowid in (
 select rowid from pwds where Account='xMe' limit 1)
 ''')


Thanks for all the info.  I ran your tests and my version of sqlite3 is 
indeed not compiled to use LIMIT.  After I sent the email I was 
wondering about using rowid.  Thanks for confirming it with an example.


Regards,  Jim

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


[Tutor] How to break long lines?

2013-02-22 Thread Jim Byrnes
I am cleaning up my code and have a number of sqlite3 execute statements 
that extend far past 80 characters.


From my reading implicit line joining with (), [] or {} seems to be the 
preferred method, but


cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
COLLATE NOCASE', cat)

gives this error:

jfb@jims1204:~/MyProgs/passwords$ python passwords.py
  File "passwords.py", line 50
cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
  ^
SyntaxError: EOL while scanning string literal

Using a \ seems to be out of favor but it works in this case.

cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account\
COLLATE NOCASE', cat)
# no error.

What am I not understanding about implicit line joining?

Thanks,  Jim

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


Re: [Tutor] How to break long lines?

2013-02-22 Thread Jim Byrnes

On 02/22/2013 03:54 PM, Prasad, Ramit wrote:

Jim Byrnes wrote:

I am cleaning up my code and have a number of sqlite3 execute statements
that extend far past 80 characters.

  From my reading implicit line joining with (), [] or {} seems to be the
preferred method, but

cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
COLLATE NOCASE', cat)

gives this error:

jfb@jims1204:~/MyProgs/passwords$ python passwords.py
File "passwords.py", line 50
  cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
^
SyntaxError: EOL while scanning string literal

Using a \ seems to be out of favor but it works in this case.

cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account\
COLLATE NOCASE', cat)
# no error.

What am I not understanding about implicit line joining?


The problem is the line break. Single delimited (quote or double quote) strings
can only stay on one line (unless using the \ hack). You can easily solve this
problem in your case by using triple delimited strings.

cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account
COLLATE NOCASE''', cat)


~Ramit



So it was the quotes that tripped me up.  The triple quoted ones worked 
great.


Thanks,  Jim


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


Re: [Tutor] How to break long lines?

2013-02-22 Thread Jim Byrnes

On 02/22/2013 03:59 PM, Jerry Hill wrote:

On Fri, Feb 22, 2013 at 4:26 PM, Jim Byrnes  wrote:

I am cleaning up my code and have a number of sqlite3 execute statements
that extend far past 80 characters.

 From my reading implicit line joining with (), [] or {} seems to be the
preferred method, but

cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
 COLLATE NOCASE', cat)

gives this error:

jfb@jims1204:~/MyProgs/passwords$ python passwords.py
   File "passwords.py", line 50
 cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
   ^
SyntaxError: EOL while scanning string literal


Single quoted strings aren't allowed to have line breaks in them.  If
you have two string literals separated only by whitespace, though,
they get joined together, so you could do this:

cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account'
 'COLLATE NOCASE', cat)

You can also use triple quoted strings instead, which is my
preference.  Triple quoted strings are allowed to have line breaks,
and the whitespace doesn't matter in your SQL query.  So I'd do
something like this:

cur.execute ('''select account
 from pwds
 where category = ?
 order by account
 collate nocase''', cat)

You can break the query up over however many lines it needs to be
readable, of course.



Thanks, the triple quoted method worked great.  I guess I always think 
of them in terms of docstrings or comments not in this way.


Regards,  Jim

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


Re: [Tutor] How to break long lines?

2013-02-22 Thread Jim Byrnes

On 02/22/2013 05:46 PM, Steven D'Aprano wrote:

On 23/02/13 08:26, Jim Byrnes wrote:


I am cleaning up my code and have a number of sqlite3 execute
statements that extend far past 80 characters.

From my reading implicit line joining with (), [] or {} seems to be
the preferred method, but

cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE', cat)

gives this error:

[...]

SyntaxError: EOL while scanning string literal



Single quote strings are limited to a single line, regardless of any
brackets (round, square or curly) around them. In this case, the
round brackets simply allow the arguments to cur.execute() to extend
over multiple lines, but each argument still has to obey the syntax
rules.

You can't expect this to work:

func(12345 67890)  # ten digit number

just because of the parentheses. Neither do single-quote strings
suddenly gain the power to extend past the end of line.


But what you can do is use a line continuation \ as you have seen. Or
you can use a little-known feature of Python, implicit string
concatenation. The Python compiler will automatically concatenate
strings at compile-time:

s = "spam " 'ham ' 'eggs'

is a more-verbose way of writing:

s = "spam ham eggs"

Now obviously this example here is useless, but when combined with
parentheses, you get a powerful way of writing long strings:


cur.execute('SELECT Account FROM pwds' ' WHERE Category=?' ' ORDER BY
Account' ' COLLATE NOCASE', cat)


which I think is really nice to read. The best part is, because
these are string literals, the language promises to concatenate them
at compile-time, not runtime.

If implicit concatenation is too magical for you, you can use
explicit concatenation:

cur.execute('SELECT Account FROM pwds' + ' WHERE Category=?' + '
ORDER BY Account' + ' COLLATE NOCASE', cat)

At worst, the string concatenation + operator will apply at runtime,
which for a short string like this is not a big deal. But in
practice, I would expect Python's "keyhole optimizer" to see that it
is only string literals being concatenated, and perform
constant-folding at compile-time.

(Note: constant-folding is not a promise of the language. Not all
Python versions or implementations will do this.)


A fourth option is to use triple-quoted strings:

cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY
Account COLLATE NOCASE''', cat)


but this relies on your SQL database being happy to receive commands
with embedded newlines, which it may not be.



Thanks for giving me so many options to use in the future.  When reading 
I completely blew by the single quote on a single line part.  The db is 
sqlite3 and it seems happy with ''' strings.


Thanks,  Jim



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


Re: [Tutor] confusing installation

2013-03-01 Thread Jim Byrnes

On 02/28/2013 08:33 PM, Lolo Lolo wrote:

Hi all. Im working through a database tutorial in a book called Core
Python Applications. On page 290 it asks of me to install something
though its not clear what it is. I think it has to do with
SQLAlchemy. It says if you use Python 3 you'll need to get distribute
first. You'll need a web browser (or the curl if you have it).


I have the book but I am only on chapter one and I don't use Windows so 
my explanation may not be 100% accurate.


Since you use python 3 you will need to download the file: 
distribute_setup.py.  To do so you will need a web browser or the 
command line tool curl.  I use Firefox and when I click on the url you 
give below it immediately offers to download the required file.



Mind you i havent a clue what it is on about.. then it goes on:

And to download the installation file (available at
http://python-distribute.org/distribute_setup.py), and then get
SQLAlchemy with easy install. Here is what this entire process might
look like on a Windows-based PC... then it proceeds to  write a whole
bunch of god know what. It looks similar to when you install
something on linux.. Im a windows only user btw.


He is showing you what to expect.  Where ever you see a line starting 
with C:\ that is what he typed into the command line session, and the 
lines that follow is the program you are installing informing you what 
it is doing. (Until you get to the next C:\ or the end)




That link i went there to download the file but if you look at that
site i dont know what on earth im supposed to do to install/retrieve
that file. I do not know what easy install is.What do they mean i
need a web browser? doesnt every computer have a web-browser?? what
is curl?? I can not proceed with this tutorial if i recieve no
help... Please can anyone assist me on what i have to do to use the
tools they are presenting.

i use Python 3 and Windows




Regards,  Jim

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


Re: [Tutor] confusing installation

2013-03-01 Thread Jim Byrnes

On 03/01/2013 05:19 PM, Lolo Lolo wrote:

He is showing you what to expect.  Where ever you see a line
starting with C:\ that is what he typed into the command line
session, and > the lines that follow is the program you are
installing informing you what it is doing. (Until you get to the
next C:\ or the end)


i managed to install that file but in the book it shows the file
going into http://www.alchemy.org/ and installing it into site
packages, my install unfortunately didnt do this very last step that
involved adding sqlalchemy to easy-install.pth. not sure how to fix
it

thanks to every that has helped



I'm sorry I can't help you with with this as I run linux.  Even if I 
jumped ahead and did that chapter I'm sure being on linux my results 
would be entirely different than you would see on Windows.


Regards,  Jim

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


Re: [Tutor] mysqlite

2013-03-06 Thread Jim Byrnes

On 03/06/2013 03:47 PM, Joel Goldstick wrote:

On Wed, Mar 6, 2013 at 1:50 PM, Lolo Lolo  wrote:


im working through alan's sql tutorial. i have a few questions from there
but 1st i wanted to try out an example in Core python's sql example.


import sqlite3
cxn = sqlite3.connect('sqlite_test/test')
cur = cxn.cursor()


after this i created a table called users and inserted some data. then i
did:


cur.execute('SELECT * from users')
for user in cur.fetchall():

 print(user)

i got the results of all data i gave the table. then did


cur.close()
cxn.commit()
cxn.close()


I've only used sqlite and Python together a couple of times but I don't 
remember seeing that sequence of commands used.  Don't use cur.close() 
and see if that helps.


Regards, Jim


i then closed this interactive IDLE session. i reopened another session
and simply did


import sqlite3
cxn = sqlite3.connect('sqlite_test/test')
cur = cxn.cursor()
for user in cur.fetchall():

 print(user)




but this time no data was printed back to me, even though the database
file 'test' already existed from the previous session. Why did this happen,
cant i just connect and my data is still intact? or do i have to always re
enter data from the previously saved session?



Are you sure you are in same directory each time?



My questions about http://www.alan-g.me.uk/tutor/tutdbms.htm is to open a
database it uses the command line directly and doesnt creat cursor() or
connect() objects e.g.

E:\PROJECTS\SQL> sqlite3 employee.db
sqlite> create table Employee
...> (EmpID,Name,HireDate,Grade,ManagerID);
sqlite> insert into Employee (EmpID, Name, HireDate, Grade, ManagerID)
...> values ('1020304','John Brown','20030623','Foreman','1020311');

i tried this in my command line but got :
python.exe: can't open file 'sqlite': [Errno 2] No
  such file or directory

i tried creating the a folder called test and doing:  test employee.db
but no test.db was created.

my main questions are it possible to use the command line without cursor()
and connect() in python 3 or is it only for python 2. is it better from the
command line or in a .py file. And also my previous question i had about
having to re enter previously stored data
___
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




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


[Tutor] Scripting Calligra sheets with Python

2013-03-18 Thread Jim Byrnes
I am trying to script Calligra Sheets (formerly KSpread) with python.  I 
have gotten some of the included example scripts to run so I know python 
scripting is running.


I found the following snippet on their website:

import KSpread
sheet = KSpread.view().sheet()
# swap text of B5 and C6
t1 = sheet.text("B5")
t2 = sheet.text(6,3)
sheet.setText("B5", t2)
sheet.setText(6, 3, t1)
# swap value of D7 and E8
v1 = sheet.value("D7")
v2 = sheet.value(8,5)
sheet.setValue("D7", v2)
sheet.setValue(8, 5, v1)

Error: 'str' object has no attribute 'text'
 File 
"file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line 
4, in 



This error message appeared in a dialog box.

I've taught myself some Python but I don't understand what is happening 
here.  Shouldn't t1 be a sheet object?  What would cause it to be a str 
instead?


Thanks,  Jim



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


Re: [Tutor] Scripting Calligra sheets with Python

2013-03-18 Thread Jim Byrnes

On 03/18/2013 07:54 PM, Dave Angel wrote:

On 03/18/2013 12:18 PM, Jim Byrnes wrote:

I am trying to script Calligra Sheets (formerly KSpread) with python.  I
have gotten some of the included example scripts to run so I know python
scripting is running.

I found the following snippet on their website:

import KSpread
sheet = KSpread.view().sheet()
# swap text of B5 and C6
t1 = sheet.text("B5")
t2 = sheet.text(6,3)
sheet.setText("B5", t2)
sheet.setText(6, 3, t1)
# swap value of D7 and E8
v1 = sheet.value("D7")
v2 = sheet.value(8,5)
sheet.setValue("D7", v2)
sheet.setValue(8, 5, v1)

Error: 'str' object has no attribute 'text'
  File
"file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line
4, in 


This error message appeared in a dialog box.

I've taught myself some Python but I don't understand what is happening
here.  Shouldn't t1 be a sheet object?  What would cause it to be a str
instead?



Since somebody has censored the rest of the error traceback, we can't
even tell what line is giving the error.  Assuming you know it's
t1 = sheet.text("85")


I think line wrapping obscured that it is line 4 t1 = sheet.text("B5").


then it has nothing to do with the type of t1, but with the type of
sheet.  If that's the case, then print out type(sheet) and see what it
actually is.  Then consult the documentation for the
KSpread.view().sheet() function and see what it's documented to return.



The docs say: Returns the KSpread::ViewAdaptor object in which the 
document is displayed.


I would like to follow your advice and print out type(sheet) but right 
now I don't know how.  This is all running inside Calligra sheets and so 
far the only thing I have gotten out if it is the error message.


Thanks for the suggestion, now I can be a little more focused trying to 
figure this out, which is why I asked here first.  I have since taken 
Hugo's advise and posted to the Calligra list also.


Regards,  Jim


Thanks,  Jim








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


Re: [Tutor] Scripting Calligra sheets with Python

2013-03-19 Thread Jim Byrnes

On 03/18/2013 11:25 PM, Dave Angel wrote:

On 03/18/2013 09:56 PM, Jim Byrnes wrote:

On 03/18/2013 07:54 PM, Dave Angel wrote:

On 03/18/2013 12:18 PM, Jim Byrnes wrote:

I am trying to script Calligra Sheets (formerly KSpread) with
python.  I
have gotten some of the included example scripts to run so I know
python
scripting is running.

I found the following snippet on their website:

import KSpread
sheet = KSpread.view().sheet()
# swap text of B5 and C6
t1 = sheet.text("B5")
t2 = sheet.text(6,3)
sheet.setText("B5", t2)
sheet.setText(6, 3, t1)
# swap value of D7 and E8
v1 = sheet.value("D7")
v2 = sheet.value(8,5)
sheet.setValue("D7", v2)
sheet.setValue(8, 5, v1)

Error: 'str' object has no attribute 'text'
  File
"file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line
4, in 


This error message appeared in a dialog box.

I've taught myself some Python but I don't understand what is happening
here.  Shouldn't t1 be a sheet object?  What would cause it to be a str
instead?



Since somebody has censored the rest of the error traceback, we can't
even tell what line is giving the error.  Assuming you know it's
t1 = sheet.text("85")


I think line wrapping obscured that it is line 4 t1 = sheet.text("B5").


I saw the line 4, but didn't see anyplace where it showed me line 4.  So
i had to guess.  And for all I knew, the error isn't happening on that
line, but on some line called indirectly by that one.  The full stack
trace would be reassuring.  But apparently your Calligra environment is
censoring it.




then it has nothing to do with the type of t1, but with the type of
sheet.  If that's the case, then print out type(sheet) and see what it
actually is.  Then consult the documentation for the
KSpread.view().sheet() function and see what it's documented to return.



The docs say: Returns the KSpread::ViewAdaptor object in which the
document is displayed.

I would like to follow your advice and print out type(sheet) but right
now I don't know how.  This is all running inside Calligra sheets and so
far the only thing I have gotten out if it is the error message.


Are you permitted to edit this myswap.py file?  If so, add a line that
prints the useful information immediately before the line which causes
the exception.  And if print is also swallowed by your helpful
environment, then write to a file.


Yes I can and it does swallow it, so I redirected to a file and it says 
.  Same as the error message.  So now I need to figure out 
why it's not returning the object expected.


I can run the sample scripts that were installed but not something I 
originate.  I guess I must be missing something procedural that is 
keeping them from running properly.


Thanks for you help.

Regards,  Jim




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


Re: [Tutor] Scripting Calligra sheets with Python

2013-03-20 Thread Jim Byrnes

On 03/19/2013 09:16 PM, Jim Byrnes wrote:

On 03/18/2013 11:25 PM, Dave Angel wrote:

On 03/18/2013 09:56 PM, Jim Byrnes wrote:

On 03/18/2013 07:54 PM, Dave Angel wrote:

On 03/18/2013 12:18 PM, Jim Byrnes wrote:

I am trying to script Calligra Sheets (formerly KSpread) with
python.  I
have gotten some of the included example scripts to run so I know
python
scripting is running.

I found the following snippet on their website:

import KSpread
sheet = KSpread.view().sheet()
# swap text of B5 and C6
t1 = sheet.text("B5")
t2 = sheet.text(6,3)
sheet.setText("B5", t2)
sheet.setText(6, 3, t1)
# swap value of D7 and E8
v1 = sheet.value("D7")
v2 = sheet.value(8,5)
sheet.setValue("D7", v2)
sheet.setValue(8, 5, v1)

Error: 'str' object has no attribute 'text'
  File
"file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py",
line
4, in 


This error message appeared in a dialog box.

I've taught myself some Python but I don't understand what is
happening
here.  Shouldn't t1 be a sheet object?  What would cause it to be a
str
instead?



Since somebody has censored the rest of the error traceback, we can't
even tell what line is giving the error.  Assuming you know it's
t1 = sheet.text("85")


I think line wrapping obscured that it is line 4 t1 = sheet.text("B5").


I saw the line 4, but didn't see anyplace where it showed me line 4.  So
i had to guess.  And for all I knew, the error isn't happening on that
line, but on some line called indirectly by that one.  The full stack
trace would be reassuring.  But apparently your Calligra environment is
censoring it.




then it has nothing to do with the type of t1, but with the type of
sheet.  If that's the case, then print out type(sheet) and see what it
actually is.  Then consult the documentation for the
KSpread.view().sheet() function and see what it's documented to return.



The docs say: Returns the KSpread::ViewAdaptor object in which the
document is displayed.

I would like to follow your advice and print out type(sheet) but right
now I don't know how.  This is all running inside Calligra sheets and so
far the only thing I have gotten out if it is the error message.


Are you permitted to edit this myswap.py file?  If so, add a line that
prints the useful information immediately before the line which causes
the exception.  And if print is also swallowed by your helpful
environment, then write to a file.


Yes I can and it does swallow it, so I redirected to a file and it says
.  Same as the error message.  So now I need to figure out
why it's not returning the object expected.

I can run the sample scripts that were installed but not something I
originate.  I guess I must be missing something procedural that is
keeping them from running properly.

Thanks for you help.

Regards,  Jim




Just a follow up for completeness in case some else finds this and has 
the same problem.


Replace line 2   sheet = KSpread.view().sheet()

with

sheetname = KSpread.currentSheet().sheetName()
sheet = KSpread.sheetByName(sheetname)

Then it will run with no errors.

Regards,  Jim




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


[Tutor] How convert an int to a string

2013-06-22 Thread Jim Byrnes
I need to convert a series of digits like 060713 to a string so I can 
make it look like a date 06-07-13.


>>> a = 060713
>>> a[:2]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'int' object has no attribute '__getitem__'
>>> b = str(a)
>>> b[:2]
'25'
>>> b
'25035'
>>>

I was confused at first but then realized that the  0  makes it octal. I 
thought str() would do it but it didn't. Reading about str() it talks of 
string representation.  So how can I convert it to a true string I can 
slice and build my date look a like?


Thanks,  Jim

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


Re: [Tutor] How convert an int to a string

2013-06-22 Thread Jim Byrnes

On 06/22/2013 05:10 PM, David Rock wrote:

* Jim Byrnes  [2013-06-22 16:01]:

I need to convert a series of digits like 060713 to a string so I can
make it look like a date 06-07-13.

  >>> a = 060713
  >>> a[:2]
Traceback (most recent call last):
File "", line 1, in 
TypeError: 'int' object has no attribute '__getitem__'
  >>> b = str(a)
  >>> b[:2]
'25'
  >>> b
'25035'
  >>>

I was confused at first but then realized that the  0  makes it octal. I
thought str() would do it but it didn't. Reading about str() it talks of
string representation.  So how can I convert it to a true string I can
slice and build my date look a like?


Is there a requirement to store them as numbers in the first place?  Why
not just store them as a string?

a = '060713'



Yes. I am scripting data entry in a spreadsheet.  I can enter the 6 
numbers quite rapidly using the number pad but entering the " - "'s to 
make it look like a date slows me down.  So I thought I would let python 
do that for me.


Regards,  Jim


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


Re: [Tutor] How convert an int to a string

2013-06-23 Thread Jim Byrnes

On 06/22/2013 06:24 PM, Dave Angel wrote:

On 06/22/2013 07:03 PM, Jim Byrnes wrote:

On 06/22/2013 05:10 PM, David Rock wrote:

* Jim Byrnes  [2013-06-22 16:01]:

I need to convert a series of digits like 060713 to a string so I can
make it look like a date 06-07-13.

  >>> a = 060713
  >>> a[:2]
Traceback (most recent call last):
File "", line 1, in 
TypeError: 'int' object has no attribute '__getitem__'
  >>> b = str(a)
  >>> b[:2]
'25'
  >>> b
'25035'
  >>>

I was confused at first but then realized that the  0  makes it
octal. I
thought str() would do it but it didn't. Reading about str() it
talks of
string representation.  So how can I convert it to a true string I can
slice and build my date look a like?


Is there a requirement to store them as numbers in the first place?  Why
not just store them as a string?

a = '060713'



Yes. I am scripting data entry in a spreadsheet.  I can enter the 6
numbers


Six digits, not numbers.


quite rapidly using the number pad but entering the " - "'s to
make it look like a date slows me down.  So I thought I would let python
do that for me.



I don't have any experience with using Rxlorg to script the Gemdaddy
spreadsheet program.  Maybe if you actually got specific, somebody would
have familiarity with the ones you're using.


It is Calligrsheets.  I didn't mention it because I was focused on the 
python error message I was seeing.  Python version is 2.7.3.



Most likely all you have to do is specify with the spreadsheet that the
user is to enter a string.  If it makes some sort of assumption that
strings cannot start with a digit, then it's just broken.


I can set the cell contents as text or numeric and I can extract the 
info either as a string or an int.  Each method gives it own error.  The 
code is short so I will post it.


def regionChanged(regions):
""" In column A. Converts data entered as mmddyy to mm-dd-yy """
myCell = viewer.selection()
print myCell
if myCell[0] - 1 == 1:
#cell_value = sheet.text(myCell[0] - 1, myCell[1])  #[1]
cell_value = sheet.value(myCell[0] - 1, myCell[1])  #[2]
print 'Type is ', type(cell_value)
cell_value = cell_value[:2] + '-' + cell_value[2:4] + '-' + 
cell_value[4:]
print 'Cell value is ', cell_value
cell_name = sheet.cellName(myCell[0] - 1, myCell[1])
writer.setCell(cell_name)
writer.setValue(cell_name, cell_value)
viewer.setSelection([2, myCell[1], 1, 1])

[1]  cell_value will always be a string.
[2]  cell_value will be a string or a long depending on cell type.

Here is the output from the terminal. Note: Kross is the plugin that 
enables Python scripting.



### code from [1], cell type = text ###
Kross: "PythonScript::Constructor."
Kross: "PythonScript::execute"
Kross: "PythonScript::execute result=None"
[2, 5, 1, 1]
Type is  
Cell value is  06-25-13
Kross: "PythonInterpreter::extractException:
"
Kross: "PythonExtension::proxyhandler Had exception on line -1:
invalid literal for int() with base 10: '06-25-13'
"
ValueError: invalid literal for int() with base 10: '06-25-13'
Kross: "PythonScript::Destructor."


### code from [2], cell type = text ###
Kross: "PythonScript::Constructor."
Kross: "PythonScript::execute"
Kross: "PythonScript::execute result=None"
[2, 5, 1, 1]
Type is  
Cell value is  06-25-13
Kross: "PythonInterpreter::extractException:
"
Kross: "PythonExtension::proxyhandler Had exception on line -1:
invalid literal for int() with base 10: '06-25-13'
"
ValueError: invalid literal for int() with base 10: '06-25-13'
Kross: "PythonScript::Destructor."


### code [1], cell type = numeric ###
Kross: "PythonScript::Constructor."
Kross: "PythonScript::execute"
Kross: "PythonScript::execute result=None"
[2, 5, 1, 1]
Type is  
Cell value is  06-25-13
Kross: "PythonInterpreter::extractException:
"
Kross: "PythonExtension::proxyhandler Had exception on line -1:
invalid literal for int() with base 10: '06-25-13'
"
ValueError: invalid literal for int() with base 10: '06-25-13'
Kross: "PythonScript::Destructor."



### code [2], cell type numeric ###
Kross: "PythonScript::Constructor."
Kross: "PythonScript::execute"
Kross: "PythonScript::execute result=None"
[2, 5, 1, 1]
Type is  
Kross: "PythonInterpreter::extractException:
  File 
"file:///home/jfb/.kde/share/apps/sheets/scripts/enter_invoices.py", 
line 38, in regionChanged

"
TypeError: 'long' object has no attribute '__getitem__'
Kross: "PythonScript::Destructor."


Regards,  Jim

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


Re: [Tutor] How convert an int to a string

2013-06-23 Thread Jim Byrnes

On 06/23/2013 06:50 PM, Dave Angel wrote:

On 06/23/2013 12:43 PM, Jim Byrnes wrote:

On 06/22/2013 06:24 PM, Dave Angel wrote:

On 06/22/2013 07:03 PM, Jim Byrnes wrote:

On 06/22/2013 05:10 PM, David Rock wrote:

* Jim Byrnes  [2013-06-22 16:01]:

I need to convert a series of digits like 060713 to a string so I can
make it look like a date 06-07-13.

  >>> a = 060713
  >>> a[:2]
Traceback (most recent call last):
File "", line 1, in 
TypeError: 'int' object has no attribute '__getitem__'
  >>> b = str(a)
  >>> b[:2]
'25'
  >>> b
'25035'
  >>>

I was confused at first but then realized that the  0  makes it
octal. I


In Python source code.  But the date number is being entered into the
spreadsheet, so the leading zero means no such thing.  It also means no
such thing when a strictly Python program does something like:
 x = int(raw_input())
This is why context is so important.


thought str() would do it but it didn't. Reading about str() it
talks of
string representation.  So how can I convert it to a true string I
can
slice and build my date look a like?


Is there a requirement to store them as numbers in the first place?
Why
not just store them as a string?

a = '060713'



Yes. I am scripting data entry in a spreadsheet.  I can enter the 6
numbers


Six digits, not numbers.


quite rapidly using the number pad but entering the " - "'s to
make it look like a date slows me down.  So I thought I would let
python
do that for me.



I don't have any experience with using Rxlorg to script the Gemdaddy
spreadsheet program.  Maybe if you actually got specific, somebody would
have familiarity with the ones you're using.


It is Calligrsheets.


I can't find any such thing.  Do you perhaps mean Calligra Sheets, at
http://www.calligra.org/sheets/ ???  If so, I'm having trouble finding
any information on the internet about scripting it, in Python or
otherwise.  It is available on Ubuntu's "Software Centre," but the only
review was rather negative.



Yes it is Calligra Sheets, that was a typo.  It is a fork of what used 
to be the KDE app kspread. Documentation is sparse that's why it has 
taken me this long to make any progress at all. Here are a couple of the 
more usefull links.


http://techbase.kde.org/Development/Tutorials/KSpread_Scripting
http://kross.dipe.org/dox/kspread.html#a00013


Using what to interface to it?  I'll assume that's what's called Kross
below.  I'll also have to make wild guesses about the available
functions and methods that Kross gives you.  Like do you have to use
writer.setValue() for both ints and strings, or does it have separate
function calls?  Does it have one for setting dates?  Perhaps string is
the wrong type entirely.


Yes Kross enables the python scripting. From the docs:

bool setValue(QVariant value, bool parse=true) [slot]

Set the value of the current cell.

value

The value that should be set.
parse

If this is true, the default, then the value got parsed to look for 
the type else we assume the value has the correct type.


true if the value was set successful else false is returned.

I take this to mean that it checks the under lying format of the cell 
and then supplies the value in that format. As to dates I haven't tried 
one.  I actually don't need or want a true date format.  I'm not going 
to do any date math or anything. I am just looking for some 
representation that looks like mm-dd-yy.



I can't find any information on the web about scripting Calligra.  If
there's no installed help either, I'd find something with better docs.


Well after a lot of searching and working with them I came the 
conclusion that Calligra Sheets was the best alternative available for 
python scripting in the Linux world.





 I didn't mention it because I was focused on the
python error message I was seeing.  Python version is 2.7.3.


But you don't have a Python error message.  It's missing the most
important parts, the traceback.  Something has intercepted that
exception and printed only a summary.  And specified a line number of
negative-one, which isn't reasonable either.

If the try/except is your own, then either fix the display or
temporarily disable the try.


It is not.  I pasted in all my code.


If the try/except is in the "Kross" code, and you have access to it,
then see what it looks like in the appropriate place.


It is open source but I think it is C++ so doubt my looking at it would 
help me much.





Most likely all you have to do is specify with the spreadsheet that the
user is to enter a string.  If it makes some sort of assumption that
strings cannot start with a digit, then it's just broken.


I can set the cell contents as text or numeric and I can extract the
inf

[Tutor] __abs__() not acting as expected

2014-03-23 Thread Jim Byrnes
I am reading Practical Programming - An Introduction to Computer Science 
Using Python 3.  They give this example:


>>> abs(-3)
3

>>> -3 .__abs__()
3

When I try it in idle or a terminal I get different results.

Python 3.3.5 (default, Mar 12 2014, 02:09:17)
[GCC 4.6.3] on linux

>>> abs(-3)
3

>>> -3 .__abs__()
-3

If I use a variable it works.

>>> x = -3
>>> x.__abs__()
3

I am curious as to what is happening.  Is the book wrong?  I checked 
it's errata and nothing is mentioned.


Regards, Jim



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


Re: [Tutor] Expressions, literals, operator precedence

2014-03-24 Thread Jim Byrnes

On 03/23/2014 11:36 PM, Ben Finney wrote:

Jim Byrnes  writes:


I am reading Practical Programming - An Introduction to Computer
Science Using Python 3.  They give this example:


abs(-3)

3


-3 .__abs__()

3


That's a poor example, in my opinion. It's not good for an introductory
text to show calling dunder methods like that on an integer literal.

Perhaps you could communicate with the maintainer of that material, to
point out the problem with their example. Hopefully they will remove the
example from an introductory text.



To be fair to the authors this was in a section taking about how the 
double underscore was special to Python and showing a little about what 
was going on behind the scenes.  They stressed that programmers would 
almost never use them in code.  I plan on sending them a message 
pointing out the results they show are incorrect.



Python 3.3.5 (default, Mar 12 2014, 02:09:17)
[GCC 4.6.3] on linux


abs(-3)

3


-3 .__abs__()

-3


Yes, I get the same result as you.

The reason is that the expression is being evaluated as::

 -( (3) .__abs__() )

That is:

* Create the integer object 3

* Get the result of that object's ‘__abs__’ method

* Negate (invert the sign) of the value

(If you really care, see the end of this message[0] for a demonstration
that this is exactly what happens.)


Presumably the expression should be different, as shown in your next
example::


If I use a variable it works.


x = -3
x.__abs__()

3


Yes, this is a better way to do it. But why are we calling the ‘__abs__’
function directly at all? That is, after all, the point of the ‘abs’
built-in function: to call the correct method on the object::


I am not really using it.  I was just trying to verify the result shown 
in an example.



 >>> x = -3
 >>> abs(x)
 3


I am curious as to what is happening.  Is the book wrong?  I checked
it's errata and nothing is mentioned.


I think that this is both an erratum, and a demonstration that the
example is a bad idea for the book entirely. Can you contact the
maintainer of that work to let them know?




Thanks for the confirmation and the explanation of what was happening, 
much appreciated.


Regards,  Jim


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


Re: [Tutor] 2 Very basic queries

2014-03-25 Thread Jim Byrnes

On 03/25/2014 02:21 PM, Saad Bashir wrote:

Hi everyone!

I am a novice programmer and actually learning to program in Python. I have
two issues that I am embarrassed to present as they seem to be extremely
basic.

1.  But encouraged by the site to ask event the most basic questions on
this forum, here goes:

  I am using the book:

Practical Programming: an introduction to computer science using Python 3.

As per its instructions I am using the IDLE environment (Python shell) of
Python [3.2.3 MSC v.1500 64 bit AMD64].  I have been going through the book
without any problems but have become stuck at the following stage:

When using "if" and "elif" statement I get two types of error messages:

1. Practicing the code as given in the book:

 >>> ph = float(input('Enter the pH level: '))
Enter the pH level: 8.5

if ph < 7.0:

...   print(ph, "is acidic.")
...elif ph > 7.0:
... print(ph, "is basic.")

When I write this in the Python shell, as soon as I hit return after "elif
ph > 7.0:"
I get an error message highlighting "elif" and saying syntax error.

Or if I try the indentation as follows with elif aligned if above I get the
message below:


ph = float(input('Enter the pH level: '))

Enter the pH level: 8.5

if ph < 7.0:

...   print(ph, "is acidic.")
...elif ph > 7.0:
... print(ph, "is basic.")

"SyntaxError: : unindent does not match any outer indentation level.

I have tried everything I can think of but to no avail. Please help.


>>> ph = float(input('Enter the ph level: '))
Enter the ph level: 8.5
>>>
>>> if ph < 7.0:
print(ph, 'is acidic.')
elif ph > 7.0:

SyntaxError: unindent does not match any outer indentation level
>>> if ph < 7.0:
print(ph, 'is acidic.')
elif ph > 7.0:
print(ph, 'is basic.')


8.5 is basic.

I am also learning Python and find idle hard to use. My first if/elif 
pair looks perfectly aligned but gives a SyntaxError, while my second 
if/elif pair looks to be not aligned but works fine.


I imagine there is a better explanation but here is how I think of it. 
Python seems to ignore the >>> and considers the i starting if to be in 
column 0, so if you put your elif against the left margin it works.




2. Another problem is that the Python shell is allowing me to copy/paste
any code at all.  Is there something I am not doing right?


I was able to copy from idle using Ctrl-C and paste to my newreader 
using Ctrl-V and then copy from my newsreader back to idle using the 
same procedure.  I am using Linux and you seem to be using Windows may 
be it works differently so I can't help you with it.



Regards,  Jim


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


Re: [Tutor] 2 Very basic queries

2014-03-26 Thread Jim Byrnes

On 03/26/2014 07:13 AM, spir wrote:

On 03/26/2014 02:32 AM, Jim Byrnes wrote:

2. Another problem is that the Python shell is allowing me to copy/paste
any code at all.  Is there something I am not doing right?


I was able to copy from idle using Ctrl-C and paste to my newreader
using Ctrl-V
and then copy from my newsreader back to idle using the same
procedure.  I am
using Linux and you seem to be using Windows may be it works
differently so I
can't help you with it.


If Ctrl-C & Ctrl-V don't work, try shift-Ctrl-C & shift-Ctrl-V, or using
the contextual menu with right-click. Anyway, in my view an interactive
interpreter is annoying for anything but using python as a pocket
calculator. If you feel like me, you may instead having a python trial
file always open (as a tab) in your favorite editor, and do most all
your trials there (instead of through the interpretor). This allow all
doing editing, modifications, variants... you like. Much better in my view.


Actually this is what I do also if the example I am looking at is more 
than a line or two.  When I am done with one example I just comment it 
out and move on to the next one.


regards,  Jim


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


[Tutor] Question about equality of sets

2014-04-05 Thread Jim Byrnes

Ubuntu 12.04 python 3.3

I was working through an exercise about sets. I needed to find the 
duplicates in a list and put them in a set.  I figured the solution had 
to do with sets not supporting duplicates.  I finally figured it out but 
along the way I was experimenting in idle and got some results I don't 
understand.


>>> s = {1,2,3}
>>> s
{1, 2, 3}
>>> s.add(1) == s# <1>
False
>>> s.add(1) == s.add(2)# <2>
True
>>>

Neither <1> or <2> changes s, so why is <1> False and <2> True ?

Thanks,  Jim

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


Re: [Tutor] Question about equality of sets

2014-04-05 Thread Jim Byrnes

On 04/05/2014 01:15 PM, Steven D'Aprano wrote:

On Sat, Apr 05, 2014 at 12:46:19PM -0500, Jim Byrnes wrote:

Ubuntu 12.04 python 3.3

I was working through an exercise about sets. I needed to find the
duplicates in a list and put them in a set.  I figured the solution had
to do with sets not supporting duplicates.  I finally figured it out but
along the way I was experimenting in idle and got some results I don't
understand.


s = {1,2,3}
s

{1, 2, 3}

s.add(1) == s# <1>

False

s.add(1) == s.add(2)# <2>

True




Neither <1> or <2> changes s, so why is <1> False and <2> True ?


You're making an assumption about what s.add returns. You're assuming it
returns a new set. It doesn't. Try this:


print(s.add(100))


and see what it prints.


Actually my assumption was worse than that.  I was thinking that because 
it would not add a dup it would end up being {1,2,3} == {1,2,3} 
completely forgetting that the left side would return None.


Thanks,  Jim



set.add modifies the set in place. So calling s.add(1) tries to change
s, it doesn't create a new set. It is standard in Python that methods
that change the object in place normally return None:

list.append
set.add
list.sort
list.reverse
dict.update

etc. So your examples try:

None == s  # this is false
None == None  # but this is true






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


Re: [Tutor] substituting for time_series, Pandas, Anaconda. Practical Programming, intro Comp Sci, Gries text

2014-05-14 Thread Jim Byrnes

On 05/14/2014 02:08 PM, Charles Agriesti wrote:

Practical programming, 2nd Edition, Paul Gries, Jennifer Campbell, Jason
Montojo
(Python 3)

P 184, the last half of chapter 10 requires the time_series module,
which is no longer available, apparently replaced by Pandas.


Read the first paragraph on page 185. The two def's on page 184 are 
saved in a file called time_series.py, this is what is being imported. 
Of course the paragraph gets confusing when it talks about importing 
tsdl.  If I remember right once the time_series file was in the current 
directory the examples then worked.




Regards,  Jim

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


Re: [Tutor] gnupg within a for loop

2014-06-01 Thread Jim Byrnes

On 06/01/2014 07:01 AM, Adam Gold wrote:

Hi there.  I'm trying to do the following using python 3: create a list
from all files in a particular directory, then loop over that list
symmetrically encrypting each file using the gnupg module (note, for the
moment I'm embedding the passphrase in the code while obviously in
practice it would have to be inputted by the user).

I start with the following which can be used to encrypt a single file
(assume I have the indentations correct in the actual code, I can't seem
to modify the wrapping with my email client):

phrase = '12345'
cipher = 'AES256'
gpg = gnupg.GPG(gnupghome='/home/adam/.gnupg')
with open('/home/adam/file1', 'rb') as f:
 status = gpg.encrypt_file(f, None, passphrase=phrase,
symmetric=cipher.upper(), output='/home/adam/file1.gpg')


Here you are giving with open( ) a full path to file1



This produces a single encrypted file, 'file1.gpg'.  I then try to embed
this in a for loop:

unencrypted = [u for u in os.listdir('/home/adam/temp')]


If I run this code with my info and print it, I get a list of files in 
my temp directory.



for G in unencrypted:
 gpg = gnupg.GPG(gnupghome='/home/adam/.gnupg')
 phrase = '12345'
 cipher = 'AES256'
 with open (G, 'rb') as f:
status = gpg.encrypt_file(f, None, passphrase=phrase,
symmetric=cipher.upper(), output=G + '.gpg')


If I then do:

for G in unencrypted:
print(G)

I get just a file name printed on each line.

When you do:

with open (G, 'rb') as f:

I think you have lost the path info for the files. If you give with 
open() path info it should work.  Hopefully if I am wrong someone with 
more knowledge will step in and give you a better answer.


Regards,  Jim



This produces the following error:
Traceback (most recent call last):
   File "", line 5, in 
 with open (G, 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'file1'

It seems 'G', which I'm intending to represent each successive element
of the list as the for loop iterates, does not find its way into the
gnupg code lines.  I have a feeling I'm missing something really basic
here :)
___
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


[Tutor] tkinter.filedialog?

2014-06-24 Thread Jim Byrnes
I am working with some demo programs in a breezypythongui book.  One 
program contains these two lines:


filetypes = [ ("Python files", "*.py"), ("Text files", "*.txt")]
fileName = tkinter.filedialog.askopenfilename(parent = self,
   filetypes = filetypes)

According to the book this should open a file dialog and show .py and 
.txt files, but it only shows .py files.  Thinking that maybe it had 
something to do with the breezypythongui implementation, I opened a 
terminal and tried:


Python 3.3.5 (default, Mar 12 2014, 02:09:17)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter.filedialog
>>> filetypes = [("Python files", "*.py"), ("Text files", "*.txt")]
>>> fileName = tkinter.filedialog.askopenfilename(filetypes = filetypes)

It pops up a file dialog but again only .py files are shown.

Why is it that both .py and .txt files are not shown?  It seems to be 
the correct way to do it.


Thanks,  Jim

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


Re: [Tutor] tkinter.filedialog?

2014-06-25 Thread Jim Byrnes

On 06/25/2014 02:36 AM, Alan Gauld wrote:

On 25/06/14 02:37, Jim Byrnes wrote:


 >>> import tkinter.filedialog
 >>> filetypes = [("Python files", "*.py"), ("Text files", "*.txt")]
 >>> fileName = tkinter.filedialog.askopenfilename(filetypes = filetypes)

It pops up a file dialog but again only .py files are shown.

Why is it that both .py and .txt files are not shown?


filetypes does not control which files are shown it controls which
filters are shown. There is a drop down list on the dialog that you can
select the filter that is applied. You should find there are two in your
case: Python files and text files.

If you select the text files filter it will show only text files...


hth


OK, I see it now, thanks.  I guess I am conditioned to seeing a downward 
pointing arrow head or triangle to indicate a drop down list, didn't 
even pay attention to the little rectangle at the right of the control.


Regards,  Jim

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


[Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-08 Thread Jim Byrnes

I would like to automate running virtualenv with a python script by:

opening gnome-terminal
cd to proper directory
run source /bin/activate

I found some examples of using os.system() to get gnome-terminal to open 
but I can't figure out how then cd to the proper directory in the new 
terminal.


My biggest frustration right now is that I can't find any documentation 
on how to use os.system().  Looking at the docs on the Python site I 
don't see system() under the os module.  Googling hasn't helped.


Thanks,  Jim

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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-09 Thread Jim Byrnes

On 07/09/2014 04:27 AM, Walter Prins wrote:

Hi Jim,

On 8 July 2014 21:45, Jim Byrnes  wrote:


I would like to automate running virtualenv with a python script by:

opening gnome-terminal
cd to proper directory
run source /bin/activate

I found some examples of using os.system() to get gnome-terminal to open
but I can't figure out how then cd to the proper directory in the new
terminal.

My biggest frustration right now is that I can't find any documentation on
how to use os.system().  Looking at the docs on the Python site I don't see
system() under the os module.  Googling hasn't helped.



Could you explain what you're trying to achieve?  Virtualenv is about
setting up an OS/Unix shell environment (For Windows there's a Powershell
variant of virtualenv...) so that a custom Python installation is used by
default instead of the system wide on (including possibly using a custom
Python executable.)  It therefore seems that trying to automate
"activating" a virtualenv with python (which presumably would use the
system wide python) is not adding much value? Hence my question: What are
you actually trying to achieve?

Walter



I forgot to mention I am using Linux (Ubuntu 12.04).

I am working my way through a book about breezypythongui which uses 
Python 3, hence virtualenv.  I found that each time I started to work 
with it I did the above 3 steps, I was just looking to automatic that 
repetitive task.


Regards,  Jim


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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-09 Thread Jim Byrnes

On 07/08/2014 06:39 PM, Alan Gauld wrote:

On 08/07/14 21:45, Jim Byrnes wrote:

I would like to automate running virtualenv with a python script by:

opening gnome-terminal
cd to proper directory
run source /bin/activate


Thats almost certainly the wrong approach.
Instead of trying to automate what the user does in the terminal replace
the terminal with Python.

Run the cd command from within Python (os.chdir())
Run Activate from within Python (this is where os.system()
could be used, but subprocess.call() is considered better
practice.


I found some examples of using os.system() to get gnome-terminal to open
but I can't figure out how then cd to the proper directory in the new
terminal.


You can't. os.system() just runs a command it has no way to interaxct5
with the command, you do that manually. Its perfectly fine for
displaying a directory listing (although os.listdir() would be better)
or sending a file to a printer, or even opening a terminal/editor
for the user to interact with. But its no good for your program
interacting with it. Thats what subprocess is for.


Alan and the others that offered advice, thanks. I see that I have taken 
the wrong approach.  My intent was to automate something I was doing 
manually time after time and learn a little more Python as well.





My biggest frustration right now is that I can't find any documentation
on how to use os.system().  Looking at the docs on the Python site I
don't see system() under the os module.


You should, although they don;t have a lot to say...








 Googling hasn't helped.


When you know the module use the browser search tools on the page itself
- that's how I found it. I searched for os.system and it
was the 3rd occurence.



My mistake.  I went to the Docs page and clicked on modules and then os. 
For some reason as I was scrolling down the page I thought the  subject 
had changed and stopped reading.  Now I see I stopped reading to soon as 
it is much further down the page.


Thanks,  Jim

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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-10 Thread Jim Byrnes

On 07/09/2014 05:40 PM, Cameron Simpson wrote:

On 09Jul2014 09:00, Jim Byrnes  wrote:

My mistake.  I went to the Docs page and clicked on modules and then
os. For some reason as I was scrolling down the page I thought the
subject had changed and stopped reading.  Now I see I stopped reading
to soon as it is much further down the page.


When searching for doco on particular functions I find the Index is a
good place. Go to the "S" section and find "system"; there should be a
link directly to the relevant doc section.

Cheers,
Cameron Simpson 



There was, thanks for the tip.

Regards,  Jim


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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-10 Thread Jim Byrnes

On 07/09/2014 04:16 PM, Walter Prins wrote:

Hi Jim,

On 9 July 2014 14:43, Jim Byrnes  wrote:


On 07/09/2014 04:27 AM, Walter Prins wrote:


I forgot to mention I am using Linux (Ubuntu 12.04).



I am working my way through a book about breezypythongui which uses Python
3, hence virtualenv.  I found that each time I started to work with it I
did the above 3 steps, I was just looking to automatic that repetitive task.



In that case you should put these commands in your .bashrc file so it gets
set up as your user's default.  (The .bashrc file is somewhat like DOS's
"autoexec.bat" file, if you're familiar with this, except each user has
their own .bashrc.)  You can also create a shell script that does this for
you.  (You can install "virtualenv wrapper" which gives you some further
commands to make working with virtualenvs easier.)

Regards

Walter



I realize I could have used a shell script but since I was working with 
Python I thought I might learn some more Python by trying to use it.  As 
it turns out, I did learn quite a bit through this discussion.


Thanks for the pointer to virtualenv wrapper.

Regards,  Jim


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


Re: [Tutor] Gmane archive/web site

2014-07-10 Thread Jim Byrnes

On 07/10/2014 11:59 AM, Alan Gauld wrote:

I just tried accessing gmane and the web site(*) seems to be down.
The news server is working OK but the web site is not responding.
(*)
www.gmane.org

Is it a problem at my end? or are others experiencing the same?



I just tried it and it timed out without connecting.

Regards,  Jim

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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-11 Thread Jim Byrnes

On 07/10/2014 09:23 AM, Jim Byrnes wrote:

On 07/09/2014 04:16 PM, Walter Prins wrote:

Hi Jim,

On 9 July 2014 14:43, Jim Byrnes  wrote:


On 07/09/2014 04:27 AM, Walter Prins wrote:


I forgot to mention I am using Linux (Ubuntu 12.04).



I am working my way through a book about breezypythongui which uses
Python
3, hence virtualenv.  I found that each time I started to work with it I
did the above 3 steps, I was just looking to automatic that
repetitive task.



In that case you should put these commands in your .bashrc file so it
gets
set up as your user's default.  (The .bashrc file is somewhat like DOS's
"autoexec.bat" file, if you're familiar with this, except each user has
their own .bashrc.)  You can also create a shell script that does this
for
you.  (You can install "virtualenv wrapper" which gives you some further
commands to make working with virtualenvs easier.)

Regards

Walter



I realize I could have used a shell script but since I was working with
Python I thought I might learn some more Python by trying to use it.  As
it turns out, I did learn quite a bit through this discussion.

Thanks for the pointer to virtualenv wrapper.

Regards,  Jim



I've worked on this a little more. If I create a file like:

#!/usr/bin/python
import os, subprocess
subprocess.Popen(args=["gnome-terminal",
"--working-directory=/home/jfb/Documents/Prog/Python/breezygui"])

and execute it, it will take me to the correct directory.  Once there if 
I type in 'source bin/activate' I will get a virtualenv. However I can't 
figure out how to do it from my script.


I have tried adding "--command=source bin/active" to args=
but then I get this error:

There was an error creating the child process for this terminal
Failed to execute child process "source" (No such file or directory)

To check if I could even use "--command=", I added "--command=python" 
and I got a  python session.


Could some one tell me what I need to do to issue the command to setup 
virtualenv?


Thanks,  Jim


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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-12 Thread Jim Byrnes

On 07/11/2014 10:50 PM, Cameron Simpson wrote:

On 11Jul2014 20:29, Jim Byrnes  wrote:

I've worked on this a little more. If I create a file like:

#!/usr/bin/python
import os, subprocess
subprocess.Popen(args=["gnome-terminal",
   "--working-directory=/home/jfb/Documents/Prog/Python/breezygui"])

and execute it, it will take me to the correct directory.  Once there
if I type in 'source bin/activate' I will get a virtualenv. However I
can't figure out how to do it from my script.

I have tried adding "--command=source bin/active" to args=
but then I get this error:

There was an error creating the child process for this terminal
Failed to execute child process "source" (No such file or directory)

To check if I could even use "--command=", I added "--command=python"
and I got a  python session.

Could some one tell me what I need to do to issue the command to setup
virtualenv?


Your problem is that "source" is a shell builtin because it must affect
the shell internals, and although gnome-terminal's --command option
takes a string it does not seem to be a shell string, passed to "sh".
Instead, it seems gnome-terminal takes it upon itself to take a string
and break it up into words and expected the first word to be an
executable program i.e. "source" in your case.

Suggestions below, but first a tiny rant on the side: gnome-terminal's
command specification option is rubbish, a long standing gripe of mine
with gnome-terminal. Most decent terminal emulators take a -e option and
follow command strings (just like you're passing to subprocess.Popen).
Some are less helpful (eg OSX Terminal) and accept only a shell command;
in Terminal's case it seems to be literally typed at the terminal :-(
gnome-terminal seems to do neither.

Returning to your task:

Virtualenv is a directory to hold python modules etc and some "activate"
scripts to set up the environment so that this is used by commands.

People are generally pointed at the "bin/activate" shell file to source
to set things up, but that doesn't need to happen _inside_ the terminal.
You can do it outside and then run the terminal.

An example shell command might look like this:

   cd /home/jfb/Documents/Prog/Python/breezygui
   . ./bin/activate
   gnome-terminal

or

   cd /home/jfb/Documents/Prog/Python/breezygui; . ./bin/activate; exec
gnome-terminal

which avoids the difficulties with gnome-terminal's command line options.

So you could adapt your Popen invocation to look like this:

   subprocess.Popen(args=["sh", "-c", "cd
/home/jfb/Documents/Prog/Python/breezygui; . ./bin/activate;
gnome-terminal"])

That is only one line, in case some mail program breaks it up.


Thank you, that worked.  At first I thought it was not working because 
when I did it manually I ended up with a prompt that looked like:


(breezygui)jfb@jims1204:~/Documents/Prog/Python/breezygui$

The script result did not have the (breezygui) at the front.  Luckily I 
decided to test it and when I type python I got python3.


Thanks,  Jim



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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-12 Thread Jim Byrnes

On 07/12/2014 03:02 AM, Alan Gauld wrote:

On 12/07/14 02:29, Jim Byrnes wrote:


I've worked on this a little more. If I create a file like:

#!/usr/bin/python
import os, subprocess
subprocess.Popen(args=["gnome-terminal",
 "--working-directory=/home/jfb/Documents/Prog/Python/breezygui"])

and execute it, it will take me to the correct directory.  Once there if
I type in 'source bin/activate' I will get a virtualenv. However I can't
figure out how to do it from my script.


What I can't figure out is why you are trying to do this using
gnome-terminal? (You may have explained and I've missed it, in which
case I apologize) Why do you feel you need to start a terminal?

You normally execute the commands you want directly from within
Python not by driving a terminal emulator. Terminals are just
windows for humans. They run a shell that reads and executes
commands. They format the output to fit the window. So when
you use a terminal you are just adding 2 extra layers of
complexity.

You can change directory and run activate from within Python
without the terminal. You could even start a bash session if
you need to let the user (eg. you) type some commands. But you
shouldn't need to start a terminal and then try to force it
to execute commands. That just seems crazy to me. Or am I
missing something?



I guess because I don't have the depth of knowledge to know any better. 
I wanted to automate a tedious process using Python.  I was working with 
a Python3 version of breezypythongui on a Python2.7 system. So I would 
open a terminal, cd to the correct directory and run source 
bin/activate, which would leave me with an open window.  Then I could 
work with Python3 and see error messages. I just focused on doing the 
same thing, but using a script.


Regards,  Jim

Regards,  Jim

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


Re: [Tutor] How can I open and use gnome-terminal from a Python script?

2014-07-12 Thread Jim Byrnes

On 07/12/2014 01:36 PM, Alan Gauld wrote:

On 12/07/14 16:34, Jim Byrnes wrote:


I guess because I don't have the depth of knowledge to know any better.
I wanted to automate a tedious process using Python.  I was working with
a Python3 version of breezypythongui on a Python2.7 system. So I would
open a terminal, cd to the correct directory and run source
bin/activate, which would leave me with an open window.


OK, Now imagine you were doing this in (bash) shell - I think you
are familiar with shell scripts? You wouldn't try to make the shell
script open a second terminal and then try to inject commands
into that terminal? You would just run the cd and source commands in the
shell script within the terminal session you were already
using, right?

Python is just another scripting tool. You use it the same way. You run
the script from a terminal so you don't need to open another one, just
use the one you are in.



You're right.  I guess I caused some confusion by stopping short of 
stating my ultimate goal. I wanted a 2 click solution. Open a launcher 
and then click to run the script.  That's why I wanted to open the 
terminal from the script.  When I try to do something I am not sure of I 
usually start simple and once I have something working try to build on 
that. Sorry I didn't state it more clearly sooner, I guess I was too 
caught up in trying to get it to work.


Regards,  Jim

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