Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-27 Thread Sean Carolan
> But, where did you get the idea that you could build Python RPMs using
> $python setup.py bdist_rpm ? I thought that was only limited to
> building RPMs for python packages (including extensions), but not the
> Python interpreter itself. Please correct me if i am wrong.
>

Ok, so it's only for module distributions?  I assumed it could package
Python itself as well, because it creates a *.spec file that reads like
this:

%define name Python
%define version 2.7.3
%define unmangled_version 2.7.3
%define release 1

Summary: A high-level object-oriented programming language


> Okay, here is something for you to try in the meantime. Download the
> Python 2.7 SRPM (source RPM) from
> http://koji.fedoraproject.org/koji/packageinfo?packageID=130. May be
> the F17 version.
> Extract it to get the source files, patches and the SPEC file.
>

Thank you, I will try this today.  In the meantime I have started a thread
on the "distutils" mailing list, so as not to spam "Tutor" with my build
woes.

regards,

Sean
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
> Given that most folks on this list are only learning Python its pretty
> unlikely that they are building bespoke RPMs...
>
> You might find more experience of RPM building on the general Python
> mailing list/newsgroup.


Sorry 'bout that.  I'll follow up with the bug report and possibly the
general list as well.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
> If so, what was your secret?
>
>
I tried running this again with strace, and it looks like it's finding the
pyconfig.h file:

open("/usr/local/include/python2.7/pyconfig.h", O_RDONLY) = 4
read(4, "/* pyconfig.h.  Generated from p"..., 4096) = 4096
stat("pyconfig.h", {st_mode=S_IFREG|0664, st_size=36037, ...}) = 0
stat("pyconfig.h.in", {st_mode=S_IFREG|0644, st_size=34336, ...}) = 0
stat("PC/pyconfig.h", {st_mode=S_IFREG|0644, st_size=20770, ...}) = 0
stat("PC/os2vacpp/pyconfig.h", {st_mode=S_IFREG|0644, st_size=10113, ...})
= 0
stat("PC/os2emx/pyconfig.h", {st_mode=S_IFREG|0644, st_size=8096, ...}) = 0
stat("Include/pyconfig.h", {st_mode=S_IFREG|0664, st_size=36037, ...}) = 0
stat("build/bdist.linux-x86_64/rpm/BUILD/Python-2.7.3/pyconfig.h",
{st_mode=S_IFREG|0664, st_size=36037, ...}) = 0
stat("build/bdist.linux-x86_64/rpm/BUILD/Python-2.7.3/Include/pyconfig.h",
{st_mode=S_IFREG|0664, st_size=36037, ...}) = 0
stat("RISCOS/pyconfig.h", {st_mode=S_IFREG|0644, st_size=18510, ...}) = 0
open("/usr/local/include/python2.7/pyconfig.h", O_RDONLY) = 3
read(3, "/* pyconfig.h.  Generated from p"..., 4096) = 4096
error: pyconfig.h: No such file or directory

/usr/local/include/python2.7/pyconfig.h exists:

[scarolan@titania:~/Python-2.7.3]$ ls
/usr/local/include/python2.7/pyconfig.h -l
-rw-r--r-- 1 root root 36037 Mar 26 11:45
/usr/local/include/python2.7/pyconfig.h

I'm not sure exactly what the installer is expecting here...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
>
> http://hg.python.org/cpython/file/d321885ff8f3/Lib/distutils/command/bdist_rpm.py#l23
>

No dice.

[scarolan@titania:~/Python-2.7.3]$ alias | grep python
alias python='/usr/local/bin/python2.7'

[scarolan@titania:~/Python-2.7.3]$ /usr/local/bin/python2.7 setup.py
bdist_rpm
error: pyconfig.h: No such file or directory
error: Bad exit status from /var/tmp/rpm-tmp.14555 (%build)
RPM build errors:
Bad exit status from /var/tmp/rpm-tmp.14555 (%build)
error: command 'rpmbuild' failed with exit status 1

Has anyone on this list successfully built a python 2.7 RPM using this
command?
python2.7 setup.py bdist_rpm

If so, what was your secret?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
> What it looks like to me is that while you run (using python 2.7):
>
> >  python27 setup.py bdist_rpm
>
> doing that generates a temporary bash script, which in turn runs:
>
> > python setup.py build
>

Yea, I checked this, and /usr/local/bin/python is just a symlink pointing
at /usr/local/bin/python2.7.

Unfortunately Red Hat is slow to update their package versions; even the
most recent RHEL6 comes with Python 2.6.

I think if I can figure out where it wants that pyconfig.h file, it should
work.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
Ok, so I'm now attempting a "clean room" installation using Python 2.7.3 to
build the RPM.  Here's my installation command:

./configure --with-zlib=/usr/include; make; sudo make install

But the bdist_rpm setup command fails:

[scarolan@titania:~/Python-2.7.3]$ python2.7 setup.py bdist_rpm

error: pyconfig.h: No such file or directory
error: Bad exit status from /var/tmp/rpm-tmp.67699 (%build)

RPM build errors:
Bad exit status from /var/tmp/rpm-tmp.67699 (%build)
error: command 'rpmbuild' failed with exit status 1

Where is it looking for pyconfig.h?




On Tue, Mar 26, 2013 at 10:18 AM, Sean Carolan  wrote:

>
> Could it be that it is taking the system python executable which is
>> probably 2.4?
>>
>> -Amit.
>
>
> I've tried it with python24, python25 and python27 and all of them give
> the same error.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
> Could it be that it is taking the system python executable which is
> probably 2.4?
>
> -Amit.


I've tried it with python24, python25 and python27 and all of them give the
same error.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error

2013-03-26 Thread Sean Carolan
I'm attempting to use setup.py to build an RPM, but ran into this error:

[scarolan@cobbler:~/rpmbuild/BUILD/Python-2.7.3]$ python27 setup.py
bdist_rpm

  File "setup.py", line 361
with open(tmpfile) as fp:
^
SyntaxError: invalid syntax
error: Bad exit status from /var/tmp/rpm-tmp.8897 (%build)

It appears the syntax error is striggered when "python setup.py build" is
run from that temporary bash script (/var/tmp/rpm-tmp.8897):

+ cd
/home/scarolan/rpmbuild/BUILD/Python-2.7.3/build/bdist.linux-x86_64/rpm/BUILD
+ cd Python-2.7.3
+ env 'CFLAGS=-O2 -g -m64 -mtune=generic' python setup.py build
  File "setup.py", line 361
with open(tmpfile) as fp:
^
SyntaxError: invalid syntax

Any ideas how to fix this?  The documentation on this topic is quite scarce.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Listen for input while performing other tasks

2012-11-25 Thread Sean Carolan
On Sun, Nov 25, 2012 at 7:29 AM, Francois Dion  wrote:
> This should really be done with interrupts, but unfortunately there is
> no support in the RPi.GPIO module for that, even if you have a patched
> kernel.

Thank you for all this great information.  I ended up going with a
simple solution; I created a separate "listener" script that just
waits for a button press.  When the mode button is pressed, it uses
os.system() to kill the other script and then starts it up again in
the next mode.  This seems to work well for my purposes.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Listen for input while performing other tasks

2012-11-25 Thread Sean Carolan
> If you show us how you check whether the button is pressed, we may be able to
> show you how to run that asynchronously.

Apologies for the previous email; I think I sent it in HTML format.
Gmail changed their user interface again...

This is how I'm checking for a button press:

modes = (weather, alarmclock, moodlight)
currmode = 0
mode = 10  ## mode button is on pin #10

def checkMode():
'''Returns the current mode and whether a mode change was detected.'''
global currmode
modechange = False
GPIO.setup(mode, GPIO.IN)
if GPIO.input(mode) == False:
print "Mode button pressed."
if currmode < len(modes) - 1:
currmode += 1
else:
currmode = 0
modechange = True
#print modes[currmode]
return (modes[currmode], modechange)

It's pretty simple, really.  If GPIO.input(mode) returns False, then
the button is pressed.  My function above returns the current mode
from my modes tuple, and whether a change was detected.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Listen for input while performing other tasks

2012-11-25 Thread Sean Carolan
I'm working on a python script that runs on a Raspberry Pi.  The script
detects when hardware buttons are pressed, and then runs functions based on
that input.

I want to be able to always listen for a button press, no matter what the
script is doing at the current moment.  When a button press is detected,
the script should stop whatever it is doing, and move to the next "mode" or
function.

So far I've only been able to come up with kludgy implementations with lots
of short time.sleep() calls alternating with checks to see whether the
buttons were pressed or not.

There has to be a cleaner way to do this.  Do you have any ideas how to
make this work?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python XML for newbie

2012-07-02 Thread Sean Carolan
> Yes, I personally think that (Mini)DOM should be locked away from beginners
> as far as possible.

Ok, I'm glad to hear that.  I'll continue to work with ElementTree and
lxml and see where it takes me.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python XML for newbie

2012-07-01 Thread Sean Carolan
> Thank you, this is helpful.  Minidom is confusing, even the
> documentation confirms this:
> "The name of the functions are perhaps misleading"
>
>> But I'd start with the etree tutorial (of which
>> there are many variations on the web):

Ok, so I read through these tutorials and am at least able to print
the XML output now.  I did this:

doc = etree.parse('computer_books.xml')

and then this:

for elem in doc.iter():
print elem.tag, elem.text

Here's the data I'm interested in:

index 1
field 11
value 9780596526740
datum

How do you say, "If the field is 11, then print the next value"?  The
raw XML looks like this:


1
11
9780470286975


Basically I just want to pull all these ISBN numbers from the file.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python XML for newbie

2012-07-01 Thread Sean Carolan
> The simplest way using the standard library tools is (IMHO)
> elementtree. minidom is a complex beast by comparison,
> especially if you are not intimately familiar with
> your XML structure.

Thank you, this is helpful.  Minidom is confusing, even the
documentation confirms this:
"The name of the functions are perhaps misleading"

> But I'd start with the etree tutorial (of which
> there are many variations on the web):
>
> The original:
> http://effbot.org/zone/element-index.htm
>
> My preference:
> http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/index.html

I'm going to work through those and see what I can come up with.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python XML for newbie

2012-07-01 Thread Sean Carolan
I'm trying to parse some XML data (Book titles, ISBN numbers and
descriptions) with Python.  Is there a *simple* way to import an XML
file into a dictionary, list, or other usable data structure?  I've
poked around with minidom, elementtree, and "untangle" but am not
really understanding how they are supposed to work.

Here's some sample data:




Title
2
1
11
true
false


...several more fields, then there are the items...




108


1
2
Essential System Administration


For starters, I'd like to be able to just print out the list of titles
in the XML file, using the correct XML parser.  I don't mind doing
some research or reading on my own, but the official documentation
seems terribly confusing to me.

http://docs.python.org/library/xml.dom.minidom.html

Any pointers?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Matplotlib labels

2012-06-18 Thread Sean Carolan
> I also noticed another issue with my stacked bar graph; the total
> height of the bar is the size of the largest number of the dataset,
> and not the total of all the individual items.  Anyone matplotlib
> experts out there who can weigh in?

I figured out what was going on here; the bars were all rendering on
top of one another.  Adjustments to the "bottom" parameter have fixed
the issue.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Matplotlib labels

2012-06-18 Thread Sean Carolan
> Unfortunately my graph is generated dynamically. How can I create my
> legend when my 'bar' objects have no names to refer to?
>
>    for admin in bd:
>        bar(ind, bd[admin], width, color=colordict[admin])
>    xticks(ind+width/2., datenames)
>    legend()
>    grid('on')
>    outfile = 'testfile.png'
>    savefig('/var/www/'+outfile)
>    return outfile

I found the solution to this problem, one of the optional kwargs for
the pyplyt.bar() function is "label".  Once I assigned that, legend()
worked fine.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Matplotlib labels

2012-06-18 Thread Sean Carolan
> Not me, but I notice there is a gmane newsfeed for matplotlib:
>
> gmane.comp.python.matplotlib.general
>
> Probably worth posting questions there.

Thank you, I will inquire on the newsfeed.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Matplotlib labels

2012-06-18 Thread Sean Carolan
> Unfortunately my graph is generated dynamically. How can I create my
> legend when my 'bar' objects have no names to refer to?

I also noticed another issue with my stacked bar graph; the total
height of the bar is the size of the largest number of the dataset,
and not the total of all the individual items.  Anyone matplotlib
experts out there who can weigh in?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with Matplotlib labels

2012-06-18 Thread Sean Carolan
I'm working on a simple python web app that generates graphs, because
managers love graphs.  I've got it about 90% done, but I'm having
trouble getting labels onto my stacked graph.  In the matplotlib
documentation there is a nice example showing how to create the
legend.  Note how the variables p1 and p2 are used to generate the
legend in this example:

http://matplotlib.sourceforge.net/examples/pylab_examples/bar_stacked.html


p1 = plt.bar(ind, menMeans,   width, color='r', yerr=womenStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
 bottom=menMeans, yerr=menStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind+width/2., ('G1', 'G2', 'G3', 'G4', 'G5') )
plt.yticks(np.arange(0,81,10))
plt.legend( (p1[0], p2[0]), ('Men', 'Women') )



Unfortunately my graph is generated dynamically. How can I create my
legend when my 'bar' objects have no names to refer to?

for admin in bd:
bar(ind, bd[admin], width, color=colordict[admin])
xticks(ind+width/2., datenames)
legend()
grid('on')
outfile = 'testfile.png'
savefig('/var/www/'+outfile)
return outfile
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] matplotlib pylab question - offset bar graph labels

2012-06-13 Thread Sean Carolan
> I've got a function that builds a bar graph.  We are 95% happy with
> it, but the x-axis tick labels are a little bit skewed to the right.
> Anyone know how to skew the labels over by 10 or 20 pixels?  Here's
> the code that generates my xticks:
>
> xticks(range(len(builds)), users, rotation=30)

In case anyone else comes across this issue, I found an acceptable
solution, these settings seem to work well for us:

xticks(range(len(xnames)), xnames, rotation=45, size=8,
horizontalalignment='center')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] matplotlib pylab question - offset bar graph labels

2012-06-13 Thread Sean Carolan
I've got a function that builds a bar graph.  We are 95% happy with
it, but the x-axis tick labels are a little bit skewed to the right.
Anyone know how to skew the labels over by 10 or 20 pixels?  Here's
the code that generates my xticks:

xticks(range(len(builds)), users, rotation=30)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python equivalent of "kill -0 PID"

2012-04-26 Thread Sean Carolan
In bash you can do this to see if a process is running:

[scarolan@kurobox:~/bin]$ kill -0 24275
[scarolan@kurobox:~/bin]$ echo $?
0

Is there a python equivalent?  I tried using os.kill() but did not see
any way to capture the output.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Sean Carolan
>> if line.startswith('notes'):
>>   break
>> notes = open('myfile','r').read().split(notes:\n')[1]
>
> The first two lines are redundant you only need the last one.

I should have clarified, the "if line.startswith" part was used to
break out of the previous for loop, which was used to import the
other, shorter strings.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Sean Carolan
> So right now my code looks something like this:
>
> for line in open('myfile','r'):
>  if line.startswith('notes'):
>      ## Assign rest of file to variable
>
> Is there an easy way to do this?  Or do I need to read the entire file
> as a string first and carve it up from there instead?

I ended up doing this, but please reply if you have a more elegant solution:

if line.startswith('notes'):
   break
notes = open('myfile','r').read().split(notes:\n')[1]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Sean Carolan
I'm not sure how to do this. I'm reading lines in from a text file.
When I reach the string "notes:", I want to assign the remainder of
the text file to a single variable (line breaks and all):

text
moretext
moretext
notes:
This is the stuff I want in my variable.
And this line should be included too.
Also this one.

So right now my code looks something like this:

for line in open('myfile','r'):
  if line.startswith('notes'):
  ## Assign rest of file to variable

Is there an easy way to do this?  Or do I need to read the entire file
as a string first and carve it up from there instead?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically assign variable names to tuple objects

2011-03-01 Thread Sean Carolan
> Another way is:
>
> zip(*map(open, myfiles))

>> Then your loop looks like:
>>
>> for i in zip([ cleanedup(filename) for filename in myfiles ])

Thanks, Steven!  I knew there was a way to do this with just a few
lines.  I will read up some more on list expansion and the map
built-in.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically assign variable names to tuple objects

2011-03-01 Thread Sean Carolan
> My advice would be to go read up on the zip() function and the
> str.join() function. Then, if you are using python 2.x, go find
> itertools.izip. It does the same thing as zip but it's more memory
> efficient. With those two you can do it in about two lines or so (and
> maybe a few for set up and clarity and such).

This is what I've got so far:

import sys
myfiles = sys.argv[1:]
for i in zip(open(myfiles[0]), open(myfiles[1]), open(myfiles[2])):
print " ".join(i)

How would you:

1.  zip an arbitrary number of files in this manner?  I hard-coded it
to do only three.
2.  Strip out trailing spaces and line breaks from the lines in each file?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically assign variable names to tuple objects

2011-03-01 Thread Sean Carolan
> I saw in your follow-up that you went straight for vars().  I really
> don't think that's what you wish to use.  Get rid of vars(), he had
> to go to jail.  Don't go visit vars() again for at least two months,
> then maybe he'll be out on probation.

Thanks Martin and Hugo.  As you can tell I'm no python guru.  Maybe I
should take a step back and explain exactly what it is I'm trying to
do.  I know this can be done quickly with awk or even perl but I want
to get more practice with python.  So here's the basic idea:

Take an arbitrary number of text files. Assume that each text file has
the exact same number of lines.  Concatenate each line of each file
with the corresponding lines of the other files and output the data.
So in other words, the first line of output will be
file1_line1+file2_line1+file3_line1, etc.

I'll work on this some more and see what I can come up with.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically assign variable names to tuple objects

2011-03-01 Thread Sean Carolan
On Tue, Mar 1, 2011 at 11:55 AM, Sean Carolan  wrote:
> Maybe someone can help with this.  I have a function that takes a
> single file as an argument and outputs a tuple with each line of the
> file as a string element.  This is part of a script that is intended
> to concatenate lines in files, and output them to a different file.

Not sure if this is the "right" or best way to do this, but I ended up
using vars() to assign my variable names, like so:

import sys

myfiles = tuple(sys.argv[1:])
numfiles = len(myfiles)
varlist = []

def makeTuple(file):
   6 lines:outlist = [] --

for i in range(numfiles):
varlist.append('tuple'+str(i))
vars()[varlist[i]] = makeTuple(myfiles[i])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Dynamically assign variable names to tuple objects

2011-03-01 Thread Sean Carolan
Maybe someone can help with this.  I have a function that takes a
single file as an argument and outputs a tuple with each line of the
file as a string element.  This is part of a script that is intended
to concatenate lines in files, and output them to a different file.
This is as far as I've gotten:


import sys

myfiles = tuple(sys.argv[1:])
numfiles = len(myfiles)

def makeTuple(file):
outlist = []
f = open(file, 'r')
for line in f.readlines():
line = line.rstrip(' \n')
outlist.append(line)
return tuple(outlist)

for i in range(numfiles):
makeTuple(myfiles[i])


The script creates the tuples as it was intended to, but I'm not sure
how to assign variable names to each tuple so that I can work with
them afterwards.  How would you dynamically assign variable names to
each tuple created by makeTuple(), so that they can be manipulated
further?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] System Monitoring

2011-02-09 Thread Sean Carolan
> Hi,
> Im fairly new to programming in python, and have a question.
> Im looking to build a program that monitor's certain things on my Linux
> system. for instance disk space. What is the best way to monitor a Linux
> server without using to much resources?
> Should I execute shell commands and grab the output of them? Or should i use
> SNMP. Or is there a better way?
> Thanks in advance!
> de Haan

de Haan:

I'm guessing from the text of your message that this is a single,
stand-alone system.  Nagios and cacti are complete overkill for system
monitoring on a single machine.  Here are some other options that you
can try:

*  GUI monitoring - gkrellm is great for this.  You can run it and see
performance graphs and monitors right in a little app on your desktop.

*  Command line monitoring - it's pretty easy to cobble together a
python script that monitors things like load average, memory, disk
space, etc.  Hint:  you can get a *lot* of useful info from the /proc
directory, for example, /proc/meminfo, /proc/loadavg, etc.

Here's a quickie that I built for a client, it watches the 15 minute
load average.

#!/usr/bin/env python
'''
File: load_average_watcher.py
Author: Sean Carolan
Description: Watches 15 minute load average and alerts sysadmin if it
gets over a certain level.
'''

import smtplib
from email.MIMEText import MIMEText

threshhold = 3.0
sender = 'r...@server.com'
recipient = 'sysad...@example.com'

def sendMail():
msg = MIMEText("Alert - system load is over "+str(threshhold))
msg['Subject'] = 'System Load Alert'
msg['From'] = sender
msg['To'] = recipient
s = smtplib.SMTP()
s.connect()
s.sendmail(sender, [recipient], msg.as_string())
s.close()

for line in open('/proc/loadavg'):
#If the load average is above threshhold, send alert
loadav = float(line.split()[2])
if loadav < threshhold:
print '15 minute load average is '+str(loadav)+': OK!'
else:
print '15 minute load average is '+str(loadav)+': HIGH!'
sendMail()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with range of months spanning across years

2011-02-01 Thread Sean Carolan
> As far as I can tell from quickly going through documentation, no. At
> least, not with a quick and easy function. datetime can represent the
> dates just fine, and you can add days to that until you hit your end
> date, but adding months is harder. timedelta can't represent a month,
> which makes sense since they're not of constant length anyway. So
> using datetime is not really your best option. Calendar is more about
> displaying than doing calculations, making it even less useful.

Thank you, this is useful information.

>
> You can use your code or ian's (or my modification of ian's code) to
> your taste, I don't expect any measurable difference in efficiency. If
> it's really important, *measure*. But I suspect it isn't, unless
> you'll run it either on time spans of thousands of years or if it will
> be used by thousands of people at a time.

Yes, the code runs quickly enough for our needs.  Thanks again for the
helpful suggestions.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with range of months spanning across years

2011-02-01 Thread Sean Carolan
> This sounds somewhat like homework. If it is, that's fine, mention it,
> and we will help you. But we won't do your homework for you, so keep
> that in mind.

A reasonable assumption but this is actually going in a cgi tool that
I'm using at work.  The input comes from pull-down menus on a web
page.

Here's what I came up with, feel free to give suggestions on how this
might be made more efficient:

if startyear > endyear or (startyear == endyear and startmonth > endmonth):
print 'Your start date must be earlier than the end date.'
else:
datelist = []
month = startmonth
year = startyear
while month != endmonth or year != endyear:
datelist.append((year, month))
if month == 12:
month = 1
year += 1
else:
month += 1
datelist.append((year, month))
print datelist

I was hoping there was some whiz-bang function that would just iterate
through months if it was fed a start and end date.  Can datetime or
calendar do this?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with range of months spanning across years

2011-02-01 Thread Sean Carolan
I have a function that accepts four arguments, namely startmonth,
startyear, endmonth, and endyear.  For example:

startmonth = 8
startyear = 2009
endmonth = 1
endyear = 2010

What would be the most straightforward way to create a list of
year/month pairs from start to end?  I want to end up with a list of
tuples like this:

mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), (2009, 12), (2010, 1)]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python on Ubuntu 10.10?

2011-01-15 Thread Sean Carolan
>>> I am new to programming and to Python.  I've been using Python with IDLE
>>> on Windows Vista for a few weeks now.
>>> (And I'm loving it!)  However, I'm thinking about switching to Ubuntu
>>> 10.10.  If I download Ubuntu, will I still be able to use the
>>> IDLE environment?  I am really quite fond of it (mostly because it's what
>>> I know!).  To use Python in Ubuntu,
>>> will I have to do any additional downloading, or do Python and IDLE come
>>> built in and ready to use?

Bite the bullet and learn how to use vim; you won't regret it.
There's a steep learning curve at first but once you get the hang of
it you'll be coding like a boss.  This blog post also has some great
tips on how to make vim into an IDE:

http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] shlex.split if there is an apostrophe in the string?

2011-01-07 Thread Sean Carolan
I'm practicing manipulating data with a text file.  I'm trying to use
shlex.split to break up each line, which works great until it gets to
the first apostrophe:

fin = open('huckfinn.txt')
startstring = 'START OF THIS PROJECT'

for line in fin:
print line
words = shlex.split(line)

This is the line is where it's choking, complaining that there is no
closing quote:

YOU don't know about me without you have read a book by the name of The

How can I get shlex.split to ignore single apostrophes such as the one above?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] matplotlib.pylab.plotfile formatting help

2011-01-07 Thread Sean Carolan
> I can also advice you to try the matplotlib mailing list: people will there 
> will be much more knowledgeable wrt to matplotlib and pylab than on this 
> mailing list: 
> http://sourceforge.net/mailarchive/forum.php?forum_name=matplotlib-users

Thanks for all the info; I managed to create a graph from my data by
using a tutorial I found on the Internet.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] matplotlib.pylab.plotfile formatting help

2011-01-03 Thread Sean Carolan
I've got a csv file that contains two data fields, the short name of a
month and an integer.  I'm experimenting with pylab and ipython to get
a feel for how pylab works.  I'm able to generate a bar graph from my
data, but there are two problems with it:

1.  I don't want "2011" appended to the month names.  This data is
from 2010, and I only want the short month name under each bar.
2.  The bars are very narrow and I'm not sure how to widen them.

Here's my CSV data, stored in a file called csvdata.csv:

month,systems
Jan,17
Feb,49
Mar,77
Apr,59
May,42
Jun,137
Jul,102
Aug,115
Sep,57
Oct,134
Nov,131
Dec,197

And here's the "ipython -pylab" command that I'm using to generate the graph:

plotfile('csvdata.csv', ('month', 'systems'), plotfuncs={'systems': 'bar'},)

I've read through some of the documentation for matplotlib, but having
never used matlab or pylab before today it's a bit confusing.  Does
anyone know how to solve #1 and #2 above?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to import python dictionary into MySQL table?

2010-12-16 Thread Sean Carolan
> I have a database with a table called "systems" that contains an
> auto-increment id field, as well as fields for each of the keys in
> mydata.keys().  But I can't seem to get the syntax to import
> mydata.values() into the table.  I think the problem may be that some
> of the items in my list are dictionaries or lists...
>
> What would be the quickest and most straightforward way to do this?

I got this working in case anyone else comes across the same problem.
This function will pull cobbler *.json data into a MySQL database
table.  The function assumes that you already have a database set up,
and that you are dumping the data into the "systems" table:

def importJSON(targetfile):
'''
Imports JSON data from targetfile into MySQL database table.
'''
value_list = []
rawdata = json.load(open(targetfile))
for key in rawdata.keys():
strvalue = str(rawdata[key]).replace("'",'"')
value_list.append(strvalue)
valtuple = tuple(value_list)
sql = "INSERT INTO systems (comment, kickstart,
name_servers_search, ks_meta, kernel_options_post, image,
redhat_management_key, power_type, power_user, kernel_options, vi
rt_file_size, mtime, template_files, gateway, uid, virt_cpus,
hostname, virt_type, mgmt_classes, power_pass, netboot_enabled,
profile, virt_bridge, parent, virt_path, interfaces, power_address,
name_servers, name, owners, ctime, virt_ram, power_id, random_id,
server, redhat_management_server, depth) VALUES (%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
cursor.execute(sql, valtuple)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to import python dictionary into MySQL table?

2010-12-16 Thread Sean Carolan
Maybe one of you can help with this.  I've got some data that I
grabbed from a cobbler *.json file using simplejson.load().  Heres
what the data looks like:

In [120]: print mydata.keys()
['comment', 'kickstart', 'name_servers_search', 'ks_meta',
'kernel_options_post', 'image', 'redhat_management_key', 'power_type',
'power_user', 'kernel_options', 'virt_file_size', 'mtime',
'template_files', 'gateway', 'uid', 'virt_cpus', 'hostname',
'virt_type', 'mgmt_classes', 'power_pass', 'netboot_enabled',
'profile', 'virt_bridge', 'parent', 'virt_path', 'interfaces',
'power_address', 'name_servers', 'name', 'owners', 'ctime',
'virt_ram', 'power_id', 'random_id', 'server',
'redhat_management_server', 'depth']

In [121]: print mydata.values()
['Virtual Machine', '<>', ['subdomain.company.com',
'company.com'], {'puppet_environment': 'development'}, {}, '', '~',
'apc_snmp', '', {'dns': '10.10.132.12'}, 160, 1286408237.2311871, {},
'10.10.32.3', 'asIjeKJIDOOUuUIDSwOTY', 16,
'webservice-app16.subdomain.company.com', '<>', [], '', True,
'rhel5-server-64-domU', '<>', '', '<>', {'eth0':
{'dhcp_tag': '', 'subnet': '255.255.255.0', 'virt_bridge': 'xenbr0',
'static_routes': ['10.10.0.0/255.255.0.0:10.10.32.3',
'10.10.0.0/255.255.0.0:10.10.32.3'], 'dns_name':
'webservice-app16.subdomain.company.com', 'bonding': '', 'static':
True, 'bonding_opts': '', 'mac_address': '00:16:3e:aa:aa:aa',
'bonding_master': '', 'ip_address': '10.10.32.219'}}, '',
['10.10.132.12', '10.10.132.13'],
'webservice-app16.subdomain.company.com', ['scarolan'],
1277755073.144805, 11749, '', '7oWY', '<>', '~', 2]

I have a database with a table called "systems" that contains an
auto-increment id field, as well as fields for each of the keys in
mydata.keys().  But I can't seem to get the syntax to import
mydata.values() into the table.  I think the problem may be that some
of the items in my list are dictionaries or lists...

What would be the quickest and most straightforward way to do this?




My table is below if you need a reference, sorry for the ugly formatting:

mysql> show columns in systems;
+--+--+--+-+-++
| Field| Type | Null | Key | Default |
Extra  |
+--+--+--+-+-++
| id   | int(11)  | NO   | PRI | NULL|
auto_increment |
| comment  | varchar(255) | YES  | | NULL|
   |
| kickstart| varchar(255) | YES  | | NULL|
   |
| name_servers_search  | varchar(255) | YES  | | NULL|
   |
| ks_meta  | varchar(255) | YES  | | NULL|
   |
| kernel_options_post  | varchar(255) | YES  | | NULL|
   |
| image| varchar(255) | YES  | | NULL|
   |
| redhat_management_key| varchar(255) | YES  | | NULL|
   |
| power_type   | varchar(255) | YES  | | NULL|
   |
| power_user   | varchar(255) | YES  | | NULL|
   |
| kernel_options   | varchar(255) | YES  | | NULL|
   |
| virt_file_size   | int(11)  | YES  | | NULL|
   |
| mtime| int(11)  | YES  | | NULL|
   |
| template_files   | varchar(255) | YES  | | NULL|
   |
| gateway  | varchar(255) | YES  | | NULL|
   |
| uid  | varchar(255) | YES  | | NULL|
   |
| virt_cpus| smallint(64) | YES  | | NULL|
   |
| hostname | varchar(255) | YES  | | NULL|
   |
| virt_type| varchar(255) | YES  | | NULL|
   |
| mgmt_classes | varchar(255) | YES  | | NULL|
   |
| power_pass   | varchar(255) | YES  | | NULL|
   |
| netboot_enabled  | varchar(255) | YES  | | NULL|
   |
| profile  | varchar(255) | YES  | | NULL|
   |
| virt_bridge  | varchar(255) | YES  | | NULL|
   |
| parent   | varchar(255) | YES  | | NULL|
   |
| virt_path| varchar(255) | YES  | | NULL|
   |
| interfaces   | text | YES  | | NULL|
   |
| power_address| varchar(255) | YES  | | NULL|
   |
| name_servers | varchar(255) | YES  | | NULL|
   |
| name | varchar(255) | YES  | | NULL|
   |
| owners   | varchar(255) | YES  | | NULL|
   |
| ctime| int(11)  | YES  | | NULL|
   |
| virt_ram | int(11)  | YES  | | NULL|
   |
| power_id   

Re: [Tutor] Problem with "yaml load"

2010-12-13 Thread Sean Carolan
Yes, I tried using os.subprocess() but there was some sort of parsing
error.  I'll just stick with the temporary file for now; the
documentation seems to indicate that is how yaml.load should be used
anyway...



On Mon, Dec 13, 2010 at 11:43 AM, Wayne Werner  wrote:
> On Mon, Dec 13, 2010 at 11:08 AM, Sean Carolan  wrote:
>>
>> Hi folks:
>>
>> I'm trying to define a short function that will import yaml data into
>> a python dictionary.  I am able to do this by dumping my data into a
>> temporary file and then importing it with yaml.load.  I would like to
>> see if I can eliminate the temporary file and import the data
>> directly.
>>
>> This works fine:
>>
>> import yaml
>> import os
>>
>> def grabfacts():
>>    ''' This function grabs facter data and sucks it into a dictionary
>>    called dataMap '''
>>    os.system('facter --yaml > /tmp/sysdata.yaml')
>>    f = open('/tmp/sysdata.yaml')
>>    dataMap = yaml.load(f)
>>    f.close()
>>
>> Is there an easy way to do this without writing to a temporary file?
>
> Presumably you could use something like subprocess and simply pipe stdout to
> your program. I presume facter --yaml will produce output to stdout? It's
> fairly trivial to read stdout using subprocess.
> http://docs.python.org/library/subprocess.html
> that should get you started.
> HTH,
> Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with "yaml load"

2010-12-13 Thread Sean Carolan
Hi folks:

I'm trying to define a short function that will import yaml data into
a python dictionary.  I am able to do this by dumping my data into a
temporary file and then importing it with yaml.load.  I would like to
see if I can eliminate the temporary file and import the data
directly.

This works fine:

import yaml
import os

def grabfacts():
''' This function grabs facter data and sucks it into a dictionary
called dataMap '''
os.system('facter --yaml > /tmp/sysdata.yaml')
f = open('/tmp/sysdata.yaml')
dataMap = yaml.load(f)
f.close()

Is there an easy way to do this without writing to a temporary file?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python: 27 times faster than bash

2010-10-29 Thread Sean Carolan
> Can we see a version of your script?

How about just a couple snippets...there's no proprietary data but I
want to be on the safe side.  The original script consisted of a bunch
of functions similar to the one below.  When I first wrote this I
didn't know how to use sed very well, so I used variable substitution
to strip out the data I wanted:

So this function in bash:

function gettomcatserver ()
{
# Strip out the short hostname
       remoteserver=$(grep remote.server.host $adminfile)
       remoteserver=${remoteserver##*=}
       remoteserver=${remoteserver%%.*}
       echo $remoteserver
}

Became this function in python:

def gettomcatserver( customername ):
   for line in open(adminfile).readlines():
       if line.startswith("remote.server.host="):
           return line.split("remote.server.host=")[1].split(".example.com")[0]

The total script runs several functions like this for each
$customername; I was quite impressed with the difference in speed.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python: 27 times faster than bash

2010-10-28 Thread Sean Carolan
I rewrote a bash script that gathers data from a bunch of text files.
The script uses grep, sed, and awk to parse the data and takes around
5.5 seconds to run.  After rewriting the script in python, it now
takes a little over 0.2 seconds to run.  Thanks to those of you who
helped me with some questions on proper syntax.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.listdir for symbolic links?

2010-10-27 Thread Sean Carolan
Is there an easy way to find the target of a symbolic link on a Linux
system with python?  I'm looking for something like the output of the
bash command: "ls -l"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess Popen PIPE error

2010-10-26 Thread Sean Carolan
What am I doing wrong here?

>>> from subprocess import Popen, PIPE
>>> cmd = 'ls -l'
>>> p = Popen(cmd, stdout=PIPE, stderr=PIPE)
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
  File "/usr/lib64/python2.4/subprocess.py", line 993, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to pass a python variable to subprocess.call?

2010-10-25 Thread Sean Carolan
I'm rewriting a bunch of my bash scripts to get some python practice.
There are some instances where python doesn't have the built-in text
processing that I need, so I'm using subprocess.call.  How can I pass
a python variable to these subprocesses?  For example:

mydir = "/usr/local/bin"
subprocess.call("ls -l /usr/local/bin", shell=True)

How do I replace /usr/local/bin in the subprocess call with the mydir variable?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to deal failed function and 0xDEADBEEF type errors...

2010-07-15 Thread Sean Carolan
Spoiler alert:  This was encountered while working on MIT OCW 6.000
problem set 4.

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/ps4.py


My function returns a list as it should:

##
def nestEggFixed(salary, save, growthRate, years):
yearlyreturn=[]
nut = 0
for i in range(0, years):
# print "At the end of year",(i),"nut size is:",(nut)
nut = nut * (1 + 0.01 * growthRate) + (salary * save * 0.01)
yearlyreturn.append(nut)
return yearlyreturn
##

print nestEggFixed(1, 10, 15, 5)
[1000.0, 2150.0, 3472.5, 4993.375, 6742.38124999]

So far so good right?  Not so fast, the test function provided by the
instructors is failing:

Here's the test function:

##
def testNestEggFixed():
salary = 1
save   = 10
growthRate = 15
years  = 5
savingsRecord = nestEggFixed(salary, save, growthRate, years)
print savingsRecord
##

Run it by itself and there's no output:

testNestEggFixed

Try to print it and it throws this error:

print testNestEggFixed


What am I missing here?  I even tried running all the code in the test
function in my script and it works fine.  It only fails when it's put
into a function.  I think I must be doing something wrong.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor