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
.Spec
Oct 4, 2001

I've got an interesting problem that I'd like to see if anyone can provide me some guidance on. I want to preface this all by saying that I've been learing Python as my first language and I'm still pretty new at it so please bear with me.

We have an AD service account at work that requires it's password to be reset every morning at 8 AM. We have a script that currently does this but it's really finicky and fails more often that not. For this reason I decided to try and rewrite it in Python as a little project. So far I've only gotten as far as creating something that will generate a password that meets the complexity requirements:

code:
import random

password = ""
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
punctuation = "!@#$%^&*()"

while len(password) < 9:
	password += random.choice(letters.lower())
	password += str(random.randrange(0,10,1))
	password += random.choice(punctuation)

password = list(password)
random.shuffle(password)
password = "".join(password)
print password
Easy enough. The new problem I'm running into is that I need a way to bind to a domain controller and change the password. In our current script kpasswd is called to do this and as luck would have it a python module exists that interfaces with kpasswd but it's got gently caress all documentation so I haven't had any luck getting it working.

That all being said has anyone used that particular module before and could give me some guidance with it or alternatively can you think of some other way for me to bind in order to make changes to the account?

Adbot
ADBOT LOVES YOU

tbradshaw
Jan 15, 2008

First one must nail at least two overdrive phrases and activate the tilt sensor to ROCK OUT!

BROHAMMER posted:

[...] AD service [...] or [...] some other way for me to bind in order to make changes to the account?

The ActiveState guys that do the ActivePython distribution provide a pretty seemless wrapper library for the native COM objects. You'll want to use that to give yourself access to the native ADS and WSH objects and work from there.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

outlier posted:

*thumps head against desk*

An obscure bug had been plaguing me for a while and I've just work it out. My program had a buffer that I was writing to which would sometimes complain along the lines "ascii encoder can't accept unicode". I fiddled with the buffer, changed parameters, tried to replicate it at the prompt to no avail.

The root problem: StringIO and cStringIO behave differently. Amongst these differences, cStringIO cannot handle unicode strings that can't be converted to ASCII. So you shouldn't use (and really can't use) unicode with cStringIO. It might work, but it might throw it back. Blergh.

There are some other bugs or wierdnesses that have been known for a few years, some of which are WONTFIX. Blergh.

StringIO and cStringIO in 2.6 are byte-based -- if you're trying to insert Unicode strings, it's best to encode them to UTF-8 before writing them. Some Unicode strings might work, but that behavior shouldn't be relied upon (as you've discovered).

In Python 3, StringIO operates only on Unicode, and BytesIO only on bytes, so this confusion doesn't exist.

Manner Please
Dec 21, 2005

Short easy question:

So I'm trying to learn PyGame, and in the aliens example I come across this:

code:
class Player:

  def __init__(self):
     self.image = self.images[0]


...

Player.images = load_image(whatever)
Specifically, what I'm confused by is why it's

self.image = self.images[0]

and not

self.image = Player.images[0]

because to me it looks like you are assigning an instance member to a class member, so it would make sense you would scope the class member by the class name, and not by self. Looking it up, it seems you can do both, but I don't understand why it is ever done this way.

Any explanation?

wins32767
Mar 16, 2007

Manner Please posted:

Any explanation?

Off the top of my head, I suspect you'd want to preserve your ability to reuse that code in a subclass.

IE:
code:
class SpecialPlayer(Player):
   pass

SpecialPlayer.images = load_image(special_whatever)

wins32767 fucked around with this message at 17:54 on Jul 30, 2009

Lurchington
Jan 2, 2003

Forums Dragoon
here's something I'm dealing with now, that I'm picking up an old project where I went hog wild with separate modules for everything:

What's the best way to deal with command option information from something like optparse when your classes are in different files and need to see something?

Currently, I'm passing the parsed tuple from optparse into the constructor of classes I know need it.
Originally, I did an import from the main file and used them as globals in each function.

similar to:

from main_file import parsed_cl_options, parsed_cl_arguments
where:
(parsed_cl_options, parsed_cl_arguments) = OptionParserInstance.parse_args()



I had also considered reparsing the command-line in each function, but that seemed bad.

Meat Beat Agent
Aug 5, 2007

felonious assault with a sproinging boner
Alright I'm kind of getting kicked in the rear end trying to use Python for CGI scripting with my Hostgator account. Even a basic "hello world" script yields a 500 error.

Here's what http://revenant1.net/cgi-bin/test.py looks like:

code:
#!/usr/bin/env python

print "Content-Type: text/plain;charset=utf-8\n"
print "Hello World!"
and even that doesn't work right.

The server's running Python 2.4 last time I checked, in case that's relevant here for some reason.

spankweasel
Jan 4, 2006

Try a couple of things:

1: check the permissions of the file. Make sure the script is executable.

2: change the file to test.cgi to see if apache (assuming) isn't aware of .py files

3: add this code:

import sys
sys.stderr = sys.stdout


so you can see anything sent to stderr on the webpage. If you don't redirect stderr, it goes to the web logs.

Meat Beat Agent
Aug 5, 2007

felonious assault with a sproinging boner
I already checked the file permissions beforehand, it was already set to 755 so that wasn't the issue.

I tried both renaming it to test.cgi, and redirecting sys.stderr; no matter what I still get the 500 error here (.cgi) and here (.py) Both of these have stderr redirected to stdout.

:bang:

king_kilr
May 25, 2007
Why are you using CGI? I didn't realize anyone still used it.

Meat Beat Agent
Aug 5, 2007

felonious assault with a sproinging boner
I don't plan on using it a whole lot, I mostly just want to figure out why the hell it's not working in the first place.

baquerd
Jul 2, 2007

by FactsAreUseless

king_kilr posted:

Why are you using CGI? I didn't realize anyone still used it.

Are you sure you know what CGI is? It's a standard in, for example, apache, used for simple scripts across the world.

king_kilr
May 25, 2007

quadreb posted:

Are you sure you know what CGI is? It's a standard in, for example, apache, used for simple scripts across the world.

Umm, it may be a standard, but it's an old crappy one, designed in such a manner to inhibit both good programming practice and speed. You'll notice mod_php, mod_perl, mod_python, mod_wsgi, mod_fcgi, etc. are a good bit more popular.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
Yeah if memory serves me correctly you're firing up a new python process for every hit to the page with straight cgi.

Meat Beat Agent
Aug 5, 2007

felonious assault with a sproinging boner
The only reason I'm using CGI for the time being is because I don't have access to mod_python with my current shared hosting plan, although I do have FastCGI available.

I know this isn't the CGI megathread, but do any of you have experience using FastCGI? Is it worth using?

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

Lurchington posted:

What's the best way to deal with command option information from something like optparse when your classes are in different files and need to see something?

Currently, I'm passing the parsed tuple from optparse into the constructor of classes I know need it.
Originally, I did an import from the main file and used them as globals in each function.

similar to:

from main_file import parsed_cl_options, parsed_cl_arguments
where:
(parsed_cl_options, parsed_cl_arguments) = OptionParserInstance.parse_args()

Note that there's nothing especially Pythonic about this problem, it's a common design issue. There's a few ways you can go around this:

1. The central command class or function gathers the options and distributes them to more peripheral classes. You parse the options and then call "MyAppModel.set_options", which calls "DisplayController. set_options" and "DataReader. set_options" which may in turn call "DataParser. set_options", etc.

Advantages: centralised control of options, no part of the program can see or effect options that don't concern it.

Disadvantages: If you change or expand options, you have to walk your changes down the chain. And what if two parts of a program share options? Probably works better with smaller programs.

2. Have some sort of global settings / options object or class. See Django's settings and conf machinery for an example.

Advantages: easy. Everything can get at everything. Scales well.

Disadvantages: ohmigod, don't you now that globals are bad! Everything can get at everything!

I'd tip my hat towards the second for most cases, especially as a program grows in size.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

acker posted:

The only reason I'm using CGI for the time being is because I don't have access to mod_python with my current shared hosting plan, although I do have FastCGI available.

I know this isn't the CGI megathread, but do any of you have experience using FastCGI? Is it worth using?

(man, everyone thinks mod_python is the right apache module to use. mod_wsgi is The One.)

Your best bet is to write the application in WSGI or use a WSGI framework, and then use a WSGI-fastcgi or WSGI-CGI adapter. You'll have more deployment options later if you want/need to change it, as well as be able to test out your application a little easier.

nbv4
Aug 21, 2002

by Duchess Gummybuns

acker posted:

Alright I'm kind of getting kicked in the rear end trying to use Python for CGI scripting with my Hostgator account. Even a basic "hello world" script yields a 500 error.

Here's what http://revenant1.net/cgi-bin/test.py looks like:

code:
#!/usr/bin/env python

print "Content-Type: text/plain;charset=utf-8\n"
print "Hello World!"
and even that doesn't work right.

The server's running Python 2.4 last time I checked, in case that's relevant here for some reason.

I think python is just hosed on hostgator. Back when I had an account I looked into getting some python stuff going, but eventually decided to just use another hosting service after reading all about people having troubles getting it working. Check their forum. I don't think a single person has gotten it working.

Meat Beat Agent
Aug 5, 2007

felonious assault with a sproinging boner

nbv4 posted:

I think python is just hosed on hostgator. Back when I had an account I looked into getting some python stuff going, but eventually decided to just use another hosting service after reading all about people having troubles getting it working. Check their forum. I don't think a single person has gotten it working.

This is what I was afraid of. :(

I had looked around the support forums a few times but every Python related thread I found pretty much boiled down to "use mod_python" which is only available if you're on a dedicated server.

As for WSGI/fastcgi, that looks doable, I'll probably check that out later today and see if I get anywhere. Thanks for the suggestion.

duck monster
Dec 15, 2004

You can use Django with fastcgi

http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/

Also if you must do cgi, make sure your setting your headers right.\

But yeah, go get yourself an account with something like slicehost so you can get your setup juuuust right. Your time is more valuable than making GBS threads around with crappy $5 hosts. A non crappy $20 vhost pays itself off in the first hour of saved time.

king_kilr
May 25, 2007

duck monster posted:

You can use Django with fastcgi

http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/

Also if you must do cgi, make sure your setting your headers right.\

But yeah, go get yourself an account with something like slicehost so you can get your setup juuuust right. Your time is more valuable than making GBS threads around with crappy $5 hosts. A non crappy $20 vhost pays itself off in the first hour of saved time.

Or if you prefer shared hosting/the low cost go with webfaction.

Thermopyle
Jul 1, 2003

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

Ok, I've decided to just make myself learn wtf classes are good for.

I'm designing a script to take entries from my google reader shared items rss feed and do various things with each item like post it to a Twitter feed, Facebook, post it on a forum, etc...

The problem is that classes seem kind of weird to me, and I'm having a hard time thinking about them with the right mind-set.

This is my current thinking about some classes to use:

  • A class for an item in the rss feed. Have various methods for doing the things I mentioned above.
  • A class for the rss feed. The constructor will take the url to the feed, fetch it, and create instances of the above class for each entry in the feed.

The second item I'm a little confused about. On the one hand it seems like I should make it a class because classes are cool, but on the other hand, I don't really see a reason for it to be a class as the things it does should only be done once each time my script is run.

Basically, I'm just looking for some ideas and thoughts about how people with experience would design such a project.

Meat Beat Agent
Aug 5, 2007

felonious assault with a sproinging boner
Why not just have a function that takes the URL and returns a list of instances of the item class?

Thermopyle
Jul 1, 2003

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

acker posted:

Why not just have a function that takes the URL and returns a list of instances of the item class?

Basically because I'm a noob to OOP and didn't know if it was bad form to mix functions and classes in such a manner. Of course, now that I think about it, I use regular Python objects all the time...

tef
May 30, 2004

-> some l-system crap ->

Thermopyle posted:

Ok, I've decided to just make myself learn wtf classes are good for.

Models of data. However, in other languages they are the only major component. (I.e in java, they do namespacing too, etc...) so you end up using classes everywhere.

quote:

I'm designing a script to take entries from my google reader shared items rss feed and do various things with each item like post it to a Twitter feed, Facebook, post it on a forum, etc...

As the poster above said, use a list of Item classes.

In python it's easier to use the built in data types than creating your own.

quote:

The problem is that classes seem kind of weird to me, and I'm having a hard time thinking about them with the right mind-set.

In a language like python, use classes where they are convenient. This frequently means custom data types with a handful of methods. (And It is often easier to use functions in python than methods.

The big thing with classes is inheritance - being able to incorporate other classes into a new one.

quote:

Basically, I'm just looking for some ideas and thoughts about how people with experience would design such a project.

If you're wanting a more common oo experience try Java or C#, or if you're feeling more traditional you can use Squeak/Smalltalk.

The python oo experience is more of an option when coding python.

tef
May 30, 2004

-> some l-system crap ->
For example, if you wrote a calculator, you could model the operations like so:

code:
class Add:
    def __init__(self, left, right):
        self.left = left
        self.right = right
    def eval(self):
        return self.left.eval() + self.right.eval()


class Num:
   def __init__(self, num):
       self.num = num
   def eval(self):
       return self.num


calc = Add(Num(2),Num(2))

print calc.eval()
In a stricter language, we would introduce an interface or an abstract class, and both Add and Num would inherit from it, as to be the same type.

This can also be written as:

code:

def add(x,y):
    return x+y

ops = {"add": add}

def eval(x):
    if hasattr(x,'__iter__'):
        return ops[x[0]](*x[1:])
    else:
        return x

print eval(("add",2,2))



With the classes, you can keep the data specific code with the data itself.

Avenging Dentist
Oct 1, 2005

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

tef posted:

In a stricter language, we would introduce an interface or an abstract class, and both Add and Num would inherit from it, as to be the same type.

But Python already has abstract classes. :downs:

tripwire
Nov 19, 2004

        ghost flow

Avenging Dentist posted:

But Python already has abstract classes. :downs:
Sorry for being dumb but is this actually an idiom in python? It seems like it does what it advertises...

Lurchington
Jan 2, 2003

Forums Dragoon

tripwire posted:

Sorry for being dumb but is this actually an idiom in python? It seems like it does what it advertises...

if I did something like:


from __builtin__ import pass as abstract


at the top of that file, it wouldn't error :v:

Here's an actual PEP on the subject

edit: and I just noticed there was a Python Module of the Week on abstract base classes: http://blog.doughellmann.com/2009/07/pymotw-abc-abstract-base-classes.html

Lurchington fucked around with this message at 03:34 on Aug 4, 2009

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

tripwire posted:

Sorry for being dumb but is this actually an idiom in python? It seems like it does what it advertises...

http://norvig.com/python-iaq.html

:v:

king_kilr
May 25, 2007

tripwire posted:

Sorry for being dumb but is this actually an idiom in python? It seems like it does what it advertises...

No, it's not. raise NotImplementerError is the correct idiom.

tripwire
Nov 19, 2004

        ghost flow

king_kilr posted:

No, it's not. raise NotImplementerError is the correct idiom.

Cool, thanks :)

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

king_kilr posted:

No, it's not. raise NotImplementerError is the correct idiom.

code:
def abstract():
    import inspect
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    raise NotImplementedError(caller + ' must be implemented in subclass')
As Norvig taught us.

spankweasel
Jan 4, 2006

I've tried to look online for this information but so far I've been unsuccessful.

I am attempting to implement a rather large API. The method we're going with is to use standard getters and setters functions. Naturally this places right into the property() built-in.

What I have been unsuccessful in coding / finding on google is a decorator or metaclass that allows to me condense the fget(), fset(), fdel() and doc arguments to property () so that I don't have classes completely loaded with dozens of (basically) duplicate functions. I see from the property link that I can use @property as a decorator for the fget(), but I'd really really like to have a way to do it for all 4 arguments to property ().

Metaclasses get into python internals that I simply do not understand but the metaclass page says this:

quote:

The potential uses for metaclasses are boundless. Some ideas that have been explored including logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.
(emphasis is mine).

Has anybody explored this? I'm tearing my hair out trying to understand metaclasses.

Ragg
Apr 27, 2003

<The Honorable Badgers>
If you're going to use set/get methods for all attribute access, that's not what property is for. Property is for special behavior on regular attribute access, so obj.attr = "foo" calls the setter method you've defined for attr instead of simply doing setattr(obj, "attr", "foo"). Unless that's what you meant. In which case you don't have to implement methods for the attributes that aren't going to do anything special on getting/setting.

Now if you're talking about changing the default behavior of attribute access, you could override setattr/getattr, I think.

tef
May 30, 2004

-> some l-system crap ->

spankweasel posted:

I've tried to look online for this information but so far I've been unsuccessful.

Naturally this places right into the property() built-in.

I see from the property link that I can use @property as a decorator for the fget(), but I'd really really like to have a way to do it for all 4 arguments to property ().

From the page:

code:
class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
You will need 2.6 to do x.setter, x.deleter

Ragg
Apr 27, 2003

<The Honorable Badgers>
On the other hand, if you wanted to automatically make a bunch of getter/setter methods for your class maybe something like this would work:

code:
def getter(self, attrname):
    def func():
        return getattr(self, attrname) #this can of course be changed to some crazy custom behavior
    return func

class C(object):
    def __init__(self):
        for attr in ["x", "y", "z"]:
            setattr(self, attr, None)
            setattr(self, "get" + attr, getter(self, attr))
Not sure if this is the right way to go about this, or even why you would want to do it. Or whether it's what you want at all. But whatever.

Kire
Aug 25, 2006
Gosh, I've heard people say to use Netbeans or Eclipse, but I'm trying to load some simple scripts that refuse to work in IDLE (pygame's event.QUIT has never worked when I create and run things in IDLE, and I've been told it might be a Tkinter issue) and holy cow is this impossible. Both Netbeans and Eclipse adamantly refuse to let me run a script. In Netbeans, it just says "Hello" in a sub-window (not part of the program I'm trying to run) and eclipse just tells me it can't do it: "The selection cannot be launched, and there are no recent launches."

I don't care if using IDLE means that I have to repeatedly force-quit every time I use pygame...at least I can edit/run things.

Scaevolus
Apr 16, 2007

Kire posted:


Try WingIDE.

Adbot
ADBOT LOVES YOU

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Before 2.6 I did
code:
def prop(f):
   fget, fset, fdel = f()
   return property(fget=fget, fset=fset, fdel=fdel, doc=f.__doc__)
and in a class

code:
...
    @prop
    def f(): # NOTA BENE: lack of self argument
        "lorem ipsum"
        def fget(self): #self here, though
            return self.whaeva
        ... etc ...
        return fget, fset, None # returning None disables a feature
...
But if you have Python 2.6, do what Tef said. In fact, all of you do what Tef says or my crew will jump you.

  • Locked thread