Gribouillis 1,391 Programming Explorer Team Colleague

Oh, wait, it's not completely solved:

on linux, everything is fine.

on windows, however, webbrowser.open only opens Explorer, even though firefox is the default.

If I try startfile, it does open the associated program as d5e5 explained, but it fails to open the help file (it seems it only works with URL's)

To make sure you open firefox in a cross platform way, use webbrowser.get

import webbrowser
webbrowser.get("firefox").open("http://www.python.org")
vegaseat commented: thanks +10
Gribouillis 1,391 Programming Explorer Team Colleague

Gribouillis one liner is at least out of order, my set solution gives solution in order of occurance:

sent='"Give me bacon and eggs," said the other man.'
print sent
print list(find_dup(sent)) ## see earlier post

Output:

"Give me bacon and eggs," said the other man.
['e', ' ', 'a', 'n', 'g', '"', 's', 'i', 'd', 'o', 't', 'h', 'm']

Actually, your result is ordered according to the position of the second occurrence of each repeated item (which is also the position of first repetition).

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a version of get_duplicate_items as a one liner. I don't know if it is more efficient

from itertools import groupby, islice

def get_duplicate_items(iterable):
    return [k for (k, v) in groupby(sorted(iterable)) if len(tuple(islice(v, 2))) == 2]

print(get_duplicate_items('"Give me bacon and eggs," said the other man.'))

""" My output --->
[' ', '"', 'a', 'd', 'e', 'g', 'h', 'i', 'm', 'n', 'o', 's', 't']
"""
Gribouillis 1,391 Programming Explorer Team Colleague

I would use something like

from collections import defaultdict

def list_has_duplicate_items(L):
    return len(L) > len(set(L))

def get_duplicate_items(L):
    D = defaultdict(int)
    for k in L:
        D[k] += 1
    return [k for (k, v) in D.items() if v > 1]
Gribouillis 1,391 Programming Explorer Team Colleague

You should be able to use a dummy file by calling the linux command 'lockfile' from your programs (I never tried this, but it should work).

Gribouillis 1,391 Programming Explorer Team Colleague

The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators &, |, ^ to perform the bitwise operations and use the 'hex' function to get the hexadecimal representation of the resulting integers. Here is an example with python 3 (but it also works with python 2)

>>> x, y = int("0x00E2", 16), int("0x0F80", 16)
>>> print(hex(x & y))
0x80
>>> print(x, y, x & y)
226 3968 128
>>> print(hex(x | y))
0xfe2
>>> print(x | y)
4066
>>> print(bin(x), bin(y), bin(x&y), bin(x|y))
0b11100010 0b111110000000 0b10000000 0b111111100010
Gribouillis 1,391 Programming Explorer Team Colleague

An open file has a concept of 'position in the file'. After the first call to f.read(), the file position is at the end of the file. If you read again, you read an empty string. The solution is to go back to the beginning of the file

f.read()
f.seek(0) # go back to the beginning
text = f.read() # read again
Gribouillis 1,391 Programming Explorer Team Colleague

I know a method which uses the (great) lxml module instead of ElementTree. The lxml.etree.tostring() method accepts a 'pretty_print' keyword argument. See the example here http://codespeak.net/lxml/tutorial.html#serialisation .
In your case

>>> from lxml import etree
>>> root = etree.XML("<home><room>bedroom</room></home>")
>>> print(etree.tostring(root, pretty_print=True))
<home>
  <room>bedroom</room>
</home>
Gribouillis 1,391 Programming Explorer Team Colleague

This makes sense. Could you tell me what this line of could is doing, it's syntax is different than I've seen before:

row = [ x.strip('"') for x in row ]

It's called "list comprehension syntax". See the doc here http://docs.python.org/tutorial/datastructures.html#list-comprehensions.
In the above code, the line removes the " surrounding words in your html file (is it really what you want ?).

Gribouillis 1,391 Programming Explorer Team Colleague

First of all, why linear search? That's like the worst algorithm to use ever.

But if you don't want to use the Python internal algorithm, a for loop can do it:

def findValue(v, li):
    for i in len(li):
        if v == len[i]:
            return i
    return -1

But that's such a bad algorithm. Internally, you have this -> value in li Also, you can code your own "smart" algorithm, like i did here:

def average(number1, number2):
    return sum([number1, number2])/2

def bisectFind(li, item):
    midpoint = (len(li)-1)/2
    minIndex = 0
    maxIndex = len(li)-1
    while True:
        if maxIndex - minIndex < 11:
            for i in range(minIndex,maxIndex+1):
                if li[i] == item:
                    return i
            return None
        if item < li[midpoint]:
            maxIndex = midpoint
            midpoint = average(minIndex, maxIndex)
            continue
        elif item > li[midpoint]:
            minIndex = midpoint
            midpoint = average(minIndex, maxIndex)
            continue
        elif item == li[midpoint]:
            return midpoint

Binary search works only if the list is initially sorted.

vegaseat commented: good catch +10
Gribouillis 1,391 Programming Explorer Team Colleague

The list class 'index' method performs a linear search

>>> mylist = list("hello world")
>>> print(mylist)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> mylist.index('w')
6
>>> mylist[6]
'w'
>>> mylist.index('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

This also works for str objects (strings)

>>> mystr = "hello world"
>>> mystr.index('w')
6
>>> mystr.index('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
Gribouillis 1,391 Programming Explorer Team Colleague

You can use generators to iterate over your web page's lines

URL_TEMPLATE = ...

def gen_lines(symbol, stat):
    url = URL_TEMPLATE % (symbol, stat)
    for line in urllib.urlopen(url):
        yield line.strip()

def gen_rows(symbol, stat):
    for line in gen_lines(symbol, stat):
        row = line.split(",")
        row = [ x.strip('"') for x in row ]
        yield row

def test_me(symbol):
    for row in gen_rows(symbol, 'l1m3m4p2va2j1j4'):
        print row
Gribouillis 1,391 Programming Explorer Team Colleague

P.S. Tabs in python files are seen as a newbie mistake. Indents are usually 2 or 3 spaces

As a newbie, use the recommended (and widely used) 4 spaces indentation. You can configure your editor to put 4 spaces when you hit the tab key.

Gribouillis 1,391 Programming Explorer Team Colleague

Try print repr(text) to see what the string 'text' actually contains.

Also if your file contains non ascii data, you should try the "rb" opening mode.

Gribouillis 1,391 Programming Explorer Team Colleague

A simple > is equivalent to 1> . It redirects stdout to your file. A 2> redirects stderr. A google search with "linux redirection" should tell you all about redirection. For example, I found this http://en.wikipedia.org/wiki/Redirection_%28computing%29

Gribouillis 1,391 Programming Explorer Team Colleague

In linux, you could use

./test.py 2&> log.txt
Gribouillis 1,391 Programming Explorer Team Colleague

When you are asking a string to the user, use raw_input instead of input (with python 2). Here is a working version where I added a few while statements

import time
print "Let's learn how to add"
quit = False
while not quit:
    x = int(input ("Give me the first number: "))
    y = int(input ("Give me the second number: "))
    print "The result is", (x+y)
    while True:
        userinput = raw_input('Want to continue adding?\nA) Y\nB) N\n').lower()
        if userinput == 'a':
            print " Let's continue learning how to add"
            break
        elif userinput == 'b':
            print ('\nNow quitting program..')
            time.sleep(3)
            quit = True
            break
        else:
            print('\nPlease enter "A", or "B"\n')
Gribouillis 1,391 Programming Explorer Team Colleague

Is there any problem with manipulating very long strings?
When I say long, I'm meaning like over 100,000 characters long.
I'm using examplelongString = data.readline() to get it from an html file. I then use examplelongString .find('text to find') to search for stuff.

I've been trying to do it, it works fine for a string I have of 60,000 characters in length (doesn't take more than a second to do BTW), but when I try it on a 100,000 character string, it doesn't work, and seems to be getting into memory space it shouldn't have access to. (It doesn't give any errors or anything though), from the debugging I've done so far.

Does this sound right? Is there a better way of dealing with long strings?

The length of the string shouldn't make any difference unless you run out of memory. You say it doesn't give any error, but how do you know it accesses invalid memory space ? (what does this mean by the way ?) You should also try and print the repr() of your string to see if it contains the text you're looking for.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a session with the python interpreter which should help you:

Python 2.6.4
>>> values = "9 10 J Q K A".split()
>>> print(values)
['9', '10', 'J', 'Q', 'K', 'A']
>>> print list(enumerate(values))
[(0, '9'), (1, '10'), (2, 'J'), (3, 'Q'), (4, 'K'), (5, 'A')]
>>> print [(i+1, v) for (i, v) in enumerate(values)]
[(1, '9'), (2, '10'), (3, 'J'), (4, 'Q'), (5, 'K'), (6, 'A')]
>>> mapping = dict((i+1, v) for (i, v) in enumerate(values))
>>> mapping
{1: '9', 2: '10', 3: 'J', 4: 'Q', 5: 'K', 6: 'A'}
>>> mapping[3]
'J'
>>> mapping[6]
'A'
>>> import random
>>> mapping[random.randint(1, 6)]
'Q'
>>> mapping[random.randint(1, 6)]
'9'
>>> rolls = [mapping[randint(1,6)] for i in range(5)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'randint' is not defined
>>> rolls = [mapping[random.randint(1,6)] for i in range(5)]
>>> rolls
['10', 'A', 'A', '10', '10']
>>> rolls
['10', 'A', 'A', '10', '10']
>>> rolls = [mapping[random.randint(1,6)] for i in range(5)]
>>> print rolls
['9', 'Q', '9', '10', 'A']
>>> print ", ".join(rolls)
9, Q, 9, 10, A
>>> print "You rolled " + ", ".join(rolls)
You rolled 9, Q, 9, 10, A
>>>
Gribouillis 1,391 Programming Explorer Team Colleague

Your matrix has 2 eigenvalues: 30 and -30. The eigenspace for the eigenvalue -30 is the space of vectors proportional to (1, 1, 1). Both Matlab and python seem to return vectors with euclidian norm 1. There are 2 possible eigenvectors with norm 1 (1/sqrt(3), 1/sqrt(3), 1/sqrt(3)) and the opposite. Matlab finds the first one and python the other (it's the first column of the matlab matrix and the second column of the python matrix.
The other eigenspace, for the eigenvalue 30 has dimension 2, and it is the plane of vectors orthogonal to (1,1,1). There are many possible basis of this plane and matlab and python return different basis (2nd and 3rd column in matlab's matrix and 1st and 3rd column in python's matrix).

So you don't get different eigenvalues, you get different eigenvectors, which is not suprising with a multiple eigenvalue.

Gribouillis 1,391 Programming Explorer Team Colleague

You should probably compile with the re.DOTALL option, because the dot character does not normally match newline

m=re.compile('<test>(.*)</test>', re.DOTALL).search(MyStr)
Gribouillis 1,391 Programming Explorer Team Colleague

Sorry i had written client_test instead of clients_test. Now im getting below error

URLError: <urlopen error (11001, 'getaddrinfo failed')>

Did you check that the last printed url was an url to a clients_test directory containing the game.exe ? If your page contains many links with "clients_test", how do we select the good link. You said we could use clients_test5 or clients_test7, but why not clients_test4 ? Also, can you post the exact url of the clients_test page ?

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, replace the get_client_url function by

def get_client_url():
    url = get_artifacts_url()
    for link in get_links(url):
        print link["href"]
        if link["href"].find("/clients_test") > 0:
            return "http://11.12.13.27:8080" + link["href"]
Gribouillis 1,391 Programming Explorer Team Colleague

Try to replace line 9 by client_re = re.compile(r"clients_test")

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, here is a new version which should read the client url

URL = "http://11.12.13.27:8080/cruisecontrol"
BRANCH_FILE = "branch.txt"


from urllib2 import urlopen
from HTMLParser import HTMLParser
import re
client_re = re.compile(r"\d+/clients_test\d*")

def read_branch():
    return open(BRANCH_FILE).read().strip()

class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kwd):
        HTMLParser.__init__(self, *args, **kwd)
        self.links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                self.links.append(dict(attrs))

    def handle_endtag(self, tag):
        pass

def get_links(url):
    parser = MyHTMLParser()
    parser.feed(urlopen(url).read())
    parser.close()
    return parser.links

def get_artifacts_url():
    branch = read_branch().lower()
    url = URL + "/buildresults/ABC_%s_nightly_build" % branch
    for link in get_links(url):
        #print link["href"]
        if link["href"].startswith("artifacts/"):
            return "%s/%s" % (URL, link["href"])

def get_client_url():
    url = get_artifacts_url()
    for link in get_links(url):
        if client_re.search(link["href"]):
            return "http://11.12.13.27:8080" + link["href"]

if __name__ == "__main__":
    url = get_client_url()
    if url is None:
        print "Could not find client url"
    else:
        print get_links(url)
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a new version with printed output, I tried to isolate the function to get the url of the artifacts page because I don't understand the problem. Please post the output again

URL = "http://11.12.13.27:8080/cruisecontrol"
BRANCH_FILE = "branch.txt"


from urllib2 import urlopen
from HTMLParser import HTMLParser

def read_branch():
    return open(BRANCH_FILE).read().strip()

class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kwd):
        HTMLParser.__init__(self, *args, **kwd)
        self.links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                self.links.append(dict(attrs))

    def handle_endtag(self, tag):
        pass

def get_links(url):
    parser = MyHTMLParser()
    parser.feed(urlopen(url).read())
    parser.close()
    return parser.links

def get_artifacts_url():
    branch = read_branch().lower()
    url = URL + "/buildresults/ABC_%s_nightly_build" % branch
    for link in get_links(url):
        print link["href"]
        if link["href"].startswith("artifacts/"):
            return "%s/%s" % (URL, link["href"])


if __name__ == "__main__":
    url = get_artifacts_url()
    if url is None:
        print "Could not find artifacts url"
    else:
        print get_links(url)
Gribouillis 1,391 Programming Explorer Team Colleague

It seems that it finds the artifacts url ... Now replace again the if __name__ == "__main__" part by this, and don't change the indentation in any way

if __name__ == "__main__":
    branch = read_branch().lower()
    url = URL + "/buildresults/ABC_%s_nightly_build" % branch
    artifacts_url = None
    for link in get_links(url):
        if link["href"].startswith("artifacts"):
            artifacts_url = "%s/%s" % (URL, link["href"])
            break
    #L = artifacts_url.split("/")
    #number = L[-1]
    print "ARTIFACTS URL", artifacts_url
    clients_url = artifacts_url+"/clients_test"
    for link in get_links(clients_url):
        print link
Gribouillis 1,391 Programming Explorer Team Colleague

Can you replace the if __name__ == "__main__" part by this

if __name__ == "__main__":
    branch = read_branch().lower()
    url = URL + "/buildresults/ABC_%s_nightly_build" % branch
    artifacts_url = None
    print "BEFORE LINK LOOP"
    for link in get_links(url):
        print link["href"]
        if link["href"].startswith("artifacts"):
            artifacts_url = "%s/%s" % (URL, link["href"])
            break
    print "AFTER LINK LOOP"
    #L = artifacts_url.split("/")
    #number = L[-1]
    #clients_url = artifacts_url+"/clients_test"
    #for link in get_links(clients_url):
    #   print link

and post the output ? It's difficult for me because I can't test the code on your machine...

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry, it means that it didn't find the artifacts page. Replace the get_links function by this one. I hope there is no other error :)

def get_links(url):
    parser = MyHTMLParser()
    parser.feed(urlopen(url).read())
    parser.close()
    return parser.links

also replace artifacts_url = "%s/%s"(URL, link["href"]) by artifacts_url = "%s/%s" % (URL, link["href"])

Gribouillis 1,391 Programming Explorer Team Colleague

This new version should print the links in the clients_test page (I skipped the artifacts page). If it works, we should find your exe file in the next step. Please post the links again

URL = "http://11.12.13.27:8080/cruisecontrol"
BRANCH_FILE = "branch.txt"


from urllib2 import urlopen
from HTMLParser import HTMLParser

def read_branch():
    return open(BRANCH_FILE).read().strip()

class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kwd):
        HTMLParser.__init__(self, *args, **kwd)
        self.links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                self.links.append(dict(attrs))

    def handle_endtag(self, tag):
        pass

def get_links(url):
    parser = MyHTMLParser()
    parser.feed(urlopen(URL).read())
    parser.close()
    return parser.links

if __name__ == "__main__":
    branch = read_branch().lower()
    url = URL + "/buildresults/ABC_%s_nightly_build" % branch
    artifacts_url = None
    for link in get_links(url):
        if link["href"].startswith("artifacts/ABC_%s_nightly_build" % branch):
            artifacts_url = "%s/%s"(URL, link["href"])
            break
    L = artifacts_url.split("/")
    number = L[-1]
    clients_url = artifacts_url+"/clients_test/"
    for link in get_links(clients_url):
        print link
Gribouillis 1,391 Programming Explorer Team Colleague

Hey, you can use the python documentation too. Here is an example for python 3 http://docs.python.org/py3k/library/pickle.html#examples, and the same for python 2 http://docs.python.org/library/pickle.html#example

Gribouillis 1,391 Programming Explorer Team Colleague

Hello Gribouillis,

Thanks for your reply. I guess you can tell that I'm still fairly new to Python ;)
Your code looks much nicer, but it still doesn't remove the src_file for some reason. Do you have any idea why?

Doris

I don't understand. When I run the code in my linux system, it runs well and removes the src files. It could be a problem of file permissions. You should check the permissions of your files. Before that, you can check if you can move one of the files manually with a cut and paste operation.

Gribouillis 1,391 Programming Explorer Team Colleague

I would write it this way

import re, glob, os
# compile the pattern only once and separately
# avoid unnecessary groups in the pattern
# escape the dot character
checkedpattern = re.compile(r'checked([0-9]+?)\.txt')

# avoid 'file' as a variable name
for src_file in glob.glob('C:/dir1/checked*.txt'):
    # Find out the file number
    found = checkedpattern.search(src_file)
    if not found:
        continue
    filenumber = found.group(1)
    dest_file = 'C:/dir2/moved%s.txt' % filenumber
    # simply use os.rename (according to the python doc)
    os.rename(src_file, dest_file)
Gribouillis 1,391 Programming Explorer Team Colleague

There are many interesting google results for ontology+python and ontology+protege. I think you should check them first. Also I understand that OWL is an xml dialect, which means that it can be parsed by a python library like lxml.

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, now create a text file named 'branch.txt' which contains gsm_7.4 for example and
run this modified code, it should list the links in the next page of the procedure. Please post these links again

URL = "http://11.12.13.27:8080/cruisecontrol"
BRANCH_FILE = "branch.txt"


from urllib2 import urlopen
from HTMLParser import HTMLParser

def read_branch():
    return open(BRANCH_FILE).read().strip()

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                print attrs

    def handle_endtag(self, tag):
        pass

if __name__ == "__main__":
    parser = MyHTMLParser()
    branch = read_branch().lower()
    url = URL + "/buildresults/ABC_%s_nightly_build" % branch
    parser.feed(urlopen(url).read())
    parser.close()

I must go for a few hours, so won't be able to post the next step immediately.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a piece of code which should display a list of the links available from your page http://11.12.13.27:8080/cruisecontrol

URL = "http://11.12.13.27:8080/cruisecontrol"


from urllib2 import urlopen
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                print attrs

    def handle_endtag(self, tag):
        pass

if __name__ == "__main__":
    parser = MyHTMLParser()
    parser.feed(urlopen(URL).read())
    parser.close()

Can you post this list here and tell me if you see the link that you must follow from this page, and how you recognize it ? If this works, we may be able to download the next page and simulate the procedure step by step.

Gribouillis 1,391 Programming Explorer Team Colleague

Is there a way to predict the address of the exe file depending on the day ? It's difficult to help you if I can't see the web pages. A possibility would be to download the web pages and parse them, but we need some criteria to automate the choice of the links to follow.

Gribouillis 1,391 Programming Explorer Team Colleague

We are going to explore why it didn't work. Can you run this script and post it's output ? (you must set the DOWNLOAD_DST)

DOWNLOAD_DST = "C:/....game.exe"

class Command(object):
    """Run a command and capture it's output string, error string and exit status"""

    def __init__(self, command):
        self.command = command 

    def run(self, shell=True):
        import subprocess as sp
        process = sp.Popen(self.command, shell = shell, stdout = sp.PIPE, stderr = sp.PIPE)
        self.pid = process.pid
        self.output, self.error = process.communicate()
        self.failed = process.returncode
        return self

    @property
    def returncode(self):
        return self.failed

def install(prog):
    com = Command(prog).run()
    print("OUTPUT")
    print(com.output)
    print("ERROR")
    print(com.error)
    print("RETURN CODE: %s" % str(com.returncode))

if __name__ == "__main__":
    install(DOWNLOAD_DST)
Gribouillis 1,391 Programming Explorer Team Colleague

If you only want to read blank cells, you could use a defaultdict

from collections import defaultdict
parsed_dictionary = defaultdict(lambda: None, book[0][1])

This would insert a value None if you try to read a non existent key (0,1) for example, instead of raising KeyError.

rasizzle commented: Very helpful. +1
Gribouillis 1,391 Programming Explorer Team Colleague

Well if the file is always found at the same address, it shouldn't be too hard to automate the task, a script could look like

from urllib2 import urlopen
import subprocess as sp

DOWNLOAD_URL = "http://11.12.13.27:8080/.....game.exe"
DOWNLOAD_DST = "C:/....game.exe"

def download(url, dst_file):
    content = urlopen(url).read()
    outfile = open(dst_file, "wb")
    outfile.write(content)
    outfile.close()


def install(prog):
    process = sp.Popen(prog, shell=True)
    process.wait()

def main():
    download(DOWNLOAD_URL, DOWNLOAD_DST)
    install(DOWNLOAD_DST)

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

Sweet. How do I go about adding exception handling to it? Also, is there an alternative to this by using pickles?

Exception is already handled in the main() function if you look carefully. And yes, you could use pickle to store the high scores, but it's not necessarily better than a text file because your high scores don't contain complex data with cross references.

Gribouillis 1,391 Programming Explorer Team Colleague

I modified your code. It seems to work now

scores_file = "scores.txt"

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except (OSError, IOError):
        return []

def store_scores(filename, scores):
    out = open(filename, "w")
    out.write(repr(scores))
    out.close()


def main():
    high_scores = load_scores(scores_file)
    try:
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def main():
    try:
        high_scores = load_scores(scores_file)
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def user_session(scores):
    choice = None
    while choice != "0":

        print \
    """
    High Scores Keeper
    
    0 - Quit
    1 - List Scores
    2 - Add a Score
    """
    
        choice = raw_input("Choice: ")
        print

        if choice == "0":
            print "Good-Bye"

        elif choice == "1":
            print "High Scores\n"
            print "NAME\tSCORE" 
            for entry in scores:
                print entry

    
        elif choice == "2":
            name = raw_input("What is the player's name?: ")
            score = int(raw_input("What score did the player get?: "))
            entry = (name, score)
            scores.append(entry)
            scores.sort()
            scores.reverse()        
            scores = scores[:5]    

        else:
            print "Sorry, but", choice, "isn't a valid choice."
  
    raw_input("\n\nPress the enter key to exit.")
    return

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

I changed a few things in load_scores() and main(). See if it works better

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except (OSError, IOError):
        return []

def main():
    high_scores = load_scores(scores_file)
    try:
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)
Gribouillis 1,391 Programming Explorer Team Colleague

I tried that and it didn't work.

"It doesn't work" does not exist. If it doesn't work, there is an exception traceback or something that tells us what happened. What does python say ?

Gribouillis 1,391 Programming Explorer Team Colleague

You could have a code structure like this

scores_file = "scores.txt"

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except OSError:
        return []

def store_scores(filename, scores):
    out = open(filename, "w")
    out.write(repr(scores))
    out.close()


def main():
    try:
        high_scores = load_scores(scores_file)
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def user_session(scores):
    choice = None
    while choice != "0":
        ... # PUT YOUR PREVIOUS CODE HERE

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

At first sight, you should indent def savefile():... to make it a method of the App class and use filemenu.add_command(label='Save', command=self.savefile) in the __init__ method.

Gribouillis 1,391 Programming Explorer Team Colleague

I do not know Pythons standard library yet well, but old BASIC hacker would do

""" Desired results
Input  Output
2.84 > 00:02.8
2.89 > 00:02.9
59.99 > 01:00.0
"""
def convert1(t):
    ## desisecond rounding
    t= int(t*10+0.5)  ## add half to get rounding to desisecond (funny unit BTW)
    minutes, ds = divmod(t,60*10)
    minutes=minutes % 10
    s,ds= divmod(ds, 10)
    return (minutes,s,ds)

def timestr(minutes,s,ds):
    return str(minutes).zfill(2)+':'+str(s).zfill(2)+'.'+str(ds).zfill(1)

for f in [2.84, 2.89, 59.99]:
    t=convert1(f) ## get minutes and desiseconds
    print f,'->',timestr(*t)    
""" Output:
>>> 
2.84 -> 00:02.8
2.89 -> 00:02.9
59.99 -> 01:00.0
"""

I suggest

timestr = "{0:0>2}:{1:0>2}.{2:0>1}".format

for python >= 2.6

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

It's only an idea, but don't you think sys.argv contains the path to the double-clicked file ?

vegaseat commented: nice indeed +10
Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you should start with the output of

>>> help(str)