SEARCH

Enter your search query in the box above ^, or use the forum search tool.

You are not logged in.

#1 2012-03-19 19:58:00

ackernan
#! Junkie
Registered: 2011-01-10
Posts: 403

[SOLVED:]Python function help?

I'm starting with python, need some help.  This error is confusing.  I got the original python script off the this #! board.  It worked fine but copied files and I wanted to symlink and made a few other changes.  I was getting an error about file existing when the symlink was created.  I decided to write a function to delete the files before the symlink.  I use an if statement too control when files are deleted.  The problem is the if statement works in one function but not another.  The files get created then deleted shortly afterwards, not sure why.  Here's the function in question and a similar one that is working.

Problem function..

def check_artist_art():
    if os.path.exists("/tmp/artistinfo") and open("/tmp/artistinfo").read() != title:
        if os.path.exists(home + "/.artist"):
            os.remove(home + "/.artist")
        if os.path.exists("/tmp/artistinfo"):
            os.remove("/tmp/artistinfo")
            print artist
        return False
    elif os.path.exists("/tmp/artistinfo") and open("/tmp/artistinfo").read() == artist:
        return False
    return True

Function that works correctly...

def check_album():
    if os.path.exists("/tmp/albuminfo") and open("/tmp/albuminfo").read() != album:
        if os.path.exists(home + "/.album"):
            os.remove(home + "/.album")
        if os.path.exists("/tmp/albuminfo"):
            os.remove("/tmp/albuminfo")
        return False
    elif os.path.exists("/tmp/trackinfo") and open("/tmp/trackinfo").read() == artist + album:
        return False
    return True

Here's the full python script..

#!/usr/bin/python
#Start from albumart-f.py

import commands
from optparse import OptionParser

#retrieve track info from player
def get_info():
    check_running = commands.getoutput("ps aux")
    check_running = check_running.split("\n")
    for line in check_running:
        if "mocp" in line:
            return commands.getoutput("mocp -Q %artist"),commands.getoutput("mocp -Q %album"),commands.getoutput("mocp -Q %song"),commands.getoutput("mocp -Q %file")
    return "","","",""

#resize image
def size_image(width, height, path):
    image = Image.open(path)
    image = image.resize((width, height))
    image.save(path, "png")

#add reflection to image
def reflect(width, height, path):
    image = Image.open(path)
    flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM)
    final_image = Image.new('RGBA', (width, (height * 2) + 1) , (0, 0, 0, 0))
    gradient = Image.new('L', (1,255))
    for y in range(255, 0, -1):
        if y < 128:
            gradient.putpixel((0,y),255 - (y * 2))
        else:
            gradient.putpixel((0,255-y),0)
    alpha = gradient.resize(flipped_image.size)
    flipped_image.putalpha(alpha)
    final_image.paste(image, (0, 0))
    final_image.paste(flipped_image, (0, height + 1))
    final_image.save(path, "png")

def check_album():
    if os.path.exists("/tmp/albuminfo") and open("/tmp/albuminfo").read() != album:
        if os.path.exists(home + "/.album"):
            os.remove(home + "/.album")
        if os.path.exists("/tmp/albuminfo"):
            os.remove("/tmp/albuminfo")
        return False
    elif os.path.exists("/tmp/trackinfo") and open("/tmp/trackinfo").read() == artist + album:
        return False
    return True

#fetch album
def get_album():
    if not os.path.exists(musicdir + "/cover.png"):
        api_album = api.get_album(album, artist)
        if api_album.image["extralarge"]:
            urllib.urlretrieve(api_album.image["extralarge"], musicdir + "/cover.png")
        elif api_album.image["large"]:
            urllib.urlretrieve(api_album.image["large"], musicdir + "/cover.png")
        elif api_album.image["medium"]:
            urllib.urlretrieve(api_album.image["medium"], musicdir + "/cover.png")
        elif api_album.image["small"]:
            urllib.urlretrieve(api_album.image["small"], musicdir + "/cover.png")
        else:
            commands.getoutput("cp %s %s" % (home + "/Pictures/Nocover.png", musicdir + "/cover.png"))
    open("/tmp/trackinfo","w").write(artist + album)
    open("/tmp/albuminfo","w").write(album)
    #commands.getoutput("cp '%s' '%s'" % ("%s/cover.png" % (musicdir), home + "/.album"))
    os.symlink(musicdir + "/cover.png", home + "/.album")
    size_image(width, height, home + album_path)
    if options.reflect:
        reflect(width, height, home + album_path)

def check_artist_art():
    if os.path.exists("/tmp/artistinfo") and open("/tmp/artistinfo").read() != title:
        if os.path.exists(home + "/.artist"):
            os.remove(home + "/.artist")
        if os.path.exists("/tmp/artistinfo"):
            os.remove("/tmp/artistinfo")
            print artist
        return False
    elif os.path.exists("/tmp/artistinfo") and open("/tmp/artistinfo").read() == artist:
        return False
    return True

#fetch artist art
def get_artist_art():
    if not os.path.exists(musicdir + "/" + artist + ".png"):
        api_artist = api.get_artist(artist)
        if api_artist.image["extralarge"]:
            urllib.urlretrieve(api_artist.image["extralarge"], musicdir + "/" + artist + ".png")
        elif api_artist.image["large"]:
            urllib.urlretrieve(api_artist.image["large"], musicdir + "/" + artist + ".png")
        elif api_artist.image["medium"]:
            urllib.urlretrieve(api_artist.image["medium"], musicdir + "/" + artist + ".png")
        elif api_artist.image["small"]:
            urllib.urlretrieve(api_artist.image["small"], musicdir + "/" + artist + ".png")
        else:
            commands.getoutput("cp %s %s" % (home + "/Pictures/Nocover.png", musicdir + "/" + artist + ".png"))
    open("/tmp/artistinfo","w").write(artist)
    #commands.getoutput("cp '%s' '%s'" % ("%s/%s.png" % (musicdir, artist), home + "/.artist"))
    os.symlink(musicdir + "/" + artist + ".png", home + "/.artist")
    size_image(width, height, home + artist_path)
    if options.reflect:
        reflect(width, height, home + artist_path)

def check_similar():
    if title == "":
        if os.path.exists(home + "/.similar"):
            os.remove(home + "/.similar")
        if os.path.exists("/tmp/titleinfo"):
            os.remove("/tmp/titleinfo")
        return False
    if os.path.exists("/tmp/titleinfo") and open("/tmp/titleinfo").read() == title:
        return False
    return True

def get_similar():
    api_artist = api.get_artist(artist)
    out = ""
    for item in api_artist.get_similar(limit=5):
        out = out + item.name + "\n"
    open(home + "/.similar", "w").write(out)

#set up command line options
parser = OptionParser()
parser.add_option("-s", "--size", dest="size", default="80x80", help="image size")
parser.add_option("-r", "--reflect", action="store_true", dest="reflect", default=False, help="image reflection")
parser.add_option("-a", "--artist-art", action="store_true", dest="artist_art", default=False, help="artist image")
parser.add_option("-n", "--net", action="store_true", dest="internet_art", default=False, help="internet image")
parser.add_option("--artist", action="store_true", dest="return_artist", default=False, help="artist")
parser.add_option("--album", action="store_true", dest="return_album", default=False, help="album")
parser.add_option("--title", action="store_true", dest="return_title", default=False, help="title")
parser.add_option("--similar", action="store_true", dest="similar_artists", default=False, help="similar artists")
(options, args) = parser.parse_args()

#check if size is valid
try:
    width,height = options.size.split("x")
    width = int(width)
    height = int(height)
except:
    parser.error("please specify size in WIDTHxHEIGHT format")

artist, album, title, musicfile = get_info()

#return artis, album, or title
if options.return_artist:
    print artist
    raise SystemExit()
if options.return_album:
    print album
    raise SystemExit()
if options.return_title:
    print title
    raise SystemExit()


import Image, os
#set up variables
home = os.getenv("HOME")
album_path = "/.album"
artist_path = "/.artist"
musicdir = commands.getoutput('dirname "' + musicfile + '"')
api_key = "5227173234d678f9eb9d415a1ff04489"

if check_artist_art() or check_album() or check_similar():
    import urllib, lastfm, re
    api = lastfm.Api(api_key)

if options.similar_artists and check_similar():
    get_similar()
    if os.path.exists(home + "/.similar"):
        print open(home + "/.similar").read()
    raise SystemExit()

if options.artist_art and check_artist_art():
    get_artist_art()

if check_album():
    get_album()

Last edited by ackernan (2012-03-21 10:21:55)

Offline

Be excellent to each other!

#2 2012-03-19 20:52:02

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [SOLVED:]Python function help?

what's the exact error you're getting?

Offline

#3 2012-03-20 01:36:52

noman
Member
Registered: 2012-03-06
Posts: 37

Re: [SOLVED:]Python function help?

Do the files that these two functions delete have a large size difference? Sorry if I'm misunderstanding, but "I was getting an error about file existing when the symlink was created" and the fact that the only difference I can see in these functions is the file types they are working with, leads me to believe that your artist images are larger than the album images, and taking longer to delete.

As an example, here's a test I ran to delete two files using os.remove, first is 3.5 megabytes jpg, second was 376 kilobytes jpg:

Deletion took 0.00117993354797 seconds.
Deletion took 0.000172138214111 seconds.

I think your function may be starting to delete the artist image, then getting back to the symlink function before deletion is finished. Try this:

def check_artist_art():
    import time
    if os.path.exists("/tmp/artistinfo") and open("/tmp/artistinfo").read() != title:
        if os.path.exists(home + "/.artist"):
            os.remove(home + "/.artist")
            time.sleep(1.0)
        if os.path.exists("/tmp/artistinfo"):
            os.remove("/tmp/artistinfo")
            time.sleep(1.0)
            print artist
        return False
    elif os.path.exists("/tmp/artistinfo") and open("/tmp/artistinfo").read() == artist:
        return False
    return True

This will pause for 1 second after each deletion. If you find this suddenly works, you can either fine tune it down to a much smaller wait time, probably  .1 of a second or less, or add a test after your os.remove or symlink code that repeatedly checks to make sure the file is gone before continuing.

Again, sorry if I've misunderstood. I'm basically a Python newb myself.

Offline

#4 2012-03-20 02:30:17

ackernan
#! Junkie
Registered: 2011-01-10
Posts: 403

Re: [SOLVED:]Python function help?

rhowaldt wrote:

what's the exact error you're getting?

The problem/error is file .artist is created then deleted immediately afterwards.  The file .album which uses a similar function in the python script is created and is not deleted until the appropriate time.

noman wrote:

Do the files that these two functions delete have a large size difference? ....

I tried the  function you posted, didn't fix/change the problem.  I looked at the file size of both symlinks .album and .artist, both are small.  The problem is .artist is deleted immediately after it's created.

Last edited by ackernan (2012-03-20 20:41:32)

Offline

#5 2012-03-20 20:41:46

ackernan
#! Junkie
Registered: 2011-01-10
Posts: 403

Re: [SOLVED:]Python function help?

Any ideas?

Offline

#6 2012-03-20 22:25:34

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [SOLVED:]Python function help?

^ sorry, not really. i'd have to try this out on my own system but am currently very busy and need to get to sleep now. all i can do right now is tell you what i'd do: try adding/removing stuff to the script to figure out exactly where this is happening and where it is going wrong, then try to change that up, if that doesn't work get angry, then calm yourself, then take another good, hard, pure-logic look at the code, hopefully find the culprit, fix it, done.

sorry i cannot be of more assistance right now. i may look at this later when i have more time...

Offline

#7 2012-03-21 02:11:58

ackernan
#! Junkie
Registered: 2011-01-10
Posts: 403

Re: [SOLVED:]Python function help?

rhowaldt wrote:

^ sorry, not really. i'd have to try this out on my own system but am currently very busy and need to get to sleep now. all i can do right now is tell you what i'd do: try adding/removing stuff to the script to figure out exactly where this is happening and where it is going wrong, then try to change that up, if that doesn't work get angry, then calm yourself, then take another good, hard, pure-logic look at the code, hopefully find the culprit, fix it, done.

sorry i cannot be of more assistance right now. i may look at this later when i have more time...

Thanks for the help.  I'm removing/adding stuff to help isolate the problem.  In so doing I create other problems.

**I did just what you said.  I got angry and took another good, hard, logic look.  Then I found the problem, a simple problem that was causing a BIG headache.  I was using the wrong varible in a test statement.  sad

Works great now that I use the variable.

Last edited by ackernan (2012-03-21 02:57:47)

Offline

#8 2012-03-21 09:50:37

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [SOLVED:]Python function help?

^ ha! good, hard, logic looks always do the trick. great thing you managed to solve this yourself. now if you can only mark this thread 'Solved' by editing your first post, everyone's happy! big_smile

Offline

Board footer

Powered by FluxBB

Copyright © 2012 CrunchBang Linux.
Proudly powered by Debian. Hosted by Linode.
Debian is a registered trademark of Software in the Public Interest, Inc.
Server: acrobat

Debian Logo