[Tutor] for loop question

2012-07-04 Thread Jim

Hello Friends,
I apologize for being such a bother. This problem has been evading me 
all day. Can you please give me a hint as to why I cannot put the 
variable UpperCaseSentence outside of the for loop?

I can do it in other instances but not in this one.
Thank you so much,
Jim

#Main function.
def main():

mySentence = (input("Enter text."))

mySentenceList = mySentence.split('.')



#Call fixCase function. Send it mySentenceList and receive result
#and stores result in variable named output.
output = fixCase(mySentenceList)
print(output)



def fixCase(myList):
#Begin making a loop through the list, using a variable myString
for myString in range (len(myList)):
tempString = myList[myString] #Store in temporary variable.
myList[myString] = tempString[0:1].upper() + 
tempString[1:len(tempString)] #Replace with upper

UpperCaseSentence = (myList[myString])
print(UpperCaseSentence)


#Call main function
main()

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


[Tutor] Using venv

2017-01-27 Thread Jim
It has been suggested to me that I should use a virtual environment and 
venv would be a good choice. I've read through PEP405 and this link [1].
Though some of it seems a little confusing to me, I'm sure I can get it 
up and running. This question seems a little dumb and maybe I am being a 
little dense, but then what?


Your program/script is done how do you run it? Do you always have to 
activate your venv and run it from there? I like to run Tkinter programs 
from a launcher. Would that be possible and what would the command look 
like? Lately I have been writing some Libreoffice calc macros and 
evaluating pyspread for it's macro capability. Would modules installed 
in my venv be available to the spreadsheet programs?



Thanks,  Jim


[1] https://realpython.com/blog/python/python-virtual-environments-a-primer/

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


Re: [Tutor] Using venv

2017-01-28 Thread Jim

On 01/27/2017 04:49 PM, Cameron Simpson wrote:

On 27Jan2017 15:47, jim  wrote:

It has been suggested to me that I should use a virtual environment
and venv would be a good choice. I've read through PEP405 and this
link [1].
Though some of it seems a little confusing to me, I'm sure I can get
it up and running. This question seems a little dumb and maybe I am
being a little dense, but then what?

Your program/script is done how do you run it? Do you always have to
activate your venv and run it from there? I like to run Tkinter
programs from a launcher. Would that be possible and what would the
command look like? Lately I have been writing some Libreoffice calc
macros and evaluating pyspread for it's macro capability. Would
modules installed in my venv be available to the spreadsheet programs?


The mere act of using the python from inside the venv invokes a python
that runs off the venv, so all you really need to do is to contrive to
execute that python instead of the system python where you want it.

If your scripts start with something like this:

 #!/usr/bin/env python3

then you can simply contrive that "python3" is found from the
virtualenv. You might put a symlink in your personal $HOME/bin
directory, or source the venv's "activate" file from your shell's
profile (this making the venv searched ahead of the system paths), etc.

Or your launcher might simply invoke:

 $HOME/path/to/your/venv/bin/python your-tk-inter-script.py

Cheers,
Cameron Simpson 



Thank you. Got it up and running and tested it with a previously written 
Tkinter script, which works fine.


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()

2017-02-01 Thread Jim

On 12/26/2016 04:48 AM, Peter Otten wrote:

Jim Byrnes wrote:


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


In theory you can open Libre Office from another thread, wait a moment and
then send it keystrokes from the main thread. I managed to do this with the
script below.

However, the procedure is very brittle; while experimenting I managed to
"press" the control key without releasing it afterwards. The interval from
doing it to realizing what was going on to "fixing" it (reboot) was an
interesting experience...

from contextlib import contextmanager
import subprocess
import threading
import time

import pykeyboard

kb = pykeyboard.PyKeyboard()


@contextmanager
def press_key(key, kb=kb):
kb.press_key(key)
try:
yield
time.sleep(1)
finally:
kb.release_key(key)


def open_it(filename):
subprocess.call(["libreoffice", filename])
print("exiting libreoffice thread")


LONG_ENOUGH = 15  # seconds

# enter text into an existing odt file
filename = "demo.odt"
text = "hello and goodbye"

opener = threading.Thread(target=open_it, args=(filename,))
opener.start()

time.sleep(LONG_ENOUGH)  # for libreoffice to start and open the file

kb.type_string(text)

with press_key(kb.control_key):
kb.tap_key("s")
with press_key(kb.alt_key):
kb.tap_key(kb.function_keys[4])


print("exiting main thread")




Peter,

My apologies for taking so long to get back and thank you for the code. 
With the holidays and moving to a new computer/OS I didn't have much 
time to work on my little project.


I was able to use your code and send the necessary keystrokes to 
manipulate LO. Thanks again.


Regards,  Jim


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


[Tutor] Please explain part of this code

2017-02-15 Thread Jim

import sys
from notebook import Notebook, Note

class Menu:
'''Display a menu and respond to choices when run.'''
def __init__(self):
self.notebook = Notebook()
self.choices = {
"1": self.show_notes,
"2": self.search_notes,
"3": self.add_note,
"4": self.modify_note,
"5": self.quit
}

def display_menu(self):
print("""
Notebook Menu

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")

def run(self):
'''Display the menu and respond to choices.'''
while True:
self.display_menu()
choice = input("Enter an option: ")
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))


The author says:

The action variable actually refers to a specific method and is called 
by appending empty brackets (since none of the methods require 
parameters) to the variable.


I sort of understand what is going on with "action". All of the choices 
to the right of the :'s are methods defined elsewhere in the code. So I 
guess that will call whatever method is associated with a choice.


I don't recall ever seeing this before.  What is this technique called?

Thanks,  Jim

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


Re: [Tutor] Please explain part of this code

2017-02-15 Thread Jim

On 02/15/2017 04:56 PM, Alan Gauld via Tutor wrote:

On 15/02/17 22:37, Jim wrote:


 self.choices = {
 "1": self.show_notes,
 "2": self.search_notes,
 "3": self.add_note,
 "4": self.modify_note,
 "5": self.quit
 }

The author says:

The action variable actually refers to a specific method and is called
by appending empty brackets (since none of the methods require
parameters) to the variable.




I don't recall ever seeing this before.  What is this technique called?


Its very common, especially in GUIs and used in many
languages including C, VB, Java, Javascript and Lisp.
Its usually called a callback (because the stored
function is called back by the event receiver).

In C it is done by using a "pointer to a function".
In Lisp you create a Lambda (an anonymous function)
- which you can also do in Python and recent Java
versions. In Smalltalk and Ruby you define a "block".
In most of the other languages it's similar to Python,
you just pass the name of the function.

This is often referred to as the language treating
functions as "first class objects", and is a core
part of Functional Programming.

A common FP structure is the map function which takes
a function and a sequence and applies the function
to each member of the sequence, returning the
resultant sequence. Here is a short Python example:

def double(x): return x*2

data = [1,2,3,4]
result = map(double, data)   # -> [2,4,6,8]
print(result)

HTH

It does help. I have done a little bit of tkinter programing and have 
used callbacks, but when I looked at this code it just didn't register 
that way in my mind. Thanks for your explanation.


Regards,  Jim

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


[Tutor] Can a virtual environment be renamed?

2017-04-16 Thread Jim
My system python is 2.7.12 so I created a virtual environment using venu 
to run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 
and put it in env36. Is it possible to change env to env35 for 3.5.2 
without breaking things?


Thanks, Jim

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


Re: [Tutor] Can a virtual environment be renamed?

2017-04-16 Thread Jim

On 04/16/2017 10:10 AM, Chris Warrick wrote:

On 16 April 2017 at 16:45, Jim  wrote:

My system python is 2.7.12 so I created a virtual environment using venu to
run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
put it in env36. Is it possible to change env to env35 for 3.5.2 without
breaking things?


No. You need to delete your existing virtualenv and create a new one.
You can just use `pip freeze > requirements.txt` in the old one and
run `pip install -r requirements.txt` in the new one to ”move” all the
packages you had.




Thanks Chris. I thought that would be the answer but wanted to check 
before I spent a lot of time trying to do something that was not possible.


Virtual environments tend to confuse me. My system is Mint 18.1 with 
2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6, 
then build it and then use it's version of venv to create a virtual 
environment to try 3.6. Is that correct?


Thanks,  Jim

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


Re: [Tutor] Can a virtual environment be renamed?

2017-04-17 Thread Jim

On 04/16/2017 02:18 PM, Mats Wichmann wrote:

On 04/16/2017 10:16 AM, Jim wrote:

On 04/16/2017 10:10 AM, Chris Warrick wrote:

On 16 April 2017 at 16:45, Jim  wrote:

My system python is 2.7.12 so I created a virtual environment using
venu to
run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6
and
put it in env36. Is it possible to change env to env35 for 3.5.2 without
breaking things?


No. You need to delete your existing virtualenv and create a new one.
You can just use `pip freeze > requirements.txt` in the old one and
run `pip install -r requirements.txt` in the new one to ”move” all the
packages you had.




Thanks Chris. I thought that would be the answer but wanted to check
before I spent a lot of time trying to do something that was not possible.

Virtual environments tend to confuse me. My system is Mint 18.1 with
2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6,
then build it and then use it's version of venv to create a virtual
environment to try 3.6. Is that correct?

Thanks,  Jim


It doesn't need to be terribly complicated, something called pyenv can
manage the install for you (yes, it will build it if needed).

pyenv install --list

to show what's available to install

pyenv install 3.6.0

to install a copy

If you set up the shell helpers, pyenv will let you create the
virtualenv and launch it:

pyenv virtualenv 3.6.0 test-3.6.0
pyenv activate test-3.6.0



Thanks Mats,

When I get a chance to try 3.6 this looks like the best way for me to 
install it.


Regards, Jim



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


Re: [Tutor] Can a virtual environment be renamed?

2017-04-17 Thread Jim

On 04/16/2017 11:24 AM, Chris Warrick wrote:

On 16 April 2017 at 18:16, Jim  wrote:

On 04/16/2017 10:10 AM, Chris Warrick wrote:


On 16 April 2017 at 16:45, Jim  wrote:


My system python is 2.7.12 so I created a virtual environment using venu
to
run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
put it in env36. Is it possible to change env to env35 for 3.5.2 without
breaking things?



No. You need to delete your existing virtualenv and create a new one.
You can just use `pip freeze > requirements.txt` in the old one and
run `pip install -r requirements.txt` in the new one to ”move” all the
packages you had.




Thanks Chris. I thought that would be the answer but wanted to check before
I spent a lot of time trying to do something that was not possible.

Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12
& 3.5.2 installed. So I would have to download a tar file of 3.6, then build
it and then use it's version of venv to create a virtual environment to try
3.6. Is that correct?


Yes, you need to install the appropriate interpreter first, and
likewise a virtualenv won’t work if you uninstall an
interpreter/upgrade it to a new minor version*. You might not need to
use the source tarball if
https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes works on Mint
(and if you do use tarballs, make sure to install somewhere in /opt or
whatever not to make a mess — it’s easy to break your OS if you’re not
careful)

* eg. 3.5 → 3.6. Won’t ever happen on Mint or other “friendly”
distros, unless you do a dist-upgrade. Happens pretty often on
rolling-release distros or macOS with homebrew.



Chris, thanks for the confirmation and the link.

Regards, Jim

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


Re: [Tutor] General question rgrd. usage of libraries

2017-05-05 Thread Jim

On 05/05/2017 08:45 AM, Rafael Knuth wrote:

Hi there,

I just recently learned how to build a basic web scraper with Python
3.5 (I am learning Python for data analytics purposes). Being new to
coding, I have a question:

How do I know which libraries I need to perform a certain task?
For example, in case of this web scraper (which I built with help of a
tutorial on YouTube) I need to have urrlib and Beautiful Soup

import urllib
import urllib.request
from bs4 import BeautifulSoup

theurl = "https://twitter.com/rafaelknuth";
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, "html.parser")

print(soup.title.text)

i = 1
for tweets in soup.findAll("div",{"class":"content"}):
print(i)
print(tweets.find("p").text)
i = i + 1

Is there a way I can figure out which libraries I need when drafting my code?
Can you share your experiences? Right now, if I wanted for example to
populate a Google Sheet with my scraped web content - how would I know
which libraries I would need to actually make this happen? I am trying
wondering if there is a process to figure out what I exactly need
library-wise.




There is a Python API to google sheets but when I had a look, it seemed 
fairly complex. I haven't tried it yet but depending on what you need to 
do this library may be what you need:

      https://pypi.python.org/pypi/gspread.

Regards,  Jim


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


[Tutor] No file or directory error using subprocess and Popen

2017-05-14 Thread Jim

I am running this on Mint 18.
This is the third script I have written to open and position windows in 
workspaces. The first two work, but trying to open ebook-viewe r 
(calibre) with a specific book produces the following error.

If I run the same command in the terminal it works without an error.


Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in 
open_it

subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer 
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'


Code:

# place_windows_OO_WS3.py

import subprocess
from subprocess import Popen,PIPE
import threading
import time

class Place():

def __init__(self):
self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer 
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']

self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

def open_it(self):
subprocess.call([self.program])

def open_and_move(self):
for self.program in self.programs:
opener = threading.Thread(target=self.open_it)
opener.start()
time.sleep(2)
p = Popen(['xdotool', 'search', '--classname', 
self.classname[self.program]], stdout=subprocess.PIPE)


if self.classname[self.program] == 'sun-awt-X11-XFramePeer':
wid = str(p.stdout.read())
wid = wid[len(wid) - 11 : len(wid) - 3]
x = '0'
y = '0'
print('***jedit***')
elif self.classname[self.program] == 'google-chrome':
wid = str(p.stdout.read())
wid = wid[len(wid) - 11 : len(wid) - 3]
x = '1924'
y = '0'
print('***google***')
elif self.classname[self.program] == 'doublecmd':
wid = str(p.stdout.read())
wid = wid[len(wid) - 11 : len(wid) - 3]
x = '1924'
y = '537'
print('***double***')
else:
wid = str(p.stdout.read())
wid = wid[len(wid) - 11 : len(wid) - 3]
x = '2540' #'1924'
y = '537'
print('***calibre***')
subprocess.call(['xdotool', 'windowmove', str(wid), x, y])

I did some googling and it seems that subprocess does not have a length 
limit in linux. Could someone tell me how to correct the above error.


Thanks,  Jim

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


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/15/2017 02:48 AM, Steven D'Aprano wrote:

On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote:

I am running this on Mint 18. This is the third script I have
written to open and position windows in workspaces. The first two
work, but trying to open ebook-viewe r (calibre) with a specific
book produces the following error. If I run the same command in the
terminal it works without an error.


I think your problem is that you're telling subprocess to run a
command called:

ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub

 with no arguments. What you want is a command called:

ebook-viewer

and a single argument:

/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub

 I think (but haven't tried it) that the simplest way to fix that is
to change the entry in self.programs from:


self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']





to:

path_to_file =
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'






self.programs = ['jedit',

'google-chrome', 'doublecmd', ['ebook-viewer', path_to_file], ]


I made the changes you suggested.

def __init__(self):
path_to_book = 
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'
self.programs = ['jedit', 'google-chrome', 'doublecmd', 
['ebook-viewer', path_to_book ]]

self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

I noticed you have a , between the last two ]],s. I don't think you 
meant that but I tried it both ways just incase.




and see if that fixes it. (It may not be enough, or the right
approach, but at least you'll get a different error if it is wrong
:-)


Unfortunately you are correct, I did get a different error message.

Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in 
open_it

subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1474, in _execute_child
executable = os.fsencode(executable)
  File "/usr/lib/python3.5/os.py", line 862, in fsencode
raise TypeError("expect bytes or str, not %s" % 
type(filename).__name__)

TypeError: expect bytes or str, not list

Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 78, in 


Place()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in 
__init__

self.open_and_move()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 31, in 
open_and_move
p = Popen(['xdotool', 'search', '--classname', 
self.classname[self.program]], stdout=subprocess.PIPE)

TypeError: unhashable type: 'list'

Regards,  Jim



The difference is that the shell automatically splits things on
spaces, so it sees the space between ebook-viewer and the long path,
and treats the first word as the executable and the second as an
argument. But Python treats the whole string, spaces and quotes
included, as the executable.





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


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/14/2017 11:19 PM, boB Stepp wrote:

On Sun, May 14, 2017 at 10:57 PM, Jim  wrote:

I am running this on Mint 18.
This is the third script I have written to open and position windows in
workspaces. The first two work, but trying to open ebook-viewe r (calibre)
with a specific book produces the following error.
If I run the same command in the terminal it works without an error.


Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
open_it
subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'

Code:

# place_windows_OO_WS3.py

import subprocess
from subprocess import Popen,PIPE
import threading
import time

class Place():

def __init__(self):
self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']
self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

def open_it(self):
subprocess.call([self.program])


I'm not very familiar with using the subprocess module yet, but when
the above call to "subprocess.call([self.program])" occurs, isn't
subprocess.call() expecting a list like

['ebook-viewer', '/home/jfb ...']

?

Hope I am not off-track here.

boB


Bob,

I thought you were on to something, especially since Steven suggested 
about the same thing. See my reply to Steven. It seems to be looking for 
a str or byte not a list.


Thanks,  Jim


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


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/15/2017 07:03 AM, Peter Otten wrote:

Jim wrote:


I am running this on Mint 18.
This is the third script I have written to open and position windows in
workspaces. The first two work, but trying to open ebook-viewe r
(calibre) with a specific book produces the following error.
If I run the same command in the terminal it works without an error.


Exception in thread Thread-4:
Traceback (most recent call last):
   File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
 self.run()
   File "/usr/lib/python3.5/threading.py", line 862, in run
 self._target(*self._args, **self._kwargs)
   File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
open_it
 subprocess.call([self.program])
   File "/usr/lib/python3.5/subprocess.py", line 557, in call
 with Popen(*popenargs, **kwargs) as p:
   File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
 restore_signals, start_new_session)
   File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
 raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer


/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'


Code:

# place_windows_OO_WS3.py

import subprocess
from subprocess import Popen,PIPE
import threading
import time

class Place():

 def __init__(self):
 self.programs = ['jedit', 'google-chrome', 'doublecmd',
 'ebook-viewer


/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']

 self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
 'google-chrome':'google-chrome',
 'doublecmd':'doublecmd',
 'calibre-ebook-viewer': 'libprs500'}
 self.open_and_move()

 def open_it(self):
 subprocess.call([self.program])

 def open_and_move(self):
 for self.program in self.programs:
 opener = threading.Thread(target=self.open_it)
 opener.start()
 time.sleep(2)
 p = Popen(['xdotool', 'search', '--classname',
self.classname[self.program]], stdout=subprocess.PIPE)

 if self.classname[self.program] == 'sun-awt-X11-XFramePeer':
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '0'
 y = '0'
 print('***jedit***')
 elif self.classname[self.program] == 'google-chrome':
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '1924'
 y = '0'
 print('***google***')
 elif self.classname[self.program] == 'doublecmd':
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '1924'
 y = '537'
 print('***double***')
 else:
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '2540' #'1924'
 y = '537'
 print('***calibre***')
 subprocess.call(['xdotool', 'windowmove', str(wid), x, y])

I did some googling and it seems that subprocess does not have a length
limit in linux. Could someone tell me how to correct the above error.


Not directly related to your question, but I think you should have one
instance of your Place class per program. That way you keep related
information together and avoid the need to look it up in a dict or find it
with a long chain of if ... elif ... tests. For example:

# untested
import subprocess
import threading
import time

DELAY = 3.0  # seconds


class Place:
def __init__(self, cmd, classname=None, name=None, x=0, y=0):
if classname is None:
classname = cmd[0]
if name is None:
name = cmd[0]

self.cmd = cmd
self.classname = classname
self.name = name
self.x = x
self.y = y

def open_it(self):
subprocess.call(self.cmd)

def open_and_move(self):
opener = threading.Thread(target=self.open_it)
opener.start()
time.sleep(DELAY)
output = subprocess.Popen(
['xdotool', 'search', '--classname', self.classname],
stdout=subprocess.PIPE
).communicate()[0]
wid = output.split()[-1].decode()
subprocess.call(
[
'

Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/15/2017 08:33 PM, Jim wrote:

On 05/15/2017 02:48 AM, Steven D'Aprano wrote:

On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote:

I am running this on Mint 18. This is the third script I have
written to open and position windows in workspaces. The first two
work, but trying to open ebook-viewe r (calibre) with a specific
book produces the following error. If I run the same command in the
terminal it works without an error.


I think your problem is that you're telling subprocess to run a
command called:

ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub


 with no arguments. What you want is a command called:

ebook-viewer

and a single argument:

/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub


 I think (but haven't tried it) that the simplest way to fix that is
to change the entry in self.programs from:


self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']






to:

path_to_file =
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'







self.programs = ['jedit',

'google-chrome', 'doublecmd', ['ebook-viewer', path_to_file], ]


I made the changes you suggested.

def __init__(self):
path_to_book =
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'

self.programs = ['jedit', 'google-chrome', 'doublecmd',
['ebook-viewer', path_to_book ]]
self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

I noticed you have a , between the last two ]],s. I don't think you
meant that but I tried it both ways just incase.



and see if that fixes it. (It may not be enough, or the right
approach, but at least you'll get a different error if it is wrong
:-)


Unfortunately you are correct, I did get a different error message.

Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
open_it
subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1474, in _execute_child
executable = os.fsencode(executable)
  File "/usr/lib/python3.5/os.py", line 862, in fsencode
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
TypeError: expect bytes or str, not list

Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 78, in

Place()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in
__init__
self.open_and_move()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 31, in
open_and_move
p = Popen(['xdotool', 'search', '--classname',
self.classname[self.program]], stdout=subprocess.PIPE)
TypeError: unhashable type: 'list'

Regards,  Jim



Replying to myself to report that I got it working.
I changed open_it to:

def open_it(self):
if self.program == 'ebook-viewer':
subprocess.call([self.program, self.path_to_book])
else:
subprocess.call([self.program])

After looking at it, I realized I should be providing the path when I 
was actually opening the file in open_it not further down in 
open_and_move where I was positioning the windows. Also I realize 
open_and_move is a poor name and needs to be changed to move_it or 
something.


I still get the following error but it does not seem to effect the 
programs operation. So for now I am just glad it is working.


Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 84, in 


Place()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in 
__init__

self.open_and_move()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 37, in 
open_and_move
p = Popen(['xdotool', 'search', '--classname', 
self.classname[self.program]], stdout=subprocess.PIPE)

KeyError: 'ebook-viewer'

Thanks for everyones help,  Jim

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


Re: [Tutor] Using venv

2017-05-29 Thread Jim

On 05/29/2017 08:09 PM, Ben Finney wrote:

You should probably disregard this message as I have since solved the 
problem I was asking about. I originally wrote this message on 01/27/17, 
how it make it back to the list I don't know.


Regards,  Jim


Jim  writes:


It has been suggested to me that I should use a virtual environment
and venv would be a good choice. I've read through PEP405 and this
link [1].


One possible confusion is the terminology.

You have “a virtual environment” when you create one. The ‘venv’ module
is not itself a virtual environment; it is what you use to create one :-)


Though some of it seems a little confusing to me, I'm sure I can get
it up and running. This question seems a little dumb and maybe I am
being a little dense, but then what?


* In each shell where you want to be working in that virtual Python
   environment, activate the virtualenv (by running the commands from its
   corresponding ‘activate’ script; e.g. ‘source $VENV/bin/activate’).

* Do things requiring Python.


Your program/script is done how do you run it? Do you always have to
activate your venv and run it from there?


To get the benefits of that particular virtualenv, yes.


I like to run Tkinter programs from a launcher. Would that be possible
and what would the command look like?


How are the programs installed? Can you customise how they're launched?


Lately I have been writing some Libreoffice calc macros and evaluating
pyspread for it's macro capability. Would modules installed in my venv
be available to the spreadsheet programs?


The trick is that the environment variables for a process need to be set
either when the program starts, or within the program; it can't be done
externally. That isn't special to Python, it is how processes work.

The virtualenv is activated by setting particular shell environment
variables to specific values. If you can do that, the answer is yes.

The ‘source $VENV/bin/activate’ command just runs shell commands to set
those environment variables. It's not the only way to set those
environment variables.

Other Python-bundled programs, like LibreOffice or Blender, will likely
have their own ways of activating a virtualenv; or at least you'll
probably find people in those communities discussing how to do it.




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


Re: [Tutor] When to use classes

2017-08-20 Thread Jim

On 08/20/2017 03:12 AM, Alan Gauld via Tutor wrote:

On 20/08/17 02:47, Steven D'Aprano wrote:


since then feels like going back to the Dark Ages. Having to care about
low-level details like creating buttons, installing callbacks and so
forth just feels wrong.


To be fair most GUI frameworks come with a GUI builder that remove
the manual coding for things like that. Even Tk (upon which Tkinter
is based) has a couple of them, but for some reason the Python
implementation has never had one that worked well. The bigger
industrial grade GUI builders for Java(Swing/JFX), .NET(VS),
and even Gnome/Qt on Linux are all very easy to use to build
quite complex GUIs.


There is an alternative to callback based GUI frameworks, and that is an
message-passing, event-driven language. The framework handles the events
for you, and fires off messages to objects. If the object doesn't handle
the event, it is sent to the next object in the message-passing
heirarchy.


Again, that's how pretty much every modern GUI works. The
callback bit is just a manual exposure of what the GUI
builder does under the covers. Most casual GUI programmers
never create or specify a call back they just click the widget
in the GUI builder and are taken to the pre-written empty
function body.


The language was Hypertalk, the scripting language of Apple's Hypercard
application in the mid to late eighties.


There was(is?) a project on Sourcefoirge to build a Python
equivalent to Hypercard. I played with it a long time ago
but it wasn't really ready for serious use in my view.
I don't know if its still running or how far it has
progressed.

And there are several GUI builders for Python beyond Tk
although I haven't had much success with any of them.
I suspect because Python is so high level as a language
that the effort they save is much less than when using
Java or C++.


By today's standards it is woefully primitive: only a single window, of
a fixed size, black and white graphics, and only a fixed set of
pre-defined GUI widgets and no way to create your own. But it is
remarkable just how much power there is in just two widgets, text fields
and buttons, especially since the buttons can be specialised into push
buttons, radio buttons and checkbox buttons.


Borland tried a similar trick on Windows with a tool called
TurboVision(Or ObjectVision? my memory fails me) which was
an entirely graphical tool with even the code being built using
graphical code blocks. Scratch does the same thing today
for beginning programmers. But all of these tools run
into the same issues - eventually you will need to create
something more complex which the tool can't handle.


stack (Hypercard document) consisted of at least one shared background
used by at least one card. Cards inherited their look, state and
behaviour from their background, but could override any part of that.


I think that was Hypercard's USP. The idea of an inherited
look 'n feel was quite powerful and I'm surprised that nobody
else has picked that up, at least as an option, for a new
window/screen/frame.


The Hypercard application managed the GUI event loop for you. It tracked
the mouse and the keyboard, and other events, and each time it noticed
an event, it sent a message to the appropriate object (a widget, card,
background or stack). That object could either handle the message, or
ignore it. If it ignored the message, it passed on to the next object in
the heirachy.


Again that's pretty much how every GUI framework operates.
Its just that Tkinter etc make it explicit by forcing you
to pass the parent object and event handler(s) into the
widget at creation time. A GUI builder does that for you.


If this looks a tiny bit like Javascript, that's because Javascript
borrowed the idea and language of handlers from Hypertalk and
Hypercard.


Most OO GUI frameworks borrowed these ideas from Hypercard
(and indeed the Object Pascal MacApp framework that
Hypercard was built on). The MaCapp framework was a huge
step up from the older procedural frameworks such as
X Windows and MS Windows etc that had gone before.


To call a handler in another object, you sent your own message, and the
Hypercard application would manage the details:

send "print" to field "Address" of card "George"

That message would be sent via the same message path as any other event,


Again that's pretty much how any GUI framework works
today (although they also allow direct message passing
between code objects too). They all have some kind of
event posting service.

Hypercard's legacy is alive and well in the GUI frameworks
we all use today. The tools used to make that accessible
are not so simple however, and in the end, the ability to
create powerful, full featured GUIs has trumped the easy
to use, but ultimately limited, scope of Hypercard.



In one sense Hypercard is still alive. Check out Livecode at livecod

[Tutor] Virtual environment question

2018-03-11 Thread Jim
It was my understanding that using a virtual environment kept everything 
isolated in that environment. So I was surprised when I got the 
following error message.


(env) jfb@jims-mint18 ~ $


File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", 
line 528, in _request

resp = opener.open(request, timeout=self._timeout)

  File "/usr/lib/python3.5/urllib/request.py", line 466, in open
response = self._open(req, data)


I snipped most of the error msg because for the purpose of this question 
I am not interested in them. I tried  something that I did not think 
would work and it did not.


I am wondering why the path for the first line and every line above it 
is /home/jfb/EVs/env and the second line and everything after is is

/usr/lib/.

I didn't think anything from my system python would be involved if I 
started from a virtual environment.


Regards,  Jim


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


Re: [Tutor] Virtual environment question

2018-03-11 Thread Jim

On 03/11/2018 05:54 PM, Cameron Simpson wrote:

Note: This message came straight to me and I haven't seen it on the list 
yet. Hopefully this reply will make it to the list.



On 11Mar2018 15:52, jim  wrote:
It was my understanding that using a virtual environment kept 
everything isolated in that environment. So I was surprised when I got 
the following error message.


(env) jfb@jims-mint18 ~ $


File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", 
line 528, in _request

   resp = opener.open(request, timeout=self._timeout)

 File "/usr/lib/python3.5/urllib/request.py", line 466, in open
   response = self._open(req, data)


I snipped most of the error msg because for the purpose of this 
question I am not interested in them. I tried  something that I did 
not think would work and it did not.


I am wondering why the path for the first line and every line above it 
is /home/jfb/EVs/env and the second line and everything after is is

/usr/lib/.

I didn't think anything from my system python would be involved if I 
started from a virtual environment.


It is possible to make a virtualenv which references the osurce python's 
library. These days the default is isolation, but older virtualenvs used 
to hook to the original python by default. This is controlled by 
virtualenv's --system-site-packages and --no-site-packages. Maybe you 
should build the env again using --no-site-packages explicitly and see 
if the behaviour changes.


If you're not using the "virtualenv" command to make the environment, 
please tell use exactly how it was made (there are other tools for the 
same purpose).


In fact, tell us regardless. It aids debugging.

Cheers,
Cameron Simpson  (formerly c...@zip.com.au)


I installed pyvenv in Jan 17 using synaptic on  Mint 18.

Here are the contents of the pyvenv cfg file:

home = /usr/bin
include-system-site-packages = false
version = 3.5.2

It's been awhile so I don't remember that much about the installation. I 
really don't know that much about virtual environments so I am guessing 
I accepted the defaults for the installation.


Just to be complete here is the entire error msg:

Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/login_af.py", line 36, in 
driver = webdriver.Remote(desired_capabilities=caps)
  File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", 
line 154, in __init__

self.start_session(desired_capabilities, browser_profile)
  File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", 
line 243, in start_session

response = self.execute(Command.NEW_SESSION, parameters)
  File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", 
line 310, in execute

response = self.command_executor.execute(driver_command, params)
  File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", 
line 466, in execute

return self._request(command_info[0], url, body=data)
  File 
"/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", 
line 528, in _request

resp = opener.open(request, timeout=self._timeout)
  File "/usr/lib/python3.5/urllib/request.py", line 466, in open
response = self._open(req, data)
  File "/usr/lib/python3.5/urllib/request.py", line 484, in _open
'_open', req)
  File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
  File "/usr/lib/python3.5/urllib/request.py", line 1282, in http_open
return self.do_open(http.client.HTTPConnection, req)
  File "/usr/lib/python3.5/urllib/request.py", line 1256, in do_open
raise URLError(err)
urllib.error.URLError: 

If you tell me where to look, I'd be happy to provide any more info you 
need.



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


Re: [Tutor] Virtual environment question

2018-03-12 Thread Jim

On 03/12/2018 04:04 AM, eryk sun wrote:

On Mon, Mar 12, 2018 at 12:44 AM, Jim  wrote:


home = /usr/bin
include-system-site-packages = false

[...]

 resp = opener.open(request, timeout=self._timeout)
   File "/usr/lib/python3.5/urllib/request.py", line 466, in open


This is normal. Virtual environments are not isolated from the standard library.


Interesting. All I know about virtual environments is what I read on the 
net. I always see them recommended as a way to keep from messing up the 
default python, so I thought isolation was their purpose.


Thanks,  Jim


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


Re: [Tutor] Virtual environment question

2018-03-13 Thread Jim

On 03/12/2018 08:44 PM, eryk sun wrote:

On Tue, Mar 13, 2018 at 1:31 AM, Jim  wrote:

On 03/12/2018 04:04 AM, eryk sun wrote:


On Mon, Mar 12, 2018 at 12:44 AM, Jim  wrote:


home = /usr/bin
include-system-site-packages = false


[...]


  resp = opener.open(request, timeout=self._timeout)
File "/usr/lib/python3.5/urllib/request.py", line 466, in open


This is normal. Virtual environments are not isolated from the standard
library.


Interesting. All I know about virtual environments is what I read on the
net. I always see them recommended as a way to keep from messing up the
default python, so I thought isolation was their purpose.


You're thinking of isolating packages that are installed in
site-packages, not the standard library. There's no point in copying
and recompiling the entire standard library in every virtual
environment.


Just curious. So do they share parts of the standard libray? What 
happens if the version of python I have in a virtual environment is 
totally different than any python available from the os? Say version 3 
vs version 2 in the os.


Regards,  Jim



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


[Tutor] Need help with FileNotFoundError

2018-04-26 Thread Jim
Been working my way through an online Python course. Up until now I have 
had no problems writing and running the programs using Python 3.6 in a 
virtual environment and then pasting them into the courses editor.


When I run this program on my system I get the following error.


# file_io.py

def copy(file, new_file):
with open(file) as data:
text = data.read()


with open(new_file, 'w') as new_text:
new_text.write(text)

copy('~/Documents/Courses/ModernBootcamp/story.txt', 
'~/Documents/Courses/ModernBootcamp/story_copy.txt')



(env36) jfb@jims-mint18 ~ $ python 
'/home/jfb/Documents/Courses/ModernBootcamp/file_io.py'

Traceback (most recent call last):
  File "/home/jfb/Documents/Courses/ModernBootcamp/file_io.py", line 
11, in 
copy('~/Documents/Courses/ModernBootcamp/story.txt', 
'~/Documents/Courses/ModernBootcamp/story_copy.txt')
  File "/home/jfb/Documents/Courses/ModernBootcamp/file_io.py", line 4, 
in copy

with open(file) as data:
FileNotFoundError: [Errno 2] No such file or directory: 
'~/Documents/Courses/ModernBootcamp/story.txt'


The file is there.

jfb@jims-mint18 ~/Documents/Courses/ModernBootcamp $ ls
adding_to_lists.py  errors.py functionsII.pyhelpers.py 
modules.py   stop_copying.py
animals exercise.py   functions.py  iteration.py 
oop.py   story.txt
decorators.py   file_io.pygenerators.py list_comps.py 
__pycache__  unlucky_numbers.py
dictionarys.py  FirstProgram  guessing_game.py  list_methods.py 
smiley_faces.py  while_loop.py


I must be doing something wrong path-wise, but I can't seem to figure it 
out. Any help appreciated.


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


Re: [Tutor] Need help with FileNotFoundError

2018-04-26 Thread Jim

On 04/26/2018 03:27 PM, Danny Yoo wrote:

copy('~/Documents/Courses/ModernBootcamp/story.txt',
'~/Documents/Courses/ModernBootcamp/story_copy.txt')



Hi Jim,

You may need to use os.path.expanduser, as "tilde expansion" isn't
something that's done automatically.

This is referenced in the docs when they say: "Unlike a unix shell, Python
does not do any automatic path expansions. Functions such as expanduser()
and expandvars() can be invoked explicitly when an application desires
shell-like path expansion. (See also the glob module.)"

  https://docs.python.org/3/library/os.path.html#module-os.path

Try adding a call to os.path.expanduser()
https://docs.python.org/3/library/os.path.html#os.path.expanduser on that
tilde-prefixed path string.

Hope this helps!


Danny,

Thanks for pointing me in the right direction. I had tried replacing the 
~ with home/jfb/... now I realize it should have been /home/jfb/... 
Working now.


Thanks,  Jim


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


[Tutor] pip stopped working gives error

2018-05-03 Thread Jim
I have python 3.6 installed in a virtual environment on Mint 18. Today I 
wanted to use pip and got this error when I tried to use it.


 (env36) jfb@jims-mint18 ~ $ pip help
Traceback (most recent call last):
  File "/home/jfb/EVs/env36/bin/pip", line 7, in 
from pip import main
  File 
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line 
43, in 

from pip.utils import get_installed_distributions, get_prog
  File 
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", 
line 23, in 

from pip.locations import (
  File 
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line 
9, in 

from distutils import sysconfig
ImportError: cannot import name 'sysconfig'

I searched for sysconfig and found this:

/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc
/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg
/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py

The results seem to be the same as when I searched a python 3.5 virtual 
environment I have setup.


It has worked in the past as I have installed pylint and pykeyboard with 
it. As I type this I just remembered Mint updated python 3.6 earlier today.


So now I suspect the update is involved. Has anyone else experienced 
this and know how to fix it?


Thanks, Jim

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


Re: [Tutor] pip stopped working gives error

2018-05-03 Thread Jim

On 05/03/2018 02:42 PM, Mats Wichmann wrote:

On 05/03/2018 01:10 PM, Jim wrote:

I have python 3.6 installed in a virtual environment on Mint 18. Today I
wanted to use pip and got this error when I tried to use it.

  (env36) jfb@jims-mint18 ~ $ pip help
Traceback (most recent call last):
   File "/home/jfb/EVs/env36/bin/pip", line 7, in 
     from pip import main
   File
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line
43, in 
     from pip.utils import get_installed_distributions, get_prog
   File
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py",
line 23, in 
     from pip.locations import (
   File
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line
9, in 
     from distutils import sysconfig
ImportError: cannot import name 'sysconfig'

I searched for sysconfig and found this:

/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc

/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg

/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py


The results seem to be the same as when I searched a python 3.5 virtual
environment I have setup.

It has worked in the past as I have installed pylint and pykeyboard with
it. As I type this I just remembered Mint updated python 3.6 earlier today.

So now I suspect the update is involved. Has anyone else experienced
this and know how to fix it?


I heard distutils may have been split out... see if you have a package
python3-distutils and if not installed, can you install it?


I have:

//usr/lib/python3.5/distutils
and
//usr/lib/python3.6/distutils, but no python3-distutils.

Checking in Synaptic there is no python3-distutils but there is a
python3-distutils-extra.

Regards, Jim


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


Re: [Tutor] pip stopped working gives error

2018-05-04 Thread Jim

On 05/03/2018 03:40 PM, Zachary Ware wrote:

On Thu, May 3, 2018 at 2:10 PM, Jim  wrote:

I have python 3.6 installed in a virtual environment on Mint 18. Today I
wanted to use pip and got this error when I tried to use it.

  (env36) jfb@jims-mint18 ~ $ pip help
Traceback (most recent call last):
   File "/home/jfb/EVs/env36/bin/pip", line 7, in 
 from pip import main
   File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py",
line 43, in 
 from pip.utils import get_installed_distributions, get_prog
   File
"/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py",
line 23, in 
 from pip.locations import (
   File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py",
line 9, in 
 from distutils import sysconfig
ImportError: cannot import name 'sysconfig'

I searched for sysconfig and found this:

/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc
/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg
/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py

The results seem to be the same as when I searched a python 3.5 virtual
environment I have setup.

It has worked in the past as I have installed pylint and pykeyboard with it.
As I type this I just remembered Mint updated python 3.6 earlier today.

So now I suspect the update is involved. Has anyone else experienced this
and know how to fix it?


First, try a clean venv (python3.6 -m venv venv && ./venv/bin/pip help).


Ok, I just tried this and got this error.

jfb@jims-mint18 ~ $ python3.6 -m venv /home/jfb/EVs/env365 && 
./venv/bin/pip help
The virtual environment was not created successfully because ensurepip 
is not

available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

apt-get install python3-venv

You may need to use sudo with that command.  After installing the 
python3-venv

package, recreate your virtual environment.

Failing command: ['/home/jfb/EVs/env365/bin/python3.6', '-Im', 
'ensurepip', '--upgrade', '--default-pip']


Couple of things troubling about this message. I just checked and 
python3-venv is installed, in fact I used it to install the python3.6 
environment I'm having problems with. I did a search and ensurepip is on 
my system at //usr/lib/python3.6/ensurepip.


Regards,  Jim

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


Re: [Tutor] pip stopped working gives error

2018-05-04 Thread Jim

On 05/03/2018 03:48 PM, Mats Wichmann wrote:

On 05/03/2018 02:27 PM, Jim wrote:


I heard distutils may have been split out... see if you have a package
python3-distutils and if not installed, can you install it?


I have:

//usr/lib/python3.5/distutils
and
//usr/lib/python3.6/distutils, but no python3-distutils.

Checking in Synaptic there is no python3-distutils but there is a
python3-distutils-extra.


it was a guess... this change seems to have just happened in Ubuntu
(bionic/18.04 only), perhaps that's not the thing affecting you in Mint
(yet).

$ dpkg -l python3-distutils
Desired=Unknown/Install/Remove/Purge/Hold
|
Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name Version
ArchitectureDescription
+++--===-===-=
ii  python3-distutils3.6.5-3 all
 distutils package for Python 3.x
$ dpkg -L python3 | grep sysconfig
$ dpkg -L python3-distutils | grep sysconfig
/usr/lib/python3.6/distutils/sysconfig.py
/usr/lib/python3.7/distutils/sysconfig.py
$


I don't know if I missed it or a late update pulled it in but I just did 
sudo apt install python3-distutils and now my problem is fixed.


Thanks to you and Zachary for helping me out.

Regards,  Jim


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


[Tutor] Need help with a virtual environment mess

2018-05-06 Thread Jim
In a prior thread you guys helped me fix a problem with pip after I 
upgraded an installed version of python 3.6 on my Mint 18 system. Pip 
would not run in my python 3.6 virtual environment. The fix was to use 
synaptic to install python3-distutils. I thought everything was ok until 
I tried to run a old script from a different VE using python 3.5 which 
could not import tkinter.


I have 4 versions of python on this system:
system Python2 = 2.7.12 (default)
system Python3 = 3.5.2 (default)
a VE called env = 3.5.2
a Ve called env36 = 3.6.5

This is the error I get trying to import tkinter in env, I also get the 
same error if I try to import it in system python3.


jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate
(env) jfb@jims-mint18 ~ $ python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter as tk
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in 
import _tkinter
ImportError: No module named '_tkinter'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in 
raise ImportError(str(msg) + ', please install the python3-tk package')
ImportError: No module named '_tkinter', please install the python3-tk 
package

>>>

If I go to synaptic and install the python3-tk it installs version 3.6.5 
of the package and I can still not import tkinter in env with python 
3.5.2, but I can in env36 with python 3.6.5.


I don't know if it makes a difference but I installed python3.6 from
LP-PPA-jonathonf-python-3.6/now.

Thanks,  Jim


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


Re: [Tutor] Need help with a virtual environment mess

2018-05-07 Thread Jim

On 05/06/2018 05:16 PM, boB Stepp wrote:

On Sun, May 6, 2018 at 11:05 AM, Jim  wrote:

In a prior thread you guys helped me fix a problem with pip after I upgraded
an installed version of python 3.6 on my Mint 18 system. Pip would not run
in my python 3.6 virtual environment. The fix was to use synaptic to install
python3-distutils. I thought everything was ok until I tried to run a old
script from a different VE using python 3.5 which could not import tkinter.

I have 4 versions of python on this system:
system Python2 = 2.7.12 (default)
system Python3 = 3.5.2 (default)
a VE called env = 3.5.2
a Ve called env36 = 3.6.5

This is the error I get trying to import tkinter in env, I also get the same
error if I try to import it in system python3.

jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate
(env) jfb@jims-mint18 ~ $ python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.

import tkinter as tk

Traceback (most recent call last):
   File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in 
 import _tkinter
ImportError: No module named '_tkinter'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
   File "", line 1, in 
   File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in 
 raise ImportError(str(msg) + ', please install the python3-tk package')
ImportError: No module named '_tkinter', please install the python3-tk
package




If I go to synaptic and install the python3-tk it installs version 3.6.5 of
the package and I can still not import tkinter in env with python 3.5.2, but
I can in env36 with python 3.6.5.



As I have not yet tried to play around with virtual environments, I
may be about to do more harm than help, but I will plow ahead anyway!
~(:>))

My primitive understanding of installing Python versions that are
different from the system Python version into a virtual environment,
is that you have to install all dependencies you need from within that
virtual environment you created.  If I am correct about this then your
error messages suggest you need to install the tkinter stuff from
within that virtual environment using that virtual environment's pip.
Hopefully I am too far off from the truth here, but in any event, I
hope this helps you in your problem!



My understanding of VE's, based on some feedback from here, is you 
install install the python you want on the system then use it to install 
your VE. Then you install what ever you need to the VE. In my case I had 
a working VE based on python 3.5 then I received an upgrade to the 
python version 3.6 I had installed. After that I had problems with the 
3.5 VE that had been working.


Regards,  Jim

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


Re: [Tutor] Need help with a virtual environment mess

2018-05-07 Thread Jim

On 05/07/2018 12:02 PM, Mats Wichmann wrote:

On 05/07/2018 10:16 AM, Jim wrote:


My understanding of VE's, based on some feedback from here, is you
install install the python you want on the system then use it to install
your VE. Then you install what ever you need to the VE. In my case I had
a working VE based on python 3.5 then I received an upgrade to the
python version 3.6 I had installed. After that I had problems with the
3.5 VE that had been working.


yes, this happens.

the default behavior for virtualenv is to make links when creating the
VE, which saves copying things but is vulnerable to breakage if the
Python it's linking to receives major changes.  In the case of a
distribution upgrading the Python version, a VE constructed against the
old version will break if the links are version-specific.  Looking at
one virtualenv I have, {VEPATH}/lib/python3.6 is full of such symlinks,
e.g.:

lrwxrwxrwx.  1 mats mats26 Aug 17  2017 re.py ->
/usr/lib64/python3.6/re.py


Virtualenvs are cheap to recreate, so one approach is to just throw away
the old one and make a new one.


My problem is right now the default python3 for my system is also 
affected. If I type python3 I will see python version 3.5.2 and I cannot 
import tkinter there either.



you can also give virtualenv an option (--always-copy) to cause the
created virtualenv to be more self-contained, at a cost of some space
and tiem.

There are plenty of tools for managing python versions and virtualenv.
The python community changed directions a little bit recently, 'venv' is
now the recommended approach:

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


That is what I used to setup my VE's.


pyenv can manage different Python versions if you're interested in that.



I am going to see if I can find some log file that would give me a clue 
about what happened during the update.


Regards,  Jim


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


[Tutor] Virtual environment can't find uno

2018-06-13 Thread Jim

Running Linux Mint 18.

I have python 3.6 running in a virtual environment.

I want to use a package called oosheet to work with libreoffice calc.
When I try to import it I get the following error:

>>> import oosheet
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/home/jfb/EVs/env36/lib/python3.6/site-packages/oosheet/__init__.py", 
line 38, in 

import uno, re, zipfile, types, inspect, tempfile, shutil, subprocess
ModuleNotFoundError: No module named 'uno'

If I do the same thing in the system installed python3 it imports and 
runs with no errors.


python3-uno was installed using apt-get.

How do I get python 3.6 in the virtual environment to find uno?

Thanks,  Jim

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


Re: [Tutor] Virtual environment can't find uno

2018-06-14 Thread Jim

On 06/14/2018 10:51 AM, Mats Wichmann wrote:

On 06/13/2018 06:55 PM, Jim wrote:

Running Linux Mint 18.

I have python 3.6 running in a virtual environment.

I want to use a package called oosheet to work with libreoffice calc.
When I try to import it I get the following error:


import oosheet

Traceback (most recent call last):
   File "", line 1, in 
   File
"/home/jfb/EVs/env36/lib/python3.6/site-packages/oosheet/__init__.py",
line 38, in 
     import uno, re, zipfile, types, inspect, tempfile, shutil, subprocess
ModuleNotFoundError: No module named 'uno'

If I do the same thing in the system installed python3 it imports and
runs with no errors.

python3-uno was installed using apt-get.

How do I get python 3.6 in the virtual environment to find uno?


You should be able to pip install uno in the virtualenv, which might be
best.  After all, once you're using a virtualenv, you've already started
down the road of picking depends from upstream, so why not :)




Is it available for a pip install? I looked on pypi and didn't see it.

It may be incompatible with 3.6. I was looking at the dependencies with 
synaptic and found. Depends Python3(>= 3.5~), Depends Python3(<= 3.6).


Anyway I had forgotten I have a virtual environment with 3.5 in it, so I 
tried that and it works.


Thanks,  Jim



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


Re: [Tutor] Using pip

2018-07-05 Thread Jim

On 07/05/2018 11:03 AM, Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] wrote:

I just downloaded Python to work on a project at work. I'm writing a pretty 
simple program for data collection for an experiment. In order to get the data, 
though I need to install PyVISA. The website for PyVISA says I can install the 
library using the line:
$ pip install -U pyvisa
When I type this line, I get a syntax error for using the $, and when I remove 
the $, I get a syntax error for using the word install. I even tried just using 
the word pip and an error said 'pip' is not defined. I'm not sure if I'm not 
using some syntax wrong, or if its a completely different issue.

Thanks for any help and insight
Matt Hlavin


It sounds like you are trying to install it from inside python. First 
make sure that pip is installed on your OS. Then install PyVISA from 
your commandline/terminal (which ever your OS provides). Also depending 
on which version of python you are using (2 or 3) you may have to type 
pip3 instead of just pip.


regards,  Jim


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


[Tutor] Need help combining elements of a list of lists

2018-07-10 Thread Jim
Say I have a list like ltrs and I want to print out all the possible 3 
letter combinations. I want to combine letters from each inner list but 
not combine any letters within the inner list itself. So ACF and ADF 
would be ok but ABC would not.


I can lay it out manually and see the pattern, I cannot figure out how 
to do it programically. Just in case this looks like homework it is not. 
It's a small test case I devised to try to figure it out so I can apply 
it to a bigger real world problem I am working on.


ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]

print(ltrs[0][0]+ltrs[1][0]+ltrs[2][0]) #ACF
print(ltrs[0][0]+ltrs[1][1]+ltrs[2][0]) #ADF
print(ltrs[0][0]+ltrs[1][2]+ltrs[2][0]) #AEF
print(ltrs[0][0]+ltrs[1][0]+ltrs[2][1]) #ACG
print(ltrs[0][0]+ltrs[1][1]+ltrs[2][1]) #ADG
print(ltrs[0][0]+ltrs[1][2]+ltrs[2][1]) #AEG
.
.
.
print(ltrs[0][1]+ltrs[1][2]+ltrs[2][3]) #BEI

thanks,  Jim

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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-11 Thread Jim

On 07/10/2018 10:09 PM, David Rock wrote:



On Jul 10, 2018, at 22:04, David Rock  wrote:


On Jul 10, 2018, at 21:46, Jim  wrote:

ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]


A fairly straightforward way is to use nested loops:


for l in ltrs[0]:

...   for j in ltrs[1]:
... for k in ltrs[2]:
...   print l,j,k



Sorry, let’s try to make that a little cleaner-looking

for x in ltrs[0]:
   for y in ltrs[1]:
 for z in ltrs[2]:
   print x,y,z



Seeing it in front of me it does look straight forward, I was having 
difficulty visualizing how to solve it.


thanks, Jim


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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-11 Thread Jim

On 07/10/2018 11:03 PM, Mats Wichmann wrote:

On 07/10/2018 09:09 PM, Steven D'Aprano wrote:

On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote:


Say I have a list like ltrs and I want to print out all the possible 3
letter combinations. I want to combine letters from each inner list but
not combine any letters within the inner list itself. So ACF and ADF
would be ok but ABC would not.

I can lay it out manually and see the pattern, I cannot figure out how
to do it programically. Just in case this looks like homework it is not.
It's a small test case I devised to try to figure it out so I can apply
it to a bigger real world problem I am working on.

ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]


If you know that there are just three sublists, then you can do this:

for a in ltrs[0]:
 for b in ltrs[1]:
 for c in ltrs[2]:
 print(a + b + c)

I trust that's easy enough to understand.

But here's a more general technique, where you don't need to know up
front how many nested lists there are:


from itertools import product  # short for "Cartesian Product"
for s in product(*ltrs):
 print(''.join(s))


This is one of those cases where: if it's homework, getting the nested
loops right is almost certainly the way to go.  If it isn't, then
itertools (that is, "using an available library solution") is almost
certainly the way to go :)

If the eventual case is not just "letters", and a list of combined lists
is the eventual goal, then the concise stanza is:

prods = list(product(*ltrs))

print(prods) then gives you:

[('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'c', 'h'), ('a', 'c', 'i'),
('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'),
('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'),
('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'c', 'h'), ('b', 'c', 'i'),
('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'),
('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i')]

if you want them concatenated, then of course join is the way to do that.





Steven & Mats thanks for your replies.

It is more that just letters. I was reading Al Sweigart's book Cracking 
Codes with Python. I got to the chapter on substitution cyphers and 
wondered if his program could solve the daily Crypto Quips in the 
newspaper. Turns out it did not do a very good job because the quips 
were to short.


It did produce a dictionary where the keys are the letters of the 
alphabet and the items are a list of possible letters to substitute. If 
a key has no possible letters it is ignored, if a key has only one 
possible letter it considered a solution and plugged into the cypher. 
the keys with multiple possible letters are ones I am interested in.


I know you cannot brute force a substitution cypher but maybe I could 
loop over and combine the possible substitution letters and crack it 
that way. That's why I made up the letter problem, I wanted to see how 
to do it on a simple data set before attempting much more complex one.


It looks like the library solution is the way for me to try.

Regards,  Jim





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


Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19

2018-07-14 Thread Jim

On 07/14/2018 06:42 PM, Alan Gauld via Tutor wrote:

On 14/07/18 22:51, boB Stepp wrote:


Linux Mint 19 comes with Python 3.6.5 pre-installed.  However, my son
and I are working on a couple of things together, and decided to use
the latest bugfix releases of Python 3.6 for them.  I would not think
that upgrading from 3.6.5 to 3.6.6 would break anything in my system


Probably not but do you really need that last dot release?
Do you know for sure there is anything in it that will affect
your code? If not I'd just stay on 3.6.5

Personally, although I have 3.6.5 installed, my default v3
is 3.5.4.

If you really need 3.6.6 then your best bet is to locate a
deb package that somebody has created, otherwise building
from source is about the only option.



Bob,

If you look you might find a PPA that has packaged it. I installed 
python 3.6.5 (no help to you) on Mint 18 from here: 
https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.6'.


Maybe you can find one that does 3.6.6 or ask Jonathon if he intends to 
package 3.6.6. Whatever you do I would suggest you install it in a 
virtual environment, especially if you are going to be experimenting 
with a lot of libraries. If you use a virtual environment you don't have 
to worry about breaking your system python.


regards,  Jim


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


[Tutor] How can I find a group of characters in a list of strings?

2018-07-25 Thread Jim

Linux mint 18 and python 3.6

I have a list of strings that contains slightly more than a million 
items. Each item is a string of 8 capital letters like so:


['MIBMMCCO', 'YOWHHOY', ...]

I need to check and see if the letters 'OFHCMLIP' are one of the items 
in the list but there is no way to tell in what order the letters will 
appear. So I can't just search for the string 'OFHCMLIP'. I just need to 
locate any strings that are made up of those letters no matter their order.


I suppose I could loop over the list and loop over each item using a 
bunch of if statements exiting the inner loop as soon as I find a letter 
is not in the string, but there must be a better way.


I'd appreciate hearing about a better way to attack this.

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 find a group of characters in a list of strings?

2018-07-25 Thread Jim

On 07/25/2018 07:43 PM, Steven D'Aprano wrote:

On Wed, Jul 25, 2018 at 06:50:56PM -0500, Jim wrote:
[...]

I need to check and see if the letters 'OFHCMLIP' are one of the items
in the list but there is no way to tell in what order the letters will
appear. So I can't just search for the string 'OFHCMLIP'. I just need to
locate any strings that are made up of those letters no matter their order.


data = ['MIBMMCCO', 'YOWHHOY', 'ABCDEFG', 'HCMLIPOF', 'TUVWXYZ']

target = sorted('OFHCMLIP')
for pos, item in enumerate(data):
 if sorted(item) == target:
 print("found", pos, item)
 break


Stephen,

Perfect, thank you.  I did remove the break because I thought I would 
get more than one hit. I got 196, more that I hoped for but now I have a 
better idea of what I am working with.


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 find a group of characters in a list of strings?

2018-07-25 Thread Jim

On 07/25/2018 07:29 PM, Martin A. Brown wrote:



I have a list of strings that contains slightly more than a
million items. Each item is a string of 8 capital letters like so:

['MIBMMCCO', 'YOWHHOY', ...]

I need to check and see if the letters 'OFHCMLIP' are one of the items in the
list but there is no way to tell in what order the letters will appear. So I
can't just search for the string 'OFHCMLIP'. I just need to locate any strings
that are made up of those letters no matter their order.

I suppose I could loop over the list and loop over each item using a bunch of
if statements exiting the inner loop as soon as I find a letter is not in the
string, but there must be a better way.

I'd appreciate hearing about a better way to attack this.

thanks,  Jim


If I only had to do this once, over only a million items (given
today's CPU power), so I'd probably do something like the below
using sets.  I couldn't tell from your text whether you wanted to
see all of the entries in 'OFHCMLIP' in each entry or if you wanted
to see only that some subset were present.  So, here's a script that
will produce a partial match and exact match.

Note, I made a 9-character string, too because you had a 7-character
string as your second sample -- mostly to point out that the
9-character string satisfies an exact match although it sports an
extra character.


Sorry, that was a typo, they are all 8 characters in length.


   farm = ['MIBMMCCO', 'YOWHHOY', 'OFHCMLIP', 'OFHCMLIPZ', 'FHCMLIP', 
'NEGBQJKR']
   needle = set('OFHCMLIP')
   for haystack in farm:
   partial = needle.intersection(haystack)
   exact = needle.intersection(haystack) == needle
   print(haystack, exact, ''.join(sorted(partial)))

On the other hand, there are probably lots of papers on how to do
this much more efficiently.

-Martin


Thanks for your help. Steven came up with a solution that works well for me.

Regards,  Jim


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


[Tutor] No module named uno in virtual environment

2018-09-07 Thread Jim

Mint 18.1
System python3 3.5.2

Python3-uno is available to the system python3. How can I make it 
available to python 3.6.5 in a virtual environment I installed using venv?




(env36) jfb@jims-mint18 ~ $ python
Python 3.6.5 (default, May  3 2018, 10:08:28)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import oosheet
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/home/jfb/EVs/env36/lib/python3.6/site-packages/oosheet/__init__.py", 
line 38, in 

import uno, re, zipfile, types, inspect, tempfile, shutil, subprocess
ModuleNotFoundError: No module named 'uno'

Thanks,  Jim

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


Re: [Tutor] No module named uno in virtual environment

2018-09-08 Thread Jim

On 09/08/2018 05:26 PM, Mats Wichmann wrote:

On 09/07/2018 03:10 PM, Jim wrote:

Mint 18.1
System python3 3.5.2

Python3-uno is available to the system python3. How can I make it
available to python 3.6.5 in a virtual environment I installed using venv?


with your virtualenv activated, just install it.

python -m pip install uno



My bad, I did not explain what python3-uno does. It is a system package 
that lets python interact with libreoffice. The uno that pip installs is 
a html generator.


I used apt to install python3-uno on my system. System python3 can use 
it and the python 3.5 in one of my virtual environments can use it. 
Python 3.6 in my other virtual environment cannot access it.


So to re-phrase my question. Python3-uno is installed on my system what 
do I need to do to get python 3.6 in a virtual environment to use it?


Maybe I am missing something obvious. With all the advice given to use 
virtual environments I would think that this problem has come up, but 
googling did not produce a solution.


Regards,  Jim

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


Re: [Tutor] No module named uno in virtual environment

2018-09-09 Thread Jim

On 09/08/2018 08:35 PM, Mats Wichmann wrote:

On September 8, 2018 5:46:46 PM MDT, Jim  wrote:

On 09/08/2018 05:26 PM, Mats Wichmann wrote:

On 09/07/2018 03:10 PM, Jim wrote:

Mint 18.1
System python3 3.5.2

Python3-uno is available to the system python3. How can I make it
available to python 3.6.5 in a virtual environment I installed using

venv?


with your virtualenv activated, just install it.

python -m pip install uno



My bad, I did not explain what python3-uno does. It is a system package

that lets python interact with libreoffice. The uno that pip installs
is
a html generator.

I used apt to install python3-uno on my system. System python3 can use
it and the python 3.5 in one of my virtual environments can use it.
Python 3.6 in my other virtual environment cannot access it.

So to re-phrase my question. Python3-uno is installed on my system what

do I need to do to get python 3.6 in a virtual environment to use it?

Maybe I am missing something obvious. With all the advice given to use
virtual environments I would think that this problem has come up, but
googling did not produce a solution.

Regards,  Jim
python




ok, awkward naming issue. try openoffice-python instead?



Unfortunately it produces the same result, no module uno found. I think 
all of the packages on pipy need the uno module to be installed to function.


When I installed python3-uno using apt it was installed at 
/usr/lib/python3/dist-packages/uno.py. I have python 3.5 installed in a 
virtual environment and it can load the uno module.  I have python 3.6 
installed in virtual environment and it cannot load the uno module.


Ok, I think I have solved it. Looking at the site-packages folder in the 
3.5 virtual environment shows uno.py and unohelper.py. In the 3.6 
virtual environment they are missing. Simply putting a copy of them in 
the python3.6 site-packages folder allows me to import uno and run a 
program that depends on importing uno.


I don't know if they should have been put there when I installed the 3.6 
virtual environment or if I did something wrong when I installed it, but 
now it works.


Mats, thanks for all your help.

Regards,  Jim



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


Re: [Tutor] No module named uno in virtual environment

2018-09-09 Thread Jim

On 09/09/2018 01:29 PM, Mats Wichmann wrote:

On 09/09/2018 10:49 AM, Jim wrote:


ok, awkward naming issue. try openoffice-python instead?



Unfortunately it produces the same result, no module uno found. I think
all of the packages on pipy need the uno module to be installed to
function.

When I installed python3-uno using apt it was installed at
/usr/lib/python3/dist-packages/uno.py. I have python 3.5 installed in a
virtual environment and it can load the uno module.  I have python 3.6
installed in virtual environment and it cannot load the uno module.

Ok, I think I have solved it. Looking at the site-packages folder in the
3.5 virtual environment shows uno.py and unohelper.py. In the 3.6
virtual environment they are missing. Simply putting a copy of them in
the python3.6 site-packages folder allows me to import uno and run a
program that depends on importing uno.

I don't know if they should have been put there when I installed the 3.6
virtual environment or if I did something wrong when I installed it, but
now it works.

Mats, thanks for all your help.


Glad it works, but you've left me curious now.  On a Fedora system these
two files come from libreoffice-pyuno:

/usr/lib64/python3.6/site-packages/uno.py
/usr/lib64/python3.6/site-packages/unohelper.py

and I don't presently see any way they are going to make it into a
virtualenv that is *not* set up to grab the system site-packages (that
is, created with the --system-site-packages option), I'm not finding
anything in PyPi that looks like it can provide this. The package I
mentioned above certainly doesn't.

uno.py imports the binary (shared object) pyuno module, which is fine,
that one is located wherever the {open,libre}office install puts it - on
my system just before the import it has done:

   sys.path.append('/usr/lib64/libreoffice/program')

maybe your 3.5 virtualenv was created differently than your 3.6 one and
that's why you have it there?

meanwhile, this is looking to my untrained eye like a small hole.


I am puzzled also. My memory isn't what it used to be but I think I 
created them the same way. Looking at the config files I see.


home = /usr/bin
include-system-site-packages = false
version = 3.5.2

and

home = /usr/bin
include-system-site-packages = false
version = 3.6.3

I don't know if it makes a difference or not, but python3.5 is the 
system default python3 and python3.6 was installed from 
LP-PPA-jonathonf-python-3.6/now and LP_PPA-jonathonf-python-3.6/xenial. 
Maybe the install script malfunctioned or was lacking some step. I may 
email jonathon to see if he has any ideas.


Regards,  Jim



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


[Tutor] Python 3.6 update?

2018-10-25 Thread Jim

Mint 18.1
Default python3 = 3.5
Python 3.6 installed for use by a virtual environment.



Update manager just informed me of an update for python 3.6 to 3.6.7-1. 
When I started to install it, I got a dialog saying:


this upgrade will trigger additional changes. The following 2 packages 
will be removed  python3-dev & python3-venv.


I am wondering what will happen to the virtual environment I have 
installed that uses python 3.6. Will the 2 packages be replaced and the 
virtual environment continue to work or is there some other steps I will 
need to take.


Regards,  Jim

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


Re: [Tutor] Python 3.6 update?

2018-10-27 Thread Jim

On 10/25/18 5:30 PM, Mats Wichmann wrote:

On 10/25/2018 03:07 PM, Jim wrote:

Mint 18.1
Default python3 = 3.5
Python 3.6 installed for use by a virtual environment.



Update manager just informed me of an update for python 3.6 to 3.6.7-1.
When I started to install it, I got a dialog saying:

this upgrade will trigger additional changes. The following 2 packages
will be removed  python3-dev & python3-venv.

I am wondering what will happen to the virtual environment I have
installed that uses python 3.6. Will the 2 packages be replaced and the
virtual environment continue to work or is there some other steps I will
need to take.

Regards,  Jim


we can't tell that from here.

Not sure whose bright idea it was to package venv separately, since it's
supposed to be a "standard" part of Python 3 since 3.3 (I guess it's
"batteries included, but you still have to install the batteries" :).
But removing the package doesn't affect a created virtual environment.

What can affect a created virtual environment is how it was created -
there are a few options, some combinations of which could leave things
going missing from underneath if the Python it's created from is
upgraded.  venv has an upgrade option that might help with that.

Mint forums (and probably Ubuntu forums) could be further help...
usually somebody's been through it before.


Asked on ubuntu forumn.



thanks,  Jim


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


[Tutor] Consequences of removing python3-venv

2019-05-09 Thread Jim
My Linux mint18 system recently wanted to up date python 3.6. When I 
clicked install I got the following message:


The following 2 packages will be removed:
python3-dev
python3-venv

I have 2 virtual environments installed: python 3.5.2 & 3.6.7.

Listing the various pythons I have installed shows:

jfb@jims-mint18 ~ $ ls -ls /usr/bin/python*
   0 lrwxrwxrwx 1 root root   9 Nov 23  2017 /usr/bin/python -> 
python2.7
   0 lrwxrwxrwx 1 root root   9 Nov 23  2017 /usr/bin/python2 -> 
python2.7

3412 -rwxr-xr-x 1 root root 3492656 Nov 12 13:46 /usr/bin/python2.7
   0 lrwxrwxrwx 1 root root   9 Jan  9  2017 /usr/bin/python3 -> 
python3.5

4360 -rwxr-xr-x 2 root root 4464368 Nov 12 10:27 /usr/bin/python3.5
   0 lrwxrwxrwx 1 root root  33 Nov 12 10:27 
/usr/bin/python3.5-config -> x86_64-linux-gnu-python3.5-config

4360 -rwxr-xr-x 2 root root 4464368 Nov 12 10:27 /usr/bin/python3.5m
   0 lrwxrwxrwx 1 root root  34 Nov 12 10:27 
/usr/bin/python3.5m-config -> x86_64-linux-gnu-python3.5m-config

4500 -rwxr-xr-x 2 root root 4604416 Oct 25  2018 /usr/bin/python3.6
   0 lrwxrwxrwx 1 root root  33 Oct 25  2018 
/usr/bin/python3.6-config -> x86_64-linux-gnu-python3.6-config

4500 -rwxr-xr-x 2 root root 4604416 Oct 25  2018 /usr/bin/python3.6m
   0 lrwxrwxrwx 1 root root  34 Oct 25  2018 
/usr/bin/python3.6m-config -> x86_64-linux-gnu-python3.6m-config
   0 lrwxrwxrwx 1 root root  16 Mar 23  2016 
/usr/bin/python3-config -> python3.5-config
   0 lrwxrwxrwx 1 root root  10 Jan  9  2017 /usr/bin/python3m -> 
python3.5m
   0 lrwxrwxrwx 1 root root  17 Mar 23  2016 
/usr/bin/python3m-config -> python3.5m-config


So will allowing the update harm my virtual environments?

I really don't want to reinstall them.

thanks,  Jim

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


[Tutor] Impersonation

2019-07-15 Thread Jim

Mats,

Hopefully you recognize my email address as someone you have given 
advice concerning Python.


Over the last month or so I have received at least 3 emails supposedly 
coming from you that I am sure you did not send.


The from line is:  Mats Wichmann 

The body is: On Monday, July 15, 2019 10:36 AM, Mats Wichmann wrote:
Hope you are well. Just wanted to share something with you 
http://www.bt6q.lnhaxf.info/


I just wanted you to know that it seems someone is trying to impersonate 
you.


Regards,  Jim

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


Re: [Tutor] Impersonation

2019-07-16 Thread Jim

On 7/15/19 9:36 PM, Jim wrote:

Mats,

Hopefully you recognize my email address as someone you have given 
advice concerning Python.


Over the last month or so I have received at least 3 emails supposedly 
coming from you that I am sure you did not send.


The from line is:  Mats Wichmann 

The body is: On Monday, July 15, 2019 10:36 AM, Mats Wichmann wrote:
Hope you are well. Just wanted to share something with you 
http://www.bt6q.lnhaxf.info/


I just wanted you to know that it seems someone is trying to impersonate 
you.


Regards,  Jim



My apologies. I intended that this message go only to Mats.

Regards, Jim


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


[Tutor] Union

2019-08-12 Thread Jim
I was reading the docs for PySimpbleGUI here: 
https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows


In the table of parameters for the Window() function for example the 
icon parameter the meaning is  Union[str, str] Can be either a filename 
or Base64 value.


What is the usage of "Union". I don't recall seeing anything like it before.

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


Re: [Tutor] Union

2019-08-12 Thread Jim

On 8/12/19 4:12 PM, Mats Wichmann wrote:

On 8/12/19 2:50 PM, Jim wrote:

I was reading the docs for PySimpbleGUI here:
https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows

In the table of parameters for the Window() function for example the
icon parameter the meaning is  Union[str, str] Can be either a filename
or Base64 value.

What is the usage of "Union". I don't recall seeing anything like it
before.


it's type annotation. Search here:

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



OK, thanks.

Jim

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


[Tutor] Problem creating a search

2010-01-30 Thread jim serson

Hi I am pretty new to python and programming in general. I am trying to create 
a search that takes a user input for a file location and user input to find a 
group of numbers or a phrase in that file count how many times it appears then 
display it.
I have gone through a tutorials and searched I/O to find the code I need. 
Although I have not been able to make it work properly yet.
 

I am able to open and read from the file the user would input but cant seem to 
make the other input retrieve the numbers or phrase from the file or have it 
count how many time it appears. If anyone can help or point me in the right 
direction I would appreciate it. Thanks for your time.

 

look_in = raw_input ("Enter the search file to look in ")
search = raw_input ("Enter your search item ")
count = 0

file = open(look_in, "r")
line = file.readline()
while line:
print line
line = file.readline()
search == line
if search in line:  

search = count + 1
print count
print search, "your search was found"
else:
print ("your search was not found")
file.close()
  
_

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


[Tutor] Shashwat Anand you helped with search

2010-02-02 Thread jim serson

I am trying to have the search return several numbers or words in a single 
sentences now. I don't know if I am using the wrong format I am trying to use 
the split method because I thought I could return several parts of a sentence 
with it. 
For example if it had 1 2 3 4 5 I thought I could search and return 1 3 5 or if 
it had “to set the function” I could return
 “set function” from that line, but I can’t get it working properly. 
 
I have tried several different approaches with split. I have tried to split it 
at the raw_input() line, at the if statement, putting it in a loop and 
declaring it separately. I have looked up, in the python library to make sure I 
am entering it properly. It will ether run trough and not work like I expect or 
it will come up with an error. 
 
I think I am using the right method in the wrong way. If you could tell me if I 
am trying the correct method or give me a push in the right direction that 
would be grate thanks.
 
look_in = raw_input ("Enter the search file to look in ")
search = raw_input ("Enter your search item ")
 
c = open(look_in, "r").read().count(search.split()
if c:   print search, ",", c,"Of your search was found"
else:   print "Your search was not found"
  
_

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


[Tutor] running split and count + looping to check for numbers in same line

2010-02-10 Thread jim serson

I am getting an error when I try and run split and count I seem to get it to 
work with one or the other but not together. python wants a character buffer 
but I am not sure how to use it. 

 

I would also like to use readline to check and see if several numbers are in 
the same line but I think I will need to use it in a loop maybe for? So it 
would check for the first then check for the second if both are true add to 
count but if ether are false continue to next line and repeat.

 

If anyone can help me that would be grate.
Thanks

 

look_in = "keno_back_up.txt"#raw_input ("Enter the search file to look in ")
search = raw_input ("Enter your search item ").split

file = open(look_in, "r").read().count(search)

print "Your search came",file ,"times"


Traceback (most recent call last):
  File "C:\Python26\keno program\get rid of 4", line 4, in 
file = open(look_in, "r").read().count(search)
TypeError: expected a character buffer object
  
_

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


Re: [Tutor] running split and count + looping to check for numbers in same line

2010-02-10 Thread jim serson

Thanks for the information
 
> Date: Wed, 10 Feb 2010 21:50:53 -0500
> Subject: Re: [Tutor] running split and count + looping to check for numbers 
> in same line
> From: ken...@tds.net
> To: fubarni...@hotmail.com
> CC: tutor@python.org
> 
> On Wed, Feb 10, 2010 at 6:43 PM, jim serson  wrote:
> > I am getting an error when I try and run split and count I seem to get it to
> > work with one or the other but not together. python wants a character buffer
> > but I am not sure how to use it.
> >
> > I would also like to use readline to check and see if several numbers are in
> > the same line but I think I will need to use it in a loop maybe for? So it
> > would check for the first then check for the second if both are true add to
> > count but if ether are false continue to next line and repeat.
> >
> > If anyone can help me that would be grate.
> > Thanks
> >
> > look_in = "keno_back_up.txt"#raw_input ("Enter the search file to look in ")
> > search = raw_input ("Enter your search item ").split
> 
> Here search is actually a function because you left out the
> parentheses after split(). But with them, search would be a list. The
> argument to count() must be a string.
> > file = open(look_in, "r").read().count(search)
> > print "Your search came",file ,"times"
> 
> Do you want a count per line or for the whole file? For the whole file
> you could do something like
> 
> search_terms = raw_input ("Enter your search item ").split() # Note
> the final ()
> data = open(look_in).read()
> count = 0
> for term in search_terms:
> count += data.count(term)
> 
> The last three lines could also be written as
> count = sum(data.count(term) for term in search_terms)
> 
> Kent
  
_
Check your Hotmail from your phone.
http://go.microsoft.com/?linkid=9708121___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using and

2010-02-21 Thread jim serson

Can anyone tell me if I can have my program check to see if something is true 
the add to count
For example something like
if c_1 and c_2 and c_3 true:
count + 1

 

or if I can use it after splitting an input the problem is the input is 
variable so I don't know if I can do such a thing without knowing the input 
ahead of time. if anyone can tell me if this is possible or if I should be 
doing something else that would be grate thanks.
  
_
Introducing Windows® phone.
http://go.microsoft.com/?linkid=9708122___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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] Re: Tutor Digest, Vol 11, Issue 30

2005-01-09 Thread Jim Kelly
This script did not run properly


jk
nj
--- [EMAIL PROTECTED] wrote:

> Send Tutor mailing list submissions to
>   tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
>   http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
>   [EMAIL PROTECTED]
> 
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>1. Re: Crossword program (Alan Gauld)
> 
> 
>
--
> 
> Message: 1
> Date: Sun, 9 Jan 2005 22:07:31 -
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Crossword program
> To: "David Holland" <[EMAIL PROTECTED]>,
> 
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hi David,
> 
> Its probably the kind of thing you could put on the
> Useless Python website. Useless is a collection of
> not-too-serious software written in Python which,
> despite the name, is actually quite useful for
> beginners
> to download and look at and learn. They can try
> improving it, or using the ideas for their own
> programs.
> 
> But you might well get some suggestions on tidying
> it up a little first...
> 
> Alan G.
> 
> - Original Message - 
> From: "David Holland" <[EMAIL PROTECTED]>
> To: 
> Sent: Sunday, January 09, 2005 9:44 PM
> Subject: [Tutor] Crossword program
> 
> 
> > I wrote a program to create crosswords in python.
> > It is not perfect but it works, is there any open
> > source place I can put this for it to be used by
> > anyone who wants it ?  (Subject to the gpl
> licence).
> > Here is the code in case anyone is interested.
> >
> > from Tkinter import *
> > #Crossword program David Holland
> > class Crossword(Frame):
> >
> > def __init__(self, master):
> > '''Default arguments'''
> > Frame.__init__(self, master)
> > self.grid()
> > self.create_widgets()
> > NUM_SQUARES = 169
> > EMPTY = " "
> > global questionanswer
> > questionanswer = {}
> > global dictshort
> > dictshort = {}
> >
> > def readdict(self):
> > #get the dictionary from a file
> > try:
> > pickle_file = open(dictfile, "rb")
> > dictread = cPickle.load(pickle_file)
> > except:
> > dictread = {}
> > return dictread
> >
> > def writedict(self, dictent):
> > #write dictionary to file
> > pickle_file = open(dictfile, "wb")
> > cPickle.dump(dictent, pickle_file)
> > pickle_file.close()
> >
> > def showclues(self):
> > #show clues on the screen
> > questionanswer = self.readdict()
> > textent = self.showinfo(questionanswer)
> > #textent = questionanswer
> > self.putinfo(textent)
> >
> > def showinfo(self, dictent):
> > #make the clues look readable
> > i = 0
> > listkeys = dictent.keys()
> > #listkeys = listkeys.sort()
> > textdisp = ''
> > for item in listkeys:
> > i = i+1
> > istr = str(i) + " "
> > question = dictent[item]
> > textdisp = textdisp + istr + " the
> > question is " + question + " the answer is " +
> item +
> > "\n"
> > return textdisp
> >
> > def newcrosswordboard(self):
> > #create a crossword board
> > board = []
> > for square in range (NUM_SQUARES):
> > board.append(EMPTY)
> > return board
> >
> > #def newcrosswordboard(self):
> > ##this is create a board with the numbers
> > #board = []
> > #for square in range (NUM_SQUARES):
> > #text = str(square)
> > #board.append(text)
> > #return board
> >
> > def deleteclue(self):
> > #delete a clue
> > try:
> > numberentered = self.delete_ent.get()
> > dictent = self.readdict()
> > numberentered = int(numberentered)
> > listkeys = dictent.keys()
> > i = 1
> > clue = ''
> > for item in listkeys:
> > if numberentered == i:
> > del dictent[item]
> > clue = item
> > break
> > i = i +1
> > text = "Clue " + clue + " has been
> removed
> > the list of clues now is :-" + "\n"
> > self.writedict(dictent)
> > moretext = self.showinfo(dictent)
> > text = text + moretext
> > except:
> > text = "Please enter a number as a
> figure"
> > self.putinfo(text)
> >
> > def create_widgets(self):
> > #create GUI
> > self.question_lbl = Label(self, text =
> "Enter
> > the question ")
> >

[Tutor] Re: Tutor Digest, Vol 11, Issue 29

2005-01-09 Thread Jim Kelly
i had the same probblem with xp.

on mac os x i can double click on the file and it will
open.


xp opens the python file and closes it immediately
apon double click


open the python file via the Start Menu in xp.


Then hit f5 and the script will run


jk
nj
--- [EMAIL PROTECTED] wrote:

> Send Tutor mailing list submissions to
>   tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
>   http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
>   [EMAIL PROTECTED]
> 
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>1. Re: (no subject) (Alan Gauld)
>2. Crossword program (David Holland)
> 
> 
>
--
> 
> Message: 1
> Date: Sun, 9 Jan 2005 15:33:28 -
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] (no subject)
> To: "Jeffrey Thomas Peery" <[EMAIL PROTECTED]>,
> 
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> 
> > Hello I can't seem to get the IDLE to start up in
> my windows XP by
> clicking
> > ...
> > Also I can't seem to get xp to recognize .py files
> belonging to
> python.
> 
> This is all fixable but it suggests maybe other
> problems in the
> installation. Personally I'd recommend reinstalling
> Python
> and that should fix all the problems.
> 
> Alan G.
> 
> 
> 
> --
> 
> Message: 2
> Date: Sun, 9 Jan 2005 21:44:03 + (GMT)
> From: David Holland <[EMAIL PROTECTED]>
> Subject: [Tutor] Crossword program
> To: tutor@python.org
> Message-ID:
>
<[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=iso-8859-1
> 
> I wrote a program to create crosswords in python.
> It is not perfect but it works, is there any open
> source place I can put this for it to be used by
> anyone who wants it ?  (Subject to the gpl licence).
> Here is the code in case anyone is interested.
> 
> from Tkinter import *
> #Crossword program David Holland
> class Crossword(Frame):
> 
> def __init__(self, master):
> '''Default arguments'''
> Frame.__init__(self, master)
> self.grid()
> self.create_widgets()
> NUM_SQUARES = 169
> EMPTY = " "
> global questionanswer
> questionanswer = {}
> global dictshort
> dictshort = {}
> 
> def readdict(self):
> #get the dictionary from a file
> try:
> pickle_file = open(dictfile, "rb")
> dictread = cPickle.load(pickle_file)
> except:
> dictread = {}
> return dictread
> 
> def writedict(self, dictent):
> #write dictionary to file
> pickle_file = open(dictfile, "wb")
> cPickle.dump(dictent, pickle_file)
> pickle_file.close()
> 
> def showclues(self):
> #show clues on the screen
> questionanswer = self.readdict()
> textent = self.showinfo(questionanswer)
> #textent = questionanswer
> self.putinfo(textent)
> 
> def showinfo(self, dictent):
> #make the clues look readable
> i = 0
> listkeys = dictent.keys()
> #listkeys = listkeys.sort()
> textdisp = ''
> for item in listkeys:
> i = i+1
> istr = str(i) + " "
> question = dictent[item]
> textdisp = textdisp + istr + " the
> question is " + question + " the answer is " + item
> +
> "\n"
> return textdisp
> 
> def newcrosswordboard(self):
> #create a crossword board
> board = []
> for square in range (NUM_SQUARES):
> board.append(EMPTY)
> return board
> 
> #def newcrosswordboard(self):
> ##this is create a board with the numbers
> #board = []
> #for square in range (NUM_SQUARES):
> #text = str(square)
> #board.append(text)
> #return board
> 
> def deleteclue(self):
> #delete a clue
> try:
> numberentered = self.delete_ent.get()
> dictent = self.readdict()
> numberentered = int(numberentered)
> listkeys = dictent.keys()
> i = 1
> clue = ''
> for item in listkeys:
> if numberentered == i:
> del dictent[item]
> clue = item
> break
> i = i +1
> text = "Clue " + clue + " has been
> removed
> the list of clues now is :-" + "\n"
> self.writedict(dictent)
> moretext = self.showinfo(dictent)
> text = text + moretext
> except:
> text = "Please enter a number as a
> figure"
> self.putinfo(text)
> 
>   

[Tutor] Can't figure out AttributeError message

2005-07-07 Thread Jim Roush
I'm getting the following error message:

  AttributeError: 'tuple' object has no attribute 'seek'

below is the code that produced the error.  The line in question is 
marked with arrow in the left margin.  Any help would be appreciated. 

def build_sp500_rand():
sp500_csv = open('c:/indices/sp500.csv', 'r')
sp500_csv_recs = sp500_csv.readlines()
sp500_csv.close()
   
sp_rand = ('c:/indices/sp500.rnd', 'w+b')
record_size  = struct.calcsize('Lf')

record_number = 0
for rec in sp500_csv_recs:
rec.strip('\n')
sp500_csv_fields = rec.split(',')
   
   
sp500_csv_date = sp500_csv_fields[0]
sp500_csv_open = sp500_csv_fields[1]
sp500_csv_high = sp500_csv_fields[2]
sp500_csv_low = sp500_csv_fields[3]
sp500_csv_close = sp500_csv_fields[4]
sp500_csv_volume = sp500_csv_fields[5]
   
print 'build:', sp500_csv_date
   
buffer = struct.pack('Lf', long(sp500_csv_date), 
float(sp500_csv_close))
>   sp_rand.seek(record_number * record_size)
sp_rand.write(buffer)
   
record_number = record_number + 1
   
sp_rand.close()




-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.8.10/43 - Release Date: 7/6/2005

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python fast enough for ad server?

2007-05-09 Thread jim stockford

there's also the question of the delivery architecture:
if there are multiple machines in a clustered
configuration, even something such as DNS round
robin, then improving performance is a matter of
throwing machines at the front end.

On May 9, 2007, at 1:17 PM, Alan Gauld wrote:

>
> "OkaMthembo" <[EMAIL PROTECTED]> wrote
>
>> I need to write an ad-serving application and i'm
>> using Win XP as my dev platform.
>
> The real issue is what are you using for your deployment
> platform,. If its Win XP then Python is probably fast
> enough since XP cannot handle huge volumes anyway.
> If its enterprise scale Windows or some other OS then
> there are other questions to ask.
>
>> i wonder if Python would have the performance or
>> scale fast enough to a large user base.
>
> Define large. Its not normally the number of users
> that matters but thenumber of concurrent users.
> Google has probably 10's of millions of users
> but less than a million at any one time. Are we
> talking google sizes?
>
>> Python and Java, but Jython only supports Python 2.2
>
> Jython will not be significantly faster than Python.
> And unless you have a good optimising/JIT compiler
> neither will Java IMHO.
>
> But Python 2.2 would be adequate to write a server
> anyhow so you just lose a few of the latest bells
> and whistles, no big loss. Given the choice between
> Python 2.2. and Java 5 I know which I'd prefer...
>
> Alan G.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Inherit from int?

2007-05-12 Thread jim stockford

the problem is in the return.

if you append a print statement to the class function
such as
print "number is ",number   # (properly indented, of course)
you'll get 8



On May 12, 2007, at 5:11 PM, John Fouhy wrote:

> On 13/05/07, Marilyn Davis <[EMAIL PROTECTED]> wrote:
>> #!/usr/bin/env python
>> '''An Under10 class, just to fiddle with inheriting from int.'''
>>
>> class Under10(int):
>>
>> def __init__(self, number):
>> number %= 10
>> int.__init__(self, number)
>
> Subclassing int and other types is a bit special.  Check out this
> page; it may help you:
> http://www.python.org/download/releases/2.2.3/descrintro/#__new__
>
> --
> John.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gmail

2007-05-29 Thread jim stockford

i'd be curious to see what happens if you
use the  tag around your (properly)
indented code, e.g.


this = 1
that = 0
if this == 1 :
that = 1
print that




On May 29, 2007, at 9:24 AM, Adam Urbas wrote:

> Hey,
>
> I have gmail now, but I'm not sure how to turn off HTML.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Promps

2007-06-03 Thread jim stockford

sounds like threading is a solution.

On Jun 3, 2007, at 2:05 PM, Jason Coggins wrote:

> I am using Linux and yes I am wanting the program to run another 
> program.  I
> have tried these before but, if I remember correctly, these methods 
> caused
> the original program to "freeze" while waiting on the "spawned" 
> program to
> return a value (usually either true or false).  I am planning on 
> having the
> program start another program and then exit the original program after 
> the
> second program is started but before the second program ends.  I will 
> take
> another look at these to see if I can work around the "freezing" 
> problem
> because I have a little more experience then when I tried it the first 
> time.
>
> I used the reply button to send a reply to the first message.  I did 
> not
> realize it would send the reply directly to you instead of the list.  
> I have
> tried to send this reply to the list.
>
> Thanks,
>
> Jason
>
> - Original Message -
> From: "Bob Gailer" <[EMAIL PROTECTED]>
> To: "Jason Coggins" <[EMAIL PROTECTED]>
> Cc: 
> Sent: Sunday, June 03, 2007 4:24 PM
> Subject: Re: [Tutor] Command Line Promps
>
>
>> Please always reply to the list, not just me. We are all working on 
>> these
>> questions and we all learn from them.
>>
>> Jason Coggins wrote:
>>> These seem to be ways of getting imput from the user.  I do not want 
>>> to
>>> send a command line to the user (for example, in the form of a 
>>> question)
>>> and get the users input.
>>>
>>> I want the Python program to open a terminal (if need be) and send a
>>> command to the computer (through the terminal) that the program is
>>> running on.
>> I think what you really want is to have Python run another program. 
>> True?
>>
>> (Not that it matters a lot but which OS are you running?)
>>
>> See os.system() and os.popen()
>>>
>>> Sorry if I was not more clear on this earlier,
>> Well it is often hard to be clear, but it sure saves time and energy.
>>
>> -- 
>> Bob Gailer
>> 510-978-4454
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Key Error

2007-07-08 Thread jim stockford

On Jul 8, 2007, at 9:45 AM, Alan Gauld wrote:

> (The tests at the end
> are poorly written too. If one of my team produced code like
> this I'd be having strong words with them!)

If you'd be willing to share your strong words, I'd
be grateful to learn better alternatives.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good writeup on Python assignment semantics

2007-07-17 Thread jim stockford

as I understand things...

there's a writeup somewhere that uses the term "bind" instead
of "assign" for the operation
a = b

for example, in Python
a = 1
the value 1 now has a name of a associated with it.
b = a
the value 1 now has two names, a and b, associated with it
the value 1 exists as an object independent of the storage
for the names a or b, which are bound to the integer object 1

in C
a = 1;
creates an integer-sized area in RAM, names it a, and puts
the value 1 in that area.
b = a;
copies the value in the area named a to a new, integer-sized
area named b

in either language (pseudocode below):
a = 1
print a
 a
b = 1
print b
 1
a = 2
print a
 2
print b
 1

I'm curious to know the practical value of knowing the
difference: where can one get tripped up in this case?


On Jul 17, 2007, at 7:38 AM, Kent Johnson wrote:

> Dick Moores wrote:
>> At 04:57 AM 7/17/2007, you wrote:
>>> A recent comp.lang.python thread has a good explanation of Python's
>>> assignment semantics:
>>> http://groups.google.com/group/comp.lang.python/browse_thread/ 
>>> thread/56e7d62bf66a435c/
>>
>>
>> Kent,
>>
>> Yes, interesting. But could you explain what you mean by "assignment
>> semantics"?  Semantics: <
>> http://dictionary.reference.com/search?q=semantics>
>> I have trouble relating semantics to programming.
>
> Semantics: The study or science of meaning in language.
>
> In other words, what does it mean to say
>a = b
> in Python?
>
> Syntax is like spelling and grammar rules - if you understand syntax,
> you can write a program that will compile and run. But without
> understanding what the various programming constructs actually mean,  
> you
> will have trouble writing a program that does something useful.
>
> I think to write correct programs in any language, you must have a
> correct mental model of what the program is doing, where by 'correct' I
> mean a model that is consistent with the actual behaviour of the  
> program.
>
> Programmers coming from a background in C and C++ have a mental model  
> of
> variables as containers for values. This model works in those  
> languages,
> where variables correspond to memory locations and assignment copies a
> value from one location to another. It doesn't work in Python, where
> variables are names for values and assignment creates another name for
> the same value without copying. To write correct Python programs you
> have to have a different model for what variables are and how they
> behave. We regularly see questions on this list from people who are
> confused by assignment because they are using a faulty model.
>
> So "what does it mean?" might be interpreted as "what is a useful model
> of this operation that allows me to understand and predict its
> behaviour?", and "assignment semantics" is a shortcut for saying "a
> useful model of assignment that allows me to understand and predict its
> behaviour."
>
> Kent
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] interpreter restarts

2007-07-17 Thread jim stockford



$ who am i
unohoo
$ which python
/usr/bin/python
$ python
Python 2.3.4 (#1, Mar 20 2006, 00:23:47)
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> print 1
1
 >>> help()

help> quit
 >>> 
$

$ vi doit.py

$ ls
doit.py
$ python doit.py

$


On Jul 17, 2007, at 8:14 AM, Eric Brunson wrote:

>
> Sara,
>
> Stick with ssh, IDE's are a crutch.  ;-)
>
> But that's just my opinion, others may differ.
>
> However, if you were running an X server on your local machine, you
> could use SSH to allow you to run GUI programs from your remote server.
> There are a couple of free X servers for Windoze, but running Linux on
> your local machine would give you the greatest success.  If you are
> interested in pursuing this, google up and install an X server, then
> post back.
>
> Sincerely,
> e.
>
> Sara Johnson wrote:
>> Luke, Jacob, et. al...
>>
>> Dumb question (may be slightly off course from what you two were
>> discussing), but are you both describing how to get the IDLE to run
>> along with the editor?  I may just be getting too many things
>> confused.  I've tried to run IDLE, but that's not working.  I have the
>> same function through opening it separately from the Start menu but
>> then it doesn't work as IDLE should work with the editor (or so I've
>> been told that happens).  I can type the word Python in my editor and
>> it comes up, but then the editor is gone.  I've gone so long with just
>> SSH, but at this point it's worth it if I find a way that makes
>> sense.  As someone mentioned from this list, at least it'll be code
>> that is easier to read for a newbie like myself.
>>
>> (Hope that didn't confuse or cause unnecessary headaches...)
>>
>> Sara
>>
>> - Original Message 
>> From: Luke Paireepinart <[EMAIL PROTECTED]>
>> To: Tiger12506 <[EMAIL PROTECTED]>
>> Cc: tutor@python.org
>> Sent: Monday, July 16, 2007 7:00:53 PM
>> Subject: Re: [Tutor] interpreter restarts
>>
>> Tiger12506 wrote:
 But there's an exception to that - if you right-click a file in  
 Windoze
 and 'edit' it,
 IDLE won't open up its subprocess, and as such, it can't restart the
 interpreter session because it's running in the same
 process as IDLE, and to restart the interpreter would mean  
 restarting
 IDLE.
 Boy, that 'edit with idle' thing sure does cause some problems,
>> don't it?
 :)
 -Luke

>>>
>>> Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE
>> open up its
>>> subprocess?
>>>
>>> This is the command that is in the registry concerning the Edit with
>> IDLE
>>> menu.
>>> "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e  
>>> "%1"
>>>
>>> This is the Target for the shortcut in the Start Menu (Note: the
>> Target box
>>> was disabled!)
>>> Python 2.5.1
>>>
>>> I thought that this was incredibly strange, so I opened this
>> shortcut in a
>>> hex editor to see what was different about this shortcut. (Normally,
>> they
>>> have a path in the target box)
>>>
>>> What I found surprised me. The title of the file in the hex editor  
>>> said
>>> "python_icon.exe"
>>> I started laughing maniacally and checked the full path of the file
>> from
>>> within the hex editor.
>>>
>> C:\windows\installer\{3184-6386-4999-a519 
>> -518f2d78d8f0}\python_icon.exe
>>>
>>> IDLE is started in two *very* different ways. So my next question
>> was: Can
>>> you pass arguments to this python_icon.exe? Simple navigations to  
>>> that
>>> directory and a confirmation... Yuck. You can't even execute it from
>>> explorer. A low-level ZwTerminateProcess function from ntdll is
>> called ...
>>> Let me try something...
>>>
>>> Woah... {3184-6386-4999-a519-518f2d78d8f0} appears in the
>> registry in
>>> alot of places. The Uninstall key for Add/Remove Programs, some
>> weird data
>>> thing... Okay, this is beyond me. I don't know the registry or
>> understand
>>> CLSIDs very well. Someone who knows Windows inside and out has done
>> a number
>>> with the python installer, or at least the msi installer does this  
>>> all
>>> automatically. Interesting. I wonder just how python_icon.exe starts
>> IDLE.
>>> If I could figure that out, I could emulate it with the Edit w/Idle
>> menu
>>> item and get IDLE to start a subprocess! But how any ideas?
>>>
>> It sounds like python_icon.exe is a fake executable that just contains
>> the icon for python programs...
>> hence the name.
>> You probably stumbled across the path to the icon to use, instead of  
>> the
>> path that is used when running the 'Edit with IDLE' thing.
>> Try this:
>> open an Explorer window, via Start Button -> Run -> explorer {ENTER}
>> or your favorite method.  Use the My Computer shortcut if you want,
>> either way.
>> Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu  
>> setting.
>> Go to the File Types tab, and scroll down till you find "PY"
>> click the Advanced button.
>> You should now see a dial

Re: [Tutor] IDLE Usage - was Interpreter Restarts

2007-07-17 Thread jim stockford

change "small" to "large" and you're right.
Vim is Vi improved.
Any tutorial or reference on Vi ought to work
for Vim.

On Jul 17, 2007, at 10:09 AM, Sara Johnson wrote:

> I initially thought Vim was sort of the same as Vi, just a few small 
> differences or upgrades.  Or have I got that confused?
>  
> Sara
>
> - Original Message 
> From: Tiger12506 <[EMAIL PROTECTED]>
> To: tutor@python.org
> Sent: Tuesday, July 17, 2007 12:33:54 PM
> Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts
>
> Yeah. But she's running Windows.
> Perhaps vim is scary to some Windows users.
> (I thought it was scary and annoying. Are all those ~ characters 
> really in
> the file or not?
> I kept second guessing the editor.)
>
> --Sara, could you give an example of how it doesn't work?
>   Just what happens? Just what doesn't happen?
>
> You say you have Python 2.3 installed...
>
>
> > Greetings,
> >
> > I use an editor called 'vim' on GNU/Linux.
> > I invoke vim on the command-line by typing: vi
> > (vi is a link to /usr/bin/vim)
> > In my home directory I have a vim config file
> > named .vimrc (that is: dot_vimrc [the dot makes it hidden]).
> > The .vimrc file has some things in it that do some nice stuff
> > for editing Python files; such as syntax highlighting, line numbers,
> > indenting, and also runs Python when I press the F2 function key.
> > I run vim in an X ternminal called Konsole. I can also run  it
> > from the command-line in any tty.
> >
> > Okay, here it is. Just copy/paste this into an editor, and save it 
> as:
> > .vimrc
> >
> > -8<--Cut Here>8---
> > " .vimrc
> > "
> > " Created by Jeff Elkner 23 January 2006
> > " Last modified 2 February 2006
> > "
> > " Turn on syntax highlighting and autoindenting
> > syntax enable
> > filetype indent on
> > " set autoindent width to 4 spaces (see
> > " http://www.vim.org/tips/tip.php?tip_id=83)
> > set nu
> > set et
> > set sw=4
> > set smarttab
> > " Bind  key to running the python interpreter on the currently 
> active
> > " file.  (curtesy of Steve Howell from email dated 1 Feb 2006).
> > map  :w\|!python %
> > -8<--Cut  Here>8---
> >
> > To use it, just type: vi myCode.py
> > (If you don't have a link named vi that points to /usr/bin/vim,
> > you'll have to type vim or /usr/bin/vim to get it going...
> > since I don't have any idea what you're working at, I can't say.)
> >
> > Once you're in vim, looking at your code, press F2 to run it.
> >
> > I understand that Emacs also does Python! =)
> > But I won't go there... I don't do Emacs.
> > --
> > bhaaluu at gmail dot com
> >
> > On 7/17/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
> >> A lot of Python programmers
> >> use Vi for writing their code.  do you have access to that through 
> SSH?
> >> I'm not quite sure what you mean by "SSH editor."
> >> -Luke
> >> ___
> >> Tutor [EMAIL PROTECTED]
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> > ___
> > Tutor [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> ___
> Tutor [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>
> Got a little couch potato?
>  Check out fun summer activities for 
> kids.___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IDLE Usage - was Interpreter Restarts

2007-07-17 Thread jim stockford

you want a very brief set of vi(m) commands--
a get-you-started tutorial that's nearly painless?
I'll send if "yes".
jim

On Jul 16, 2007, at 9:26 PM, Sara Johnson wrote:

> First off, yes, I was referring to (I guess you could say) a 
> non-python editor.  I use an SSH editor set up by my school.  If I 
> type python at the prompt in SSH, I get the Python shell.  My problem 
> is, I can't open a GUI no matter what I subscribe to or purchase.  I 
> have Python 2.3 and yes, I can access the commandline, but that does 
> not work the way it's been described to work.
>  
> If this still doesn't make any sense, just ignore me...
>  
> Sara
>
>
> >>Not quite what we were discussing, but I think you may have given 
> just
> enough clues that i can be of some help. Just for reference ~ which 
> editor
> are you using?
>
> IDLE is both an editor and a python shell or interpreter. It is not 
> the same
> thing as typing python.exe wherever you might be typing it.
>
> Typing Python into an editor should put the word "Python" into your
> currently open file. I don't believe that this is what you mean. 
> Perhaps you
> are confusing what exactly is an editor?
>
> You use Windows you've mentioned before. So here's what you can do. 
> Start ->
> Programs -> Python 2.5 -> Python (commandline)
>
> This is the python interpreter. As you might already know.
>
> And then this.
> Start -> Programs -> Python 2.5 -> IDLE (Python GUI)
>
> This is IDLE. As you probably know.
>
> Two windows should come up when you click IDLE. One is an editor. The 
> other
> is the python shell, or interpreter. You can open .py files in IDLE by 
> right
> clicking and selecting "Edit with IDLE". At any time that you wish to 
> run a
> program that is open in the editor half of IDLE, hit F5 and the Python 
> shell
> half of IDLE comes to the top and runs the program.
>
> If doing all that doesn't do what I expect it to do, or you have 
> something
> else in mind, reply back. If it does, then great!
>
> Oh. And tell me which editor you are using which magically opens a 
> python
> interpreter when you type Python into it. ;-)
>
> JS
>
> ___
> Tutor [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>
> Moody friends. Drama queens. Your life? Nope! - their life, your story.
> Play Sims Stories at Yahoo! 
> Games.___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IDLE Usage - was Interpreter Restarts

2007-07-19 Thread jim stockford

here's a link to the very brief vi get-started web page:
http://www.sf-lug.com/How2vi.html


On Jul 17, 2007, at 11:01 AM, Sara Johnson wrote:

> Sure, sounds good.  Should I assume that 'any' Unix version allows Vim?
>  
> Thanks,
> Sara
>
> ----- Original Message 
> From: jim stockford <[EMAIL PROTECTED]>
> To: Sara Johnson <[EMAIL PROTECTED]>
> Cc: tutor@python.org
> Sent: Tuesday, July 17, 2007 12:30:12 PM
> Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts
>
> you want a very brief set of vi(m) commands--
> a get-you-started tutorial that's nearly painless?
> I'll send if "yes".
> jim
>
> On Jul 16, 2007, at 9:26 PM, Sara Johnson wrote:
>
> > First off, yes, I was referring to (I guess you could say) a
> > non-python editor.  I use an SSH editor set up by my school.  If I
> > type python at the prompt in SSH, I get the Python shell.  My problem
> > is, I can't open a GUI no matter what I subscribe to or purchase.  I
> > have Python 2.3 and yes, I can access the commandline, but that does
> > not work the way it's been described to work.
> >  
> > If this still doesn't make any sense, just ignore me...
> >  
> > Sara
> >
> >
> > >>Not quite what we were discussing, but I think you may have given
> > just
> > enough clues that i can be of some help. Just for reference ~ which
> > editor
> > are you using?
> >
> > IDLE is both an editor and a python shell or interpreter. It is not
> > the same
> > thing as typing python.exe wherever you might be typing it.
> >
> > Typing Python into an editor should put the word "Python" into your
> > currently open file. I don't believe that this is what you mean.
> > Perhaps you
> > are confusing what exactly is an editor?
> >
> > You use Windows you've mentioned before. So here's what you can do.
> > Start ->
> > Programs -> Python 2.5 -> Python (commandline)
> >
> > This is the python interpreter. As you might already know.
> >
> > And then this.
> > Start -> Programs -> Python 2.5 -> IDLE (Python GUI)
> >
> > This is IDLE. As you probably know.
> >
> > Two windows should come up when you click IDLE. One is an editor. The
> > other
> > is the python shell, or interpreter. You can open .py files in IDLE 
> by
> >  right
> > clicking and selecting "Edit with IDLE". At any time that you wish to
> > run a
> > program that is open in the editor half of IDLE, hit F5 and the 
> Python
> > shell
> > half of IDLE comes to the top and runs the program.
> >
> > If doing all that doesn't do what I expect it to do, or you have
> > something
> > else in mind, reply back. If it does, then great!
> >
> > Oh. And tell me which editor you are using which magically opens a
> > python
> > interpreter when you type Python into it. ;-)
> >
> > JS
> >
> > ___
> > Tutor [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> > Moody friends. Drama queens. Your life? Nope! - their life, your 
> story.
> > Play Sims Stories at Yahoo!
> > Games.___
> > Tutor [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>
> No need to miss a message. Get email on-the-go
> with Yahoo! Mail for Mobile. Get 
> started.___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple way to compare Two lists

2007-08-16 Thread jim stockford

Why is a dict lookup constant time. I.e. if there's a
loop that walks a (shorter) list and compares each
element with each element of a dict, what's going
on to make this faster than an outer loop walking
a list and an inner loop walking a second list?



On Aug 16, 2007, at 5:01 PM, Stephen McInerney wrote:

>
> Sorting both lists is unnecessary and not very scalable (order(NlogN)).
>
> Assuming the lists do not contain duplicates,
> just turn the longer one into a dict and check that each element of the
> shorter list in that dict (e.g. "if j not in BigList: return false")
> Since dict lookup is constant-time O(1), this approach is O(M)
> i.e. speed is linear in the length of the shorter list;
> and memory requirement is O(N+M) i.e. linear in the length
> of the longer list. If M<
> Stephen
>
>
>> From: Jaggo <[EMAIL PROTECTED]>
>> Reply-To: [EMAIL PROTECTED]
>> To: tutor@python.org
>> Subject: Re: [Tutor] Simple way to compare Two lists
>> Date: Thu, 16 Aug 2007 10:11:14 -0700 (PDT)
>>
>> Thank you Kent, Michael, Tom and anyone else I'm forgetting who took  
>> time to reply.
>>
>> I don't work quite so fast, very limited personal computer time means  
>> I only do it on weekends,
>>
>> I read through your suggestions and eventually found a way to  
>> speed-up the proccess through sorting the Two lists, then manually  
>> iterating through each of them. This way I've completely canceled the  
>> need to compare Two lists: instead just ensuring I start from a point  
>> not taken in One list and having to only check whether Item not in  
>> BigList.
>>
>> [If anyone's interested, I should have the script finished and  
>> thoroughly tested on, ah, next weekend, and I could post a link  
>> here.]
>>
>> Again, Thx.
>> -Omer.
>>
>> Message: 1
>> Date: Fri, 10 Aug 2007 08:11:47 -0400
>> From: Kent Johnson
>> Subject: Re: [Tutor] Simple way to compare Two lists
>> To: Tom Fitzhenry , tutor@python.org
>> Message-ID: <[EMAIL PROTECTED]>
>> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>>
>> Tom Fitzhenry wrote:
>> > On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote:
>> >> Can anyone think of any better way?
>> >
>> > If SmallList and BigList are sorted (in order), there is a faster  
>> method:
>> >
>> > def IsAPartOfList(SmallList,BigList):
>> > for i in BigList:
>> > for j in SmallList:
>> > if i==j:
>> > return true
>> > if i>j:
>> > break
>> > return false
>> >
>> > (I'm not sure how encouraged using break statements are, so wait  
>> for a tutor to
>> > answer)
>>
>> break is fine! If the list you are searching is sorted you can use the
>> bisect module to do a binary search instead of the linear search  
>> above.
>>
>> > If one list is already sorted but the other isn't, it may still be  
>> faster to
>> > sort the unsorted list then use the method above.
>>
>> I don't think BigList has to be sorted in the above algorithm. If both
>> lists are sorted I suppose you could write it like a merge sort,  
>> walking
>> along both lists looking for a match.
>>
>> Kent
>>
>>
>>
>>
>> -
>> Park yourself in front of a world of choices in alternative vehicles.
>> Visit the Yahoo! Auto Green Center.
>
>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
> _
> See what you’re getting into
> before you go there  
> http://newlivehotmail.com/? 
> ocid=TXT_TAGHM_migration_HM_viral_preview_0507
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there any logic in this?

2007-09-01 Thread jim stockford

seems to me this is an artifact of the language.
reading right to left:
"make a list that contains 10,40,30,20, then create a
name 'a' to be used as a label to identify that list, then
(next line) create a label 'b' to attach to whatever is
the thing 'a' refers to, then (next line) modify the thing
via 'b' (e.g. b.sort)."
the essence is to allow multiple names for things
without clogging up memory with a lot of copies and
to have a uniform mechanism of referencing anything
(i.e. any "object", for everything in Python is an object,
hence the utility of a uniform mechanism.
the effect is programmers have to know this is the
case. those who have the old style "C head" using the
model of a variable name representing an area in
memory where assignment copies data to a new area
in memory with the other variable name will get caught
on this until they catch on.

I'll be very grateful for any criticism of the above.



On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote:

> If you copy a list into another variable, and then change the second
> one, the first gets changed aswell, for example:
>
 a = [10, 40, 30, 20]
 b = a
 b.sort()
 a
> [10, 20, 30, 40]
 b
> [10, 20, 30, 40]
>
> or:
>
 a = [10, 40, 30, 20]
 b = a
 b[0] = 99
 a
> [99, 40, 30, 20]
 b
> [99, 40, 30, 20]
>
> this happens with dictionary's too, but not with intergers, it is not
> that this is a problem because I can just use...
>
 b = a[:]
>
> ...but I wonder if there is any logic behind this, I cannot find a
> practical use for it, just problems.
>
> thx, Righard
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there any logic in this?

2007-09-01 Thread jim stockford

essentially right reinterpretation. I believe Pythonists
use the term "bind" to describe the action of what we're
used to thinking of as the assignment operator =
the name 'a' is bound to the list, in your former
example.

Everything is an object in Python, including integers.
Every object persists until there are no names bound
to it, in which case the object is permanently out of
scope and eligible for garbage collection. but...
Objects for the small integers remain in scope always.

your example is interesting, but reading right to left
doesn't work well, which bothers me.
I read your first line as "make 'a' reference the
integer object 10, then make 'b' reference whatever 'a'
references, then (next line) add 10 to whatever 'b'
references, but oops: under the hood the Python
interpreting system must as its first principle keep
common sense--the human wants to add 10 to 'b' so
'b' will now reference the integer object that matches
10 + 10.
I totally made the above explanation up, so it's a
good target for skepticism.
I hate not being able to read from right to left in a
procrustean manner. The compromise is read the
right side of the "assignment" operator and then
the left side and do what common sense expects.

I hope one of the p-t gurus will explain better.



On Sep 1, 2007, at 8:02 AM, Righard/Riku van Roy wrote:

> Thanks for your explenation, so essentialy a = b, copys the pointer of 
> a
> to b rather than the actual content. This explains why a[:] does work.
>
> Do you have an explenation why this is not the case with integers ie.
>
>>>> a, b = 10, a
>>>> b = b + 10
>>>> a, b
> (10, 20)
>
> thx
>
>
> Op za, 01-09-2007 te 07:50 -0700, schreef jim stockford:
>> seems to me this is an artifact of the language.
>> reading right to left:
>> "make a list that contains 10,40,30,20, then create a
>> name 'a' to be used as a label to identify that list, then
>> (next line) create a label 'b' to attach to whatever is
>> the thing 'a' refers to, then (next line) modify the thing
>> via 'b' (e.g. b.sort)."
>> the essence is to allow multiple names for things
>> without clogging up memory with a lot of copies and
>> to have a uniform mechanism of referencing anything
>> (i.e. any "object", for everything in Python is an object,
>> hence the utility of a uniform mechanism.
>> the effect is programmers have to know this is the
>> case. those who have the old style "C head" using the
>> model of a variable name representing an area in
>> memory where assignment copies data to a new area
>> in memory with the other variable name will get caught
>> on this until they catch on.
>>
>> I'll be very grateful for any criticism of the above.
>>
>>
>>
>> On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote:
>>
>>> If you copy a list into another variable, and then change the second
>>> one, the first gets changed aswell, for example:
>>>
>>>>>> a = [10, 40, 30, 20]
>>>>>> b = a
>>>>>> b.sort()
>>>>>> a
>>> [10, 20, 30, 40]
>>>>>> b
>>> [10, 20, 30, 40]
>>>
>>> or:
>>>
>>>>>> a = [10, 40, 30, 20]
>>>>>> b = a
>>>>>> b[0] = 99
>>>>>> a
>>> [99, 40, 30, 20]
>>>>>> b
>>> [99, 40, 30, 20]
>>>
>>> this happens with dictionary's too, but not with intergers, it is not
>>> that this is a problem because I can just use...
>>>
>>>>>> b = a[:]
>>>
>>> ...but I wonder if there is any logic behind this, I cannot find a
>>> practical use for it, just problems.
>>>
>>> thx, Righard
>>>
>>>
>>>
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] about modules, classes, methods, functions

2007-09-02 Thread jim stockford

I've gotten red-eyed looking through google pages
to find answers. I've read the python.org docs and
tutorials entirely (some parts very quickly).

If I write a little .py file, its name is __main__

assuming no big nit-picks in the claim above,
is __main__ a class?

What exactly does it mean "module" and how
is that different from a class.

Is it sufficient to define a class as some executable
code that gets run when it's loaded? Someone has
so defined, but I don't think it's sufficient.

classic definition of a function is some code that
takes arguments and returns a single value. What's
the definition of a function in python?

how is a method different from a function? Is it
just that a method is a member of a class, i.e. can
a class have both methods and functions?

thanks in advance.
jim

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] random number generator

2007-10-04 Thread Jim Hutchinson
Hello,

I am writing a little program to test a theory and as part of teaching
myself Python. I've only been at this about a week now. I have a
program that "should" work but doesn't. It generates a random number
between 1 and 2 out to 10 decimal places. I think there is something
wrong with how my random number is generated or defined or how my
guesses are defined. I added a line to tell me what the random number
is and then if I enter it as a guess it doesn't match and exit the
loop. Any idea what I'm doing wrong? Here is a sample output:

---
I'm thinking out to 10 decimal places. Good luck.

1.14981949962
Make a guess: 1.14981949962
Higher...
Make another guess: 1.14981949963
Lower...
1.14981949963
Make another guess:
---

Here is my code:

---
# Number guessing game
#
# The computer will choose a number between 1 and 2 (to ten decimal places)
# and the player will try to guess the number. The program will tell the
# player the number is either higher or lower than the number they guessed.
import random
import os
os.system("clear")
print "\nWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 2."
print "\nYes, that's right. Between 1 and 2."
print "\nYou have heard of decimals right? Well, I'm"
print "\nthinking out to 10 decimal places. Good luck.\n"
# set random value
random.seed()
number = random.random() + 1
print number
guess = float(raw_input("Make a guess: "))
tries = 1
# the guess loop
while (guess != number):
if (guess > number):
print "Lower..."
else:
print "Higher..."
guess = float(raw_input("Make another guess: "))
tries += 1
print "Congratulations! You guessed my number! The number was", number
print "It took you only", tries, "tries!\n"
# end
---

Thanks,
Jim

-- 
Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] random number generator

2007-10-06 Thread Jim Hutchinson
Greetings all,

It seems I forgot to subscribe to the list so I didn't receive any of
the replies. However, I did check the archive and found all of the
very helpful suggestions. Thanks for your time.

Based on the replies I was able to get this to more or less work.
However, one problem still exists. If you guess a number that is
slightly larger than the random number it evaluates to correct

For example:


The number is 1.78889511441
Make a guess: 1.788895114455

Congratulations! You guessed my number! The number was 1.78889511441

It took you only 1 tries!
---

Or even:

---
1.36344601965
Make a guess: 1.3634460196

Congratulations! You guessed my number! The number was 1.36344601965

It took you only 1 tries!
---

I'm also unclear as to how it is choosing a random number out to 10
decimal places. Is that the default and it's just coincidence that I
chose 10? What if I want a random number to 20 decimal places or five?

Here is the code:

# Number guessing game
#
# The computer will choose a number between 1 and 2 (to ten decimal places)
# and the player will try to guess the number. The program will tell the
# player the number is either higher or lower than the number they guessed.
import random
import os
os.system("clear")
print "\nWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 2."
print "\nYes, that's right. Between 1 and 2."
print "\nYou have heard of decimals right? Well, I'm"
print "\nthinking out to 10 decimal places. Good luck.\n"
# set random value
random.seed()
number = random.random() + 1
print number
guess = float(raw_input("Make a guess: "))
tries = 1
# the guess loop
while (abs(number-guess) > 0.01):
if guess > number:
print "Lower..."
elif guess < number:
print "Higher..."
tries += 1
if guess != number:
guess = float(raw_input("Make another guess: "))
print "\nCongratulations! You guessed my number! The number was", number
print "\nIt took you only", tries, "tries!\n"
# end

Thanks again,
Jim
-- 
Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2 problems in a small script

2007-10-12 Thread jim stockford

On Oct 12, 2007, at 11:48 AM, Kent Johnson wrote:

> If all you want to do is copy the list, then
>lstB = lstA[:]
> is fine, or you can use
>lstB = list(lstA)

why choose one over the other? is there a performance
or other difference?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] global is bad but ...

2007-11-13 Thread jim stockford
On Nov 13, 2007, at 3:11 PM, Alan Gauld wrote:

> Rather than answer your question directly can I ask, do
> you know *why* wiser heads say global is bad? What
> problems does using global introduce? What problems
> does it solve?


i'll try:

globals are good because they provide common data to
one's entire program without issues of scope.

globals are bad because one can design (or just allow to
happen) software in which globals are changed by
different entities within the program without coordination.
the classic:
globflag = True
proc_1 checks globflag and starts to perform accordingly
proc_2 changes globflag to False for some good reason
before proc_1 has finished, and enough before so that
there's trouble.

how to get the good without the bad? in a small program,
be a disciplined coder. in a large program, wrap the globals
in some function wrapper that doesn't easily allow changes
to the global data. in the above case, write some kind of
not_yet code to keep proc_2 from changing globflag until
after proc_1 is finished.

okay, i tried. so why are globals bad and what problems
do they solve?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   6   >