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
deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Bonus posted:

Haha! Yes, clown coding is the best coding.

Eh, it seems that this func_globals is not gonna work since it pollutes the global namespace and I don't want that.
code:
>>> def foo():
...     print clowns
...
>>> dir()
['__builtins__', '__doc__', '__name__', 'foo']
>>> foo.func_globals['clowns'] = 5
>>> dir()
['__builtins__', '__doc__', '__name__', 'clowns', 'foo']

I wonder if there's a way to just affect a function's local namespace?

Is there a reason you can't make 'clowns' a global? Unless I'm misunderstanding some implementation-specific need, a global variable should probably do the trick.

Adbot
ADBOT LOVES YOU

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


karuna posted:

Hey, how do you pass a variable within a URL?

I am using urllib2

code:
urllib2.urlopen('http://www.somewhere.com/some_other_crap<$MYVAR&>')
This isn't working for me at all, i have also tried %MYVAR and ("\<\$"+"MYVAR"+"\$\>")

Any help would be great, thanks

Check out the official documentation on urllib and urllib2 (http://docs.python.org/lib/module-urllib2.html) specifically the part about urllib2.urlopen() and urllib.urlencode(). That should answer most of your questions. I've worked with these libraries extensively and have encountered pretty much every conceivable problem that could come up with them.

deedee megadoodoo fucked around with this message at 18:53 on May 10, 2008

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Spazmo posted:

Ah, that's great. Thanks very much!

Also try http://docs.python.org/lib/lib.html and http://docs.python.org/modindex.html

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Is there any way to call a function that expects a number arguments with a list of those arguments without resorting to this:

code:
import cx_Oracle as oracle
date = [int(x) for x in time.strftime('%Y,%m,%d,%H,%M,%S').split(',')]
[b]timestamp = oracle.Timestamp(date[0],date[1],date[2],date[3],date[4],date[5])[/b]
The above works fine, it just seems really inelegant.

And yes, I am aware of the many alternate methods to get a timestamp from the DBAPI, this just came up in something I was working on and I wanted to know if there was a pretty way to call the oracle.Timestamp() function without doing "date[0],date[1],..."

deedee megadoodoo fucked around with this message at 13:23 on Jun 24, 2008

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I know when I first started working with python I had read something about how to call a function with a list of arguments but I couldn't for the life of me remember what it was. Thanks to both of you.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I own Python in a Nutshell and Learning Python. I use Python in a Nutshell on an almost daily basis even though it only covers version 2.2. I just supplement with the online docs. After finishing Learning Python I never looked at it again (even though I could probably stand to brush up on some of the basics again). It sounds like you want a combination of both of these. I don't think that exists. Or if it does, I haven't found it.

The only book for any language that I can think of that really covers both of those bases is Thinking in Java/C++. If only Bruce Eckel wrote Thinking in Python (and not the electronic version available at his website, that was last updated in 2001 and isn't as comprehensive as his other works).

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Recommending Django for writing simple cgi scripts is a bit overkill don't you think? I've used a variety of methods for writing web applications and I like mod_python the most. web.py and other cgi modules feel clunky to me. I guess it's personal preference, but mod_python makes writing cgi in python feel more like python.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Milde posted:

I would personally never ever ever use mod_python if I could avoid it. Its poorly documented code caching (which can be inconsistent across the processes it loads) is probably the most frustrating thing I've ever had to deal with when testing code. And to make matters worse you can't really test applications developed for mod_python outside of mod_python. It's a loving framework too.

I absolutely love mod_wsgi, and for quick one-off development I just write WSGI apps directly and use wsgiref.simple_server. :)

I've run into the caching problem a few times, but it's really only been an issue if I'm developing on a live environment and constantly changing the code. Usually I develop on another box, deploy the app and hup apache.

As for not being able to test applications outside of mod_python, you can't really test PHP apps outside of mod_php either or JSP's outside of a java application server so I don't really understand where you're going with that one.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I ran into an issue when attempting to retrieve a slice from a container class I had created. The docs seem to imply that __getslice__() has been deprecated since 2.0 so I didn't bother to declare it in my class definition. However, once I added it my code magically worked. What gives? I can see why it would be deprecated as __getitem__ should be enough to pull a slice. But why is that bit about deprecation in the docs if I still have to declare it? Is that just wishful thinking?

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


bitprophet posted:

In a semi related note, I'm embarrassed to admit that I only really "got" PEP8 about a month or two ago (despite being primarily a Python coder for the past 4 years), and until then would sort of haphazardly mix things up. Still not a PEP8 saint but I've got the basics (e.g. foo, bar instead of foo,bar) down pat and it actually does make a difference in terms of the overall feel of the code.

I've been using Python for about 2 years and I've been using nearly everything in PEP8 since the beginning, probably due to the book I was learning from (Learning Python). The only thing I had been doing differently was using lowerCamelCase for variable names. I just switched to underscored variables and it *feels* more Pythonic. Which probably sounds weird. But it does. I don't know.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I wanted to contribute to this thread because I use python a ton. I was reading a few pages back and saw there was some confusion about how to implement decorators so I figured I'd post two that I've used fairly recently:

The first example wraps a function in some log messages that will tell you when a function starts and when it ends and what values it took as arguments. I've used this quite a bit in a threaded application to track down some bugs I encountered and changed the "print" statements to logging calls when it went into production. Just add "@log" above your function declaration to make it work.

code:
def log(function):
    from itertools import chain
    def wrappedFunction(*v, **k):
        name = function.__name__
        print "starting %s(%s)" % (name, ", ".join(map(repr, chain(v, k.values()))))
        output = function(*v, **k)
        print "finished %s(%s)" % (name, ", ".join(map(repr, chain(v, k.values()))))
        return output
    return wrappedFunction

This is a very simple decorator I used the other day to track the execution time of a bunch of functions to figure out where the bottleneck was in a piece of code. At the end of execution you can inspect the "timeTable" variable and it will contain a list of execution times for every call to each decorated function.

code:
timeTable = {}

def functionTimer(function):
    def timedFunction(*v, **k):
        start = time.time()
        output = function(*v, **k)
        stop = time.time()
        try:
            timeTable[function.__name__].append(stop - start)
        except KeyError:
            timeTable[function.__name__] = [stop - start]
        return output
    return timedFunction

Hopefully somebody learns something or gets some use out of these.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Can anyone explain in small words how the gently caress to use ZSI to access a SOAP service with WSDL?

Using the SOAPpy module this is simple as all hell...

code:
import SOAPpy

service = SOAPpy.WSDL.Proxy('http://localhost/service/wsdl')
but for some reason I just don't understand the ZSI way to do this.

send ha;lp

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


tef posted:

I have never had any success with python soap implementations :(

They seem old, unmaintained and dependant on even more unmaintained libs.

I would much rather use xmlrpc but that option isn't available. It makes me a sad panda.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


HatfulOfHollow posted:

Can anyone explain in small words how the gently caress to use ZSI to access a SOAP service with WSDL?

Using the SOAPpy module this is simple as all hell...

code:
import SOAPpy

service = SOAPpy.WSDL.Proxy('http://localhost/service/wsdl')
but for some reason I just don't understand the ZSI way to do this.

send ha;lp

I figured out that the actual issue I was having is that ZSI makes assumptions about the format of the wsdl document. ZSI tries to read ahead on certain node types because it assumes that those nodes have children, which causes all kinds of errors. It's some hosed up xml parsing that makes no sense. Just walk the doman tree you loving loonies.

In any case I switched to suds. It does everything I need (correctly) and seems to be recent and/or at least maintained a bit better. It even supports http proxies and wsdl that doesn't live at the same address as the service.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I've done something stupid but for the life of me I can't figure out what.

code:
#!/bin/env python

import sys, re
from os import popen
from optparse import OptionParser

class Process(object):
    def __init__(self, pid, ppid, etime, cmd):
        self.pid = pid
        self.ppid = ppid
        self.etime = etime
        self.cmd = cmd

class JavaProcess(Process):
    def __init__(self, pid, ppid, etime, cmd):
        super(JavaProcess, self).__init__(pid, ppid, etime, cmd)

        for key, string in [('instance','weblogic.Name=(.*?) '), ('jvm','/opt/bea/(.*?)/bin/java'), ('weblogic','wls.home=/opt/bea/(.*?)/server')]:
            temp = re.compile(string).findall(self.cmd)
            if temp:
                setattr(self, key, temp[0])
            else:
                setattr(self, key, '-')


class ProcessList(dict):
    def __init__(self):
        self.refresh()
        print self

    def refresh(self, top=True):
        self = {}

        #do a `ps` and turn output lines into processes
        ps = popen('ps axww -o "pid ppid etime args" | grep java | grep -v grep','r').read()
        ps = ps.split('\n')[:-1]

        for line in ps:
            pid, ppid, etime, cmd = line.split()[:3] + [' '.join(line.split()[3:])]
            self[pid] = JavaProcess(pid, ppid, etime, cmd)

        #get cpu and memory usage data from `top`
        if top:
            top_output = popen('top bn1 | grep java','r').read()
            top_output = top_output.split('\n')[:-1]

            for line in top_output:
                line = line.lstrip().rstrip().split()
                if self.has_key(line[0]):
                    setattr(self[line[0]], 'tcpu', line[8])
                    setattr(self[line[0]], 'tmem', line[9])

        #determine whether or not a pid is a parent process
        #only matters when java threads are shown as individual processes
        def _setParent(pid):
            if self[pid].ppid in self.keys():
                _setParent(self[pid].ppid)
                setattr(self[pid], 'parent', False)
            else:
                setattr(self[pid], 'parent', True)

        for pid in self.keys():
            _setParent(pid)


def main(argv=sys.argv[1:]):
    parser = OptionParser(usage="usage: %prog [options] <list of instances or pids>", version="%prog 2.0")
    parser.add_option('-a', '--all', action='store_true', default=False, dest='all', help='show all pids, displays threads and child processes')
    parser.add_option('-p', '--pipe', action='store_true', default=False, dest='pipe', help='display output in pipe-delimited format')
    options, arguments = parser.parse_args(argv)

    process_list = ProcessList()

    if options.pipe:
        lineout = '%(pid)s|%(etime)s|%(tcpu)s|%(tmem)s|%(instance)s'
    else:
        print 'PID     Uptime       %CPU %MEM Instance                              '
        print '------- ------------ ---- ---- --------------------------------------'
        lineout = '%(pid)-7s %(etime)12s %(tcpu)4s %(tmem)4s %(instance)-38s'

    for p in process_list:
        if options.all:
            print lineout % process_list[p]
        elif p.parent:
            print lineout % process_list[p]


if __name__=='__main__':
    main()
The variable "self" is what it should be in ProcessList.refresh() but after invoking the method, self is an empty dictionary. I did something dumb but I don't know what.

deedee megadoodoo fucked around with this message at 17:12 on Jun 14, 2009

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


tef posted:

I don't think self = {} does what you think it does

code:
>>> foo = {}
>>> def whatdoyouthinkyouaredoing(obj):
...     obj = {}
...     obj['a'] = 'b'
...     print obj
... 
>>> whatdoyouthinkyouaredoing(foo)
{'a': 'b'}
>>> foo
{}
>>> def ithinkyoumeanthis(obj):
...     obj.clear()
...     obj['a'] = 'b'
...     print obj
... 
>>> ithinkyoumeanthis(foo)
{'a': 'b'}
>>> foo
{'a': 'b'}
>>> 


poo poo. You're right. I was trying to empty the ProcessList dict and hosed myself.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


CentOS has a server distribution that fits on a single CD. It doesn't include x windows so you should probably be comfortable with the command line before you download it.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


LuckySevens posted:

Is there an alternative to mod_python, since I'm running 2.6? I found some vague info from google on how to alter the install, but I can't get it to work.

It depends on what you're trying to do with it. If you're looking to find something like the python publisher handler you can probably use zope but I've never used it personally so I can't say what the real differences are. If you wanted to use mod_python to access apache via handlers for each step I don't think there is an alternative to mod_python. But if all you're trying to do is write CGI scripts, you can just stick a "#!/bin/env python" at the top of your script and drop them in a directory with +ExecCGI.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


PrinceofLowLight posted:

Newbie with python. I'm trying to automate a repetitive task, analyzing some data that's too big to put in Excel. The text files range from 6-30 megs. It usually crashes notepad too, but opens with wordpad. Will Python be able to handle this?

The lines are arranged like so:

8.79669 5 5 5 5


I want to make it that so that python associates each column with its row. Then, if the third column is 5, to take the next 20 values of the third column and then average them, then spit that out into an output file with a small header. I'm not sure how to go about this.

Thanks!

Python isn't a front end like notepad. You'll be able to open any file as long as your machine has the memory for it and you've coded the operations correctly.

PS - notepad can't open the file because it has a limit on file size. Wordpad has a much higher limitation, if it has one at all.

edit: also, for what you're describing you really only need to read one row at a time, which is fairly trivial.

deedee megadoodoo fucked around with this message at 21:59 on Jul 5, 2009

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


ATLbeer posted:


This is an odd question. I want to abuse the list type...

I need all the fun functionality of lists (slicing, etc) but, want to use it almost like a dictionary with a defined index (not starting at 0).

Basically I want to store something in a list but, use an epoch time as the index.

so

x = []
x[1247787135] = "yes please"

(Oh.. and I am planning on filling in gaps. So it will be a list with no gaps.)

First idea at a solution: [I guess subclassing the list object and adding an attribute called "start_time" and then override the get set functionality?]

:)
http://pytseries.sourceforge.net/contents.html

Since a tuple is immutable you can wrap your time in parens and use a normal dictionary.

x = {}
x[(12345678910,)] = "hello thar"

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


checkeredshawn posted:

It turns out that even though I figured out the pygtk problem I had asked about above, I can't figure out one of the other problems that goes like this:

If I have a text file that has something like this in the contents:

TEMPLATE0$ TEMPLATE1$
TEMPLATE0$ blah blah TEMPLATE4$

and a list like this: ['zero', 'one', 'two', 'three', 'four']

and I would like the result to look like:

zero one
zero blah blah four

is it possible to pass through and replace each one of those with the string given at the index of the list, provided by the number immediately following the TEMPLATEs?

I know you can use grouping to get those numbers, for example, like this:

code:
p = re.compile('TEMPLATE(P?<num>\d+)$')
for line in lines:
  print p.match(line).group('num')
But I have no idea how to go through and do multiple replacements on the lines. Any help would be greatly appreciated.

Instead of using a list, if you use a dictionary you can do this pretty simply.

code:
data = {}
data["0"] = "zero"
data["1"] = "one"
data["2"] = "two"
data["3"] = "three"
data["4"] = "four"

print "%(0)s %(4)s" % (data)
print "%(0)s blah blah %(4)s" % (data)

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Sparta posted:

I want to develop a small ad network system, I've worked out the logic behind how it will work and have mapped out functions, checks, etc. Problem is I am not really a programmer. I'm the opposite of an average programmer: I don't know poo poo about syntax but I know how to keep good practices (writing up specs, keeping view, model, and data seperate, making sure user input is cleansed, etc.

I have heard some pretty great things about python and specifically Django.

What would be a good book to read regarding this? People keep telling me to read the Python Docs, but I can't really learn by reading docs on my monitor, I need printed word.

Any recommendations for good, hands on, learn-by-doing books on Python and Django for someone who knows how to code well but doesn't know how to code?

I've never used django but it might make sense to pick up a basic python book before diving into a framework. I started with "Learning Python" but have heard good things about "Dive into Python." http://www.pythonchallenge.com is worth a look to get some hands on experience. Once you have the basic understanding you should pick up one of the many django books. Someone can call me out on this if they feel it's bad advice.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


TheMaskedUgly posted:

http://pastebin.com/m7eea8442

There's the first program. The original program was identical except it went all the way to the 10th copy and finished. To make the two programs, I copied the beginning section and initialising crap, and then cut out the last 5. It works now in two sections.

I'm pretty sure this replaces that entire monstrosity:

code:
## Contains the File locations for all necessary files
Template = r"c:/Documents and Settings/Name/Desktop/HTMLiser/Input/Template.txt"
TitlesFile = r"c:/Documents and Settings/Name/Desktop/HTMLiser/Input/Titles.txt"
ParagraphsFile = r"c:/Documents and Settings/Name/Desktop/HTMLiser/Input/Paragraphs.txt"
TracerFile = r"c:/Documents and Settings/Name/Desktop/HTMLiser/Input/TracerImages.txt"
ReffNoFile = r"c:/Documents and Settings/Name/Desktop/HTMLiser/Input/ReffNo.txt"
OutputFiles ["C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-A-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-B-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-C-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-D-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-E-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-F-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-G-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-H-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-I-Zuneta1.htm",
"C:/Documents and Settings/Name/Desktop/HTMLiser/Output/12-000211-J-Zuneta1.htm"]

template = open(Template).read()
title_file = open(TitlesFile)
paragraph_file = open(ParagraphsFile)
tracer_file = open(TracerFile)
reffno_File = open(ReffNoFile)


for file in OutputFiles: 
    title = title_file.readline()
    paragraph = paragraph_file.readline()
    tracer = tracer_file.readline()
    reffno = reffno_file.readline()

    
    output_file = open(file, 'w')
    output_file.write(template.replace("@@@@@TITLE@@@@@", title).replace("@@@@@PARAGRAPH@@@@@", paragraph).replace("@@@@@TRACERIMAGE@@@@@", tracer).replace("@@@@@REFERENCENUMBER@@@@@", reffno))
    output_file.close()

title_file.close()
paragraph_file.close()
tracer_file.close()
reffno_file.close()
And this could even be cleaned up a bit.

deedee megadoodoo fucked around with this message at 19:47 on Aug 12, 2009

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


TheMaskedUgly posted:

You people and your making me look bad. I'll have a look over those, and if they work, I love you. Even if they don't I appreciate the effort. Thanks, really.
Any ideas why it stopped before the end, or should I just chalk that up to I suck at python and it got angry at that?

E: Just checked, both are perfect; I'm indebted to you.

That's actually surprising. I didn't even test mine. I wrote it in notepad after tracing the original script in my head. I'm a badass.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


NadaTooma posted:

Yeah but mine calls strip() so it doesn't embed extra newlines. :v:

creating a working script without testing > using strip()

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Habnabit posted:

Twisted! Anything else is just dumb. (Short of reimplementing twisted yourself, which is dumb for other reasons.) Threading would just add a lot of overhead: code complexity overhead and CPU overhead both.

I can write a multi-threaded application with no problem but for some reason twisted just confuses the hell out of me. I think it's the layer of abstraction. Not seeing exactly what's going on behind the scenes makes it harder for me to understand.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


TheMaskedUgly posted:

Say I've got a list of values, in this form:
["reference-2-000111-A", "reference-2-000111-B", "reference-2-000111C"]
So there's three sections to each list, the word reference which is common to all values like this, the number which is common to all the values in this set, and the letter which is difference for each.
How can I separate a value in the list, so I can use the number elsewhere. How can I get the two parts of the number on their own if its in a list, basically.

If every value starts with the word "reference," has a string of numbers and then a single letter at the end you can extract the number and letter with this...

code:
>>>data = ["reference-2-000111-A", "reference-2-000111-B", "reference-2-000111-C"]
>>>[(i[10:-2],i[-1]) for i in data]
[('2-000111', 'A'), ('2-000111', 'B'), ('2-000111', 'C')]

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


nbv4 posted:

Anyone have any experience with the csv module? I have a csv file that, after so many lines, switches headers. Like this:

code:
head1,head2,head3
12,172,34
453,568,235
342,834,2234
...
head4,head5,head6,head7
564,3576,3546,322
356,332,556,789
3435,435,76,980
I have a DictReader that is defined with the first header line, but I can't figure out how to handle setting the new header to the same DictReader. I know how to test for when I get to a new header row during iteration, I just can't figure out how to give the DictReader the new list of headers.

How about reading through the whole file first and marking the header sections since you know how to identify them. Then seek(0) and start reading until you reach your next header. At that point recreate your DictReader and it might pick up the next header. Not sure if this works, but its worth a shot.

Alternatively subclass "reader" and alter the next() method to inspect the new line to see if it's a header.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


duck monster posted:

Yay debian!

I love it when people quote things without context.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


duck monster posted:

Whats there to say? 2.6 won't be in the next debian.

And?

[root@ashprdmon04 nagios]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.3 (Tikanga)
[root@ashprdmon04 nagios]# rpm -q python
python-2.4.3-24.el5

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


duck monster posted:

Well thats poo poo too. Its a problem, because it slows adoption of 2.6/3.0 and that means python devs have to keep supporting legacy code bases, and provides disincentives for people to modernise their code for the superior 2.6/3.0 branches.

I completely agree. But I've just started accepting that Redhat is going to be slow to adopt new versions of anything, even if it offers vast improvement. Hell, we're still building some boxes with RHEL4 and those REALLY suck...

-bash-3.00$ cat /etc/redhat-release
Red Hat Enterprise Linux AS release 4 (Nahant Update 4)
-bash-3.00$ rpm -q python
python-2.3.4-14.2

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I just want to add the one of the main problems I encountered with twisted is that in every release they are drastically changing the API. Because of this, the twisted book and a lot of the examples you find online are hilariously/frustratingly dated.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I'm trying to write a handler using mod_python that will process all requests on a specific directory and perform some action before serving the originally requested file. Is this possible? I'm really only familiar with the mod_python publisher which is a completely different animal.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


aSSbAG. posted:

Hey guys, just decided to learn python. I used to consider myself a pretty good VB6 programmer, and was waiting for microsoft to realize what a huge mistake they made with VB.net, yeah I got tired of burning that torch.

I downloaded and installed the latest version from python.org and since then I have been doing some reading, haven't gotten any further then "hello world" but that's fine by me, I'm in no big hurry. I then find this thread which led me to pyglet which sounds bad as hell. So I download it and try to install:




3.1 < 2.4? :ughh:

Yeah I'm gonna love python :(

Python 3.0 is a huge departure from 2.x and as such many libraries need to be updated to do things the new way. You need to either get the latest 2.x release or wait until Pyglet supports 3.x. I'm not sure why that information isn;t front and center on the Pyglet website. But yeah, that's a pretty terrible message that doesn't describe the actual problem.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Avenging Dentist posted:

Also I really question the notion that Py3k is a "huge departure" from Python 2.x. There are some important differences, but it's still more-or-less the same syntax, and the number of stuff that changed (as opposed to being added) could probably be summed up in a page.

Probably. I'm still developing for 2.3 so for me it feels much bigger than for everyone else.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Thermopyle posted:

Shelf is a shelve. I'm storing my object on disk.

Save isn't manipulating it's own object per se...it's storing the object in the shelve.

I'm confused why you would want to store the object in the shelf. It really doesn't make much sense to me.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Thermopyle posted:

That's how the shelve module works.

No I mean, why do you need a save method? Why can't you just do

code:
shelve[name]=obj
wherever you need to update? It just seems kind of unnecessary.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


xmlrpclib is built in and standard and easy as gently caress to use. You can even use it inside apache if you don't want to write your own daemon.

deedee megadoodoo fucked around with this message at 21:34 on Aug 10, 2013

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


You need to read up on scope.

The simplest explanation is that the variables within a certain scope (in this case the function) only exist within that scope. However, the function has access to outside variables in the greater scope.

So for example:

code:
def test(myvar):
    print myvar, x

x = "goon"
test("hello")
will actually work because the variable x is available to the function.

however

code:
def test1(myvar):
    y = myvar

def test2(myvar):
    print myvar, y


test1(2)
test2("goon")
will fail because "y" only exists within test1 and is not accesible outside of that functions scope.

There is a lot more to it, but hopefully that makes sense.

Adbot
ADBOT LOVES YOU

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Couldn't you encapsulate your code within a class then pickle it and send it across via rpc? I'm pretty sure I did something similar for a custom nagios NCSA replacement a while back.

  • Locked thread