Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

Adbot
ADBOT LOVES YOU

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
In Python 3+, print is a function not statement so its arguments need to be wrapped in ()

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Python posted:

If you don't know which version to use, start with Python 2.6.4; more existing third party software is compatible with Python 2 than Python 3 right now.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

king_kilr
May 25, 2007

GregNorc posted:

poo poo, too late for that now. Unless there's a way to revert?

I'll probably try and fix this example and if the issues comes back again revert to the older version.

Mark's wrote a python 3 version of the book: http://diveintopython3.org/ so you can use that, or switch to python 2.6, they're really very similar.

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

GregNorc posted:

poo poo, too late for that now. Unless there's a way to revert?

I'll probably try and fix this example and if the issues comes back again revert to the older version.

If all you did was use print as a function like print() then the code should run perfectly fine in 2. Unless you used any of the special things print can do in 3.0(like file= rather than >> in python 2). python 2 should handle string formatting and concatenation inside of the tuple and print fine if it results in a tuple filled with a single item. So you are not too deep.

tehk fucked around with this message at 21:07 on Dec 17, 2009

BigRedDot
Mar 6, 2008

GregNorc posted:


Here's some people with similar bugs, who just got told "oh it's no big deal":
https://svn.enthought.com/epd/ticket/267
https://svn.enthought.com/epd/ticket/511

How funny, I used to work there.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

If someone has the time to give me a critique, I've got a 70 line module here on pastebin. This module scrapes a movies sex, violence, and profanity ratings off of kids-in-mind.com. (I've got a kid and I'd like my movie organizing script to take advantage of this stuff.)

I'm particularly looking for style and code organization critiques. It's hard when you're not a pro programmer and learning programming on your own in isolation to know if you're doing things the "right" way.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
I only have a minute but just glancing at it there are exactly zero reasons that should be a class and uncountably infinitely many why it shouldn't be. Other than that :wtf: it looks fine, but like I said I just did it a cursory once over.

king_kilr
May 25, 2007

Thermopyle posted:

If someone has the time to give me a critique, I've got a 70 line module here on pastebin. This module scrapes a movies sex, violence, and profanity ratings off of kids-in-mind.com. (I've got a kid and I'd like my movie organizing script to take advantage of this stuff.)

I'm particularly looking for style and code organization critiques. It's hard when you're not a pro programmer and learning programming on your own in isolation to know if you're doing things the "right" way.

Here goes, you asked for fully anal PEP8 mode, you got it :)

Put imports on seperate lines, alphabetized:
code:
import re
import urllib
import urrlib2
Line break before imports from external packages, 2 lines between imports and code.

class names should be CamelCase, no underscores, use new style classes (subclass object):
code:
class KimGetter(object):
Your __init__ doesn't do anything, don't define it.

One space after colons inside of dictionaries:
code:
values = {
    "key": "value",
}
Use str.split() instead of str.split(" ").

You've also got some indentation weirdness with docstrings. They should be indented all the way.

I'd simplify _move_the to be this:

code:
def _move_the(self, title):
    words = title.split()
    if words[0].lower() != "the":
        return title
    the = ", %s" % words.pop(0)
    return " ".join(words).strip() + the
Otherwise your code seems mostly sane. I'll note that I'm very fond of PyQuery: http://pyquery.org/ in place of beautiful soup.

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

Thermopyle posted:

If someone has the time to give me a critique, I've got a 70 line module here on pastebin. This module scrapes a movies sex, violence, and profanity ratings off of kids-in-mind.com. (I've got a kid and I'd like my movie organizing script to take advantage of this stuff.)

I'm particularly looking for style and code organization critiques. It's hard when you're not a pro programmer and learning programming on your own in isolation to know if you're doing things the "right" way.

Your class kim_getter is not much of a object and the methods could just be functions or a single function. I would not use a class unless you are defining a video object that has attributes like title, sex_rating, violence_rating, profanity_rating. Perhaps this stuff should be in that Video object you posted about earlier.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Thanks guys.

The reason it's a class is that I'm imitating several other third-party modules I'm using for querying stuff like IMDB and the like. Of course, now that you made me think of it, just because they use a class doesn't mean I have to...

Also, that kind of stuff was much appreciated, king_kilr.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

GregNorc posted:

poo poo, too late for that now. Unless there's a way to revert?

I'll probably try and fix this example and if the issues comes back again revert to the older version.

You don't need to revert, python installs with different major versions can live beside each other just fine. Just edit your path to put the one you want first. I think I was telling someone else about this a few pages back if you need more detail. Just grab the 2.6.4 dmg installer and it should set you up right good.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Out of curiosity more than anything...

Say I wanted to make the module I just posted a web service. You submit the movie title and year (a POST request a guess) and get back a JSON feed with the ratings.

What's the simplest way to do that? Is the simplest way somewhat scalable?

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

Thermopyle posted:

Out of curiosity more than anything...

Say I wanted to make the module I just posted a web service. You submit the movie title and year (a POST request a guess) and get back a JSON feed with the ratings.

What's the simplest way to do that? Is the simplest way somewhat scalable?

I'd personally use a Django install. You could do it by editing one line of the urls file and a view which would just take the variables, do whatever you want to do with them, and use the (simple)json module to serialise and output them. Django's pretty scalable as far as I know. If you want help, there's the Django thread here (or feel free to PM me if it's one of those 'yes it's in the docs but I can't be bothered reading them' type questions).

You could probably do it with a simpler mod_python or whatever type script I guess, but I'm not familiar with them.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

griliard
May 12, 2006
code:
def prompt_fermat():
        
        a = int(raw_input("Please enter value for a.\n"))

        b = int(raw_input("Please enter value for b.\n"))

        c = int(raw_input("Please enter value for c.\n"))

        n = int(raw_input("Please enter value for n.\n"))

        check_fermat(a, b, c, n)
int is a function that returns the integer value of the string you pass it. So proper usage is as above.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

ZippySLC
Jun 3, 2002


~what is art, baby dont post, dont post, no more~

no seriously don't post
Here's a pretty basic question. How well suited is Python for sysadmin-y type tasks? Basically, I'm trying to decide if I should learn Perl or Python. Obviously I'm leaning towards Python as a better general-purpose language, but I have no desire to write games or web apps, mostly looking for a replacement for writing shell scripts.

bitprophet
Jul 22, 2004
Taco Defender

ZippySLC posted:

Here's a pretty basic question. How well suited is Python for sysadmin-y type tasks? Basically, I'm trying to decide if I should learn Perl or Python. Obviously I'm leaning towards Python as a better general-purpose language, but I have no desire to write games or web apps, mostly looking for a replacement for writing shell scripts.

It's excellent for sysadmin stuff; I use it all the time. The builtin standard library alone has just about everything you could need for integration with the OS, and there are oodles upon oodles of third party libraries for anything imaginable.

The only thing Perl has going for it over Python in this area is the marginally quicker-to-write integration with regex and the shell, so whereas Perl can do stuff like (paraphrasing here, my Perl is weak)
code:
$STDIN.gets =~ /^(\d+)(\w+)$/
print("Number is $1, word is $2")
Python has to do slightly more work:
code:
import sys, re
results = re.findall(r'^(\d+)(\w+)$', sys.stdin.read())
print("Number is %s, word is %s" % (results[1], results[2]))
To be honest, though, the #1 reason to prefer Python over Perl for shell-script-like stuff (or anything) is simply that you can figure out what the hell it's doing 6 months later -- something that is often poo-pooed but is far more important than inexperienced folks think. And I don't mean this as a rag on "lol Perl is line noise", but hard-to-read code is inevitable in a language with such a large syntax and loose constraints on formatting, no matter what one's intentions are.

ZippySLC
Jun 3, 2002


~what is art, baby dont post, dont post, no more~

no seriously don't post

bitprophet posted:

To be honest, though, the #1 reason to prefer Python over Perl for shell-script-like stuff (or anything) is simply that you can figure out what the hell it's doing 6 months later -- something that is often poo-pooed but is far more important than inexperienced folks think. And I don't mean this as a rag on "lol Perl is line noise", but hard-to-read code is inevitable in a language with such a large syntax and loose constraints on formatting, no matter what one's intentions are.

Right, that's sort of the problem I have now with some of my larger, oft-ignored shell scripts. I write something, it runs fine for a long time, and then I need to make a change and I have to spend 30 minutes trying to decipher what the heck I was thinking.

Ferg
May 6, 2007

Lipstick Apathy
I've been messing with this all day...I have a class derived from BaseHTTPRequestHandler which I want to handle AJAX POST requests. Here's the AJAX POST I'm doing via jQuery;

code:
<script type='text/javascript'>
    jQuery.post('handler', 
    {
        param: 'SomeValue'
    }, 
    function(data, textStatus) {
        console.log('Hello!');
        console.log(data);
    });
</script>
I'm trying to use cgi.FieldStorage() to access the items but I don't seem to pull any results at all. What would you use to pull 'param' out of this request?

Note: I intentionally am not pasting my Python code. I don't care what I wrote, I want to see how you all do it this since my method is obviously not working.

Scaevolus
Apr 16, 2007

ZippySLC posted:

Right, that's sort of the problem I have now with some of my larger, oft-ignored shell scripts. I write something, it runs fine for a long time, and then I need to make a change and I have to spend 30 minutes trying to decipher what the heck I was thinking.
I had a few shell (bash) scripts that I converted into Python when they became too unwieldy to modify-- that is, I didn't know bash well enough to make it do what I want. Bash and Perl have confusing sytanx compared to Python, which is more verbose, but it's much easier to know all the syntax and refactor your scripts when you want to change things.

The set type can be really useful for sysadmin tasks.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

Scaevolus
Apr 16, 2007

GregNorc posted:

I've read stuff like this: http://docs.python.org/library/index.html

But is there something that goes even lower level? (IE what is allowed within a for loop etc)
http://docs.python.org/reference/index.html

If you want to understand the syntax on a deep level, that's what you want to read. Otherwise, the tutorial covers pretty much all the syntax.



e: I'd rewrite your code to be
code:
def uses_only(word, available):
    return not set(word) - set(available)

Scaevolus fucked around with this message at 03:40 on Dec 23, 2009

maskenfreiheit
Dec 30, 2004
Edit: Double Post

maskenfreiheit fucked around with this message at 20:34 on Mar 13, 2017

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Write a .bat file?

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:21 on Mar 13, 2017

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.
I have a decorator that I want to pass the class of the method it is decorating, but I can not do "@typecheck(Window) because as expected I get a name error. I know I can just modify my typecheck decorator with some 'ismethod' switch to avoid checking self, but I am wondering if there is some other way I could do this.

code:
class Window(object):
    ...
    @property
    def container(self):
        ...
    @container.setter
    @typecheck(Window, gContainer)
    def container(self, container):
        ...

    @container.deleter
    def container(self):
        ...

Lobe
Jul 27, 2009

griliard posted:

code:
def prompt_fermat():
        
        a = int(raw_input("Please enter value for a.\n"))

        b = int(raw_input("Please enter value for b.\n"))

        c = int(raw_input("Please enter value for c.\n"))

        n = int(raw_input("Please enter value for n.\n"))

        check_fermat(a, b, c, n)
int is a function that returns the integer value of the string you pass it. So proper usage is as above.

You could do it like that, but to be forward compatible then I would use input().
The cool thing about input() is it wraps the input to a type, so if you type "1" into the prompt it will see that it is an integer and return an integer, as opposed to a string.

That way you can change the code to this:

code:
def prompt_fermat():
        
        a = input("Please enter value for a.\n")
        b = input("Please enter value for b.\n")
        c = input("Please enter value for c.\n")
        n = input("Please enter value for n.\n")
        # There is definitely a nicer way to check the types, but I am lazy.
        # Will raise AssertionError if any of the numbers are not integers.
        # Alternatively you could write another function that is assured to
        # return a integer (And prompts the user for new input if they don't)
        # and remove the type check.
        for v in [a,b,c,n]: assert type(v) == int
        return a,b,c,n
Raw input is good if you are not sure what the input is going to be.

MaberMK
Feb 1, 2008

BFFs

tehk posted:

I have a decorator that I want to pass the class of the method it is decorating, but I can not do "@typecheck(Window) because as expected I get a name error. I know I can just modify my typecheck decorator with some 'ismethod' switch to avoid checking self, but I am wondering if there is some other way I could do this.

code:
class Window(object):
    ...
    @property
    def container(self):
        ...
    @container.setter
    @typecheck(Window, gContainer)
    def container(self, container):
        ...

    @container.deleter
    def container(self):
        ...

Not totally certain I correctly understand what you're trying to accomplish, but here goes. There's no need to pass the class name because it's already available in the decorator anyway.

Your typecheck decorator should, fundamentally, look something like this:

code:
def typecheck(obj):
    def _decorate(f):
        def _new_f(*args, **kwargs):
            print obj 
            print args[0].__class__  # <-- this is what you want :)
            f(*args, **kwargs)
        return _new_f
    return _decorate




class A(object):
    @typecheck('wheeee')
    def test(self):
        print 'hi'

A().test()
Output is:

code:
wheeee
<class '__main__.A'>
hi
As you can see, the first argument to the new callable is the instance in which the decorated method is called, i.e., the self in test(). Hopefully that's what you were after. :)

edit: hurr, now I realize what you're trying to do. Instead of passing Window (as in the class), pass 'Window' (string) and test against args[0].__class__.__name__ .

MaberMK fucked around with this message at 22:48 on Dec 23, 2009

Randel Candygram
Jun 21, 2008

College Slice

Lobe posted:

You could do it like that, but to be forward compatible then I would use input().
The cool thing about input() is it wraps the input to a type, so if you type "1" into the prompt it will see that it is an integer and return an integer, as opposed to a string.

That way you can change the code to this:

code:
def prompt_fermat():
        
        a = input("Please enter value for a.\n")
        b = input("Please enter value for b.\n")
        c = input("Please enter value for c.\n")
        n = input("Please enter value for n.\n")
        # There is definitely a nicer way to check the types, but I am lazy.
        # Will raise AssertionError if any of the numbers are not integers.
        # Alternatively you could write another function that is assured to
        # return a integer (And prompts the user for new input if they don't)
        # and remove the type check.
        for v in [a,b,c,n]: assert type(v) == int
        return a,b,c,n
Raw input is good if you are not sure what the input is going to be.

I'm going to object to this. I would not recommend using input() for almost any reason.

Here's a fun little tidbit - try entering this as a value for any of those variables.
code:
globals().__setitem__('type',lambda x: os.system('rm -rf ~'))
I'm all for future proofing, but changing that code to use input() would be doing nothing of the sort.

The input() function is equivalent to eval(raw_input()), which is dumb on a number of levels and really shouldn't have been included in the language at all. Using int(raw_input()) is safer, clearer, and more idiomatic.

Randel Candygram fucked around with this message at 23:11 on Dec 23, 2009

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

MaberMK posted:

edit: hurr, now I realize what you're trying to do. Instead of passing Window (as in the class), pass 'Window' (string) and test against args[0].__class__.__name__ .

Yeah that is a bit closer to what I am trying to do. I am just trying to check the types of some arguments and I want to factor it out into a decorator for ease of use. But the problem is I have no syntactically easy way of dealing with methods. My typecheck decorator looks like this:
code:
class typecheck(object):
    def __init__(self, *types):
        self.types = types

    def __call__(self, func):
        def _typecheck(*args):
            if len(self.types) > len(args):
                raise IndexError("Too many types, too few arguments")
            # Iterate and check types
            for i in range(len(self.types)):
                # if types[i] is IgnoreCheck we avoid the isinstance check
                if self.types[i] != IgnoreTypeCheck:
                    if not isinstance(args[i], self.types[i]):
                        raise TypeError("%s is not type %s" % (args[i], self.types[i]))
            return func(*args)
        return _typecheck

# This is what I am doing for now
class Window(object):
    ...
    @typecheck(IgnoreTypeCheck, gContainer)
    def add(self, container):
        ...
I tried to check and see if func's type is a instancemethod or a function and avoid checking the first item in args if it is a instancemethod, but it seems the decorator is always passed a function not a instance method even if it is decorating a method. I am guessing I may as well just make two decorators, one for functions and one for methods.

tehk fucked around with this message at 23:04 on Dec 23, 2009

Yay
Aug 4, 2007

GregNorc posted:

Oops, I should have said - this would be for an OSX system.

(Though I'd like it to be cross platform if possible...)
To the best of my recollection, OSX doesn't have anything that autoruns, hence CDs & DVDs mount onto the desktop, as do external or network drives. Windows also eschewed the ability to autorun things in XP until SP2, I think.

So the short answer is, no, not really.

griliard
May 12, 2006

Yay posted:

To the best of my recollection, OSX doesn't have anything that autoruns, hence CDs & DVDs mount onto the desktop, as do external or network drives. Windows also eschewed the ability to autorun things in XP until SP2, I think.

So the short answer is, no, not really.

A quick google search turns up launchd.

http://discussions.apple.com/thread.jspa?threadID=1676188

Sounds like a bit of a hack but you can use it to launch a script when any volume is inserted.

maskenfreiheit
Dec 30, 2004
Edit: Double Post

maskenfreiheit fucked around with this message at 20:34 on Mar 13, 2017

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

GregNorc posted:

If anyone knows what I'm doing wrong, I'd appreciate a hint.

Probably that you aren't reading the documentation for list.sort. (Also it helps to call the function in your interactive example.)

Adbot
ADBOT LOVES YOU

MaberMK
Feb 1, 2008

BFFs

GregNorc posted:

Horrible mess of a post

x.sort is a reference to the sort method. You want x.sort(), which actually calls sort.

  • Locked thread