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
Hughmoris
Apr 21, 2007
Let's go to the abyss!

Jonnty posted:

There are lots of options, depending on how you're doing things.

code:
for line in lines:
  if line < 8:
    pass

for line in lines[8:]:
  #stuff
That last one's called a list slice if you want to look it up by the way.

I've tried both methods (probably incorrectly) and it is still printing off all the lines in the text file. Here is what I have:
code:
myMovies = open('movieList.txt','r')
for line in myMovies:
    if line < 8:
        pass
    else: print line

Adbot
ADBOT LOVES YOU

yippee cahier
Mar 28, 2005

Hughmoris posted:


You'll need to use enumerate() if you want to do it that way, because "line" isn't the index of the line, it refers to the line itself. Here you are with slicing:

code:
myMovies = open('movieList.txt','r')
for line in myMovies[8:]:
    print line

Hughmoris
Apr 21, 2007
Let's go to the abyss!

sund posted:

You'll need to use enumerate() if you want to do it that way, because "line" isn't the index of the line, it refers to the line itself. Here you are with slicing:

code:
myMovies = open('movieList.txt','r')
for line in myMovies[8:]:
    print line

That gives me this error:

Traceback (most recent call last):
File "C:/Python27/programs/reader.py", line 17, in <module>
for line in myMovies[8:]:
TypeError: 'file' object is not subscriptable

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

sund posted:

You'll need to use enumerate() if you want to do it that way, because "line" isn't the index of the line, it refers to the line itself. Here you are with slicing:

code:
myMovies = open('movieList.txt','r')
for line in myMovies[8:]:
    print line

You need to use islice or read the whole file into memory with readlines and then slice it:

code:
from itertools import islice
myMovies = open('movieList.txt','r')
for line in islice(myMovies, 8, None):
    print line
or
code:
myMovies = open('movieList.txt','r')
for line in myMovies.readlines()[8:]:
    print line

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

sund posted:

You'll need to use enumerate() if you want to do it that way, because "line" isn't the index of the line, it refers to the line itself. Here you are with slicing:

code:
myMovies = open('movieList.txt','r')
for line in myMovies[8:]:
    print line

whoops, I'm thick. Sorry Hughmoris!

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Jonnty posted:

whoops, I'm thick. Sorry Hughmoris!

No worries, its the thought that counts! Thanks for input Lonely Wolf, I'll give it a shot when I get off work today. Since you're all so helpful, I have another question. I posted this in the Linux thread but perhaps there is an easier way to do it in Python.

I'm working on my first project which is a little script that will gather the names of DVDs being released that week and send those names to me in an email. I have figured out how to pull the names from the website and put them in a text file but I'm a bit clueless on how to automate an email with the names in the body of the message. I have one computer running Linux Mint 8 and another running Windows XP. I have a Gmail address and an email address through my ISP.

Any suggestions on how to best tackle the email issue, assuming I have no knowledge beyond using webmail or Outlook.

Hughmoris fucked around with this message at 14:25 on Jul 26, 2010

tripwire
Nov 19, 2004

        ghost flow

Hughmoris posted:

No worries, its the thought that counts! Thanks for input Lonely Wolf, I'll give it a shot when I get off work today. Since you're all so helpful, I have another question. I posted this in the Linux thread but perhaps there is an easier way to do it in Python.

I'm working on my first project which is a little script that will gather the names of DVDs being released that week and send those names to be in an email. I have figured out how to pull the names from the website and put them in a text file but I'm a bit clueless on how to automate an email with the names in the body of the message. I have one computer running Linux Mint 8 and another running Windows XP. I have a Gmail address and an email address through my ISP.

Any suggestions on how to best tackle the email issue, assuming I have no knowledge beyond using webmail or Outlook.
I'm sure you can probably do this from within python as well, but what I did to accomplish that was to set up the default mail daemon to use my gmail account. That way sending an email is just a matter of piping what you want to send into an invocation of mail like so:

code:
echo "Hello World"|mail -s "This is a subject" recipient@address.com
If you need to send attachments you uuencode them and append them to the message you are sending.

tef
May 30, 2004

-> some l-system crap ->

Hughmoris posted:

No worries, its the thought that counts! Thanks for input Lonely Wolf, I'll give it a shot when I get off work today. Since you're all so helpful, I have another question. I posted this in the Linux thread but perhaps there is an easier way to do it in Python.

on unix, you would make your program print all of the information, and run it under cron
cron runs a script at a specified time repeatedly and emails you the result.

this would be the 'easiest' way if everything is set up properly.

wins32767
Mar 16, 2007

Is there a more abstracted python LDAP library than python-ldap?

Ziir
Nov 20, 2004

by Ozmaugh
I have an XML file with say the element <name> and a list of names, some foreign so they have accents and other special characters in them. I wrote a script to read the XML file and find all the elements <name> and write to a file the names as a list. This almost works fine, but the problem is that it breaks when it encounters a name with an accent. The thing is, I don't want to strip the accents away because I want my outputted list (an HTML file) to have them.

I've searched for variations of python and unicode and encoding but I can't seem to find any answers. All I want is for my script to either print the accents themselves or convert them into some kind of code that my browser can parse (such as À -> & Agrave;). Any suggestions?

Edit:

import codecs and declaring my output file utf-8 seemed to do the trick.

Ziir fucked around with this message at 20:43 on Jul 26, 2010

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum
Can somebody explain how this works to me? Why doesn't it create a new list for the default argument on every call?

code:
class Test(object):
    """docstring for Test"""
    def __init__(self, myList=list()):
        super(Test, self).__init__()
        self.myList = myList
        
a = Test()
a.myList.append(3)
print "a before:", a.myList

b = Test()
b.myList.append(2)

print "a after:", a.myList
print "b after:", b.myList
output:
code:
a before: [3]
a after: [3, 2]
b after: [3, 2]
http://codepad.org/luFDMwEy

tripwire
Nov 19, 2004

        ghost flow

Sweeper posted:

Can somebody explain how this works to me? Why doesn't it create a new list for the default argument on every call?

code:
class Test(object):
    """docstring for Test"""
    def __init__(self, myList=list()):
        super(Test, self).__init__()
        self.myList = myList
        
a = Test()
a.myList.append(3)
print "a before:", a.myList

b = Test()
b.myList.append(2)

print "a after:", a.myList
print "b after:", b.myList
output:
code:
a before: [3]
a after: [3, 2]
b after: [3, 2]
http://codepad.org/luFDMwEy

I think its due to the way keyword arguments work. When you are supplying a value for a default keyword argument, that value is used for all future calls of the function.

Like if you had
code:
def foo(arg = "default value" ):
    pass
The string "default value" is only created once, and that one instance is passed for all future invocations of foo.

You probably want something this:
code:
class Test(object):
    """docstring for Test"""
    def __init__(self, myList=None):
        super(Test, self).__init__()
        self.myList = [] if myList == None else myList
        
a = Test()
a.myList.append(3)
print "a before:", a.myList

b = Test()
b.myList.append(2)

print "a after:", a.myList
print "b after:", b.myList

tripwire fucked around with this message at 16:13 on Jul 28, 2010

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum

tripwire posted:

I think its due to the way keyword arguments work. When you are supplying a value for a default keyword argument, that value is used for all future calls of the function.

Like if you had
code:
def foo(arg = "default value" ):
    pass
The string "default value" is only created once, and that one instance is passed for all future invocations of foo.

You probably want something this:
code:
class Test(object):
    """docstring for Test"""
    def __init__(self, myList=None):
        super(Test, self).__init__()
        self.myList = [] if myList == None else myList
        
a = Test()
a.myList.append(3)
print "a before:", a.myList

b = Test()
b.myList.append(2)

print "a after:", a.myList
print "b after:", b.myList

I figured it was something about default arguments only being created one. Is that a design decision? Is there a reason to create them only once vs. creating it every time?

tripwire
Nov 19, 2004

        ghost flow

Sweeper posted:

I figured it was something about default arguments only being created one. Is that a design decision? Is there a reason to create them only once vs. creating it every time?

Im pretty sure its designed that way on purpose. I could be wrong but I'd imagine default values sit outside of the function for efficiency- if a default argument had to be created every time a function was invoked, thered be way too much overhead.

b0lt
Apr 29, 2005

tripwire posted:

Im pretty sure its designed that way on purpose. I could be wrong but I'd imagine default values sit outside of the function for efficiency- if a default argument had to be created every time a function was invoked, thered be way too much overhead.

Yep, that's it. Never use a mutable object as a default argument.

Another way to do it which is a bit more informative from the function declaration would be
code:
def foo (arg=list):
    if callable(arg):
        arg = arg()
    arg.append("foo")

Haystack
Jan 23, 2005





Stack Overflow has a good overview of the topic

tl;dr is that default arguments are properties on a function or method object, and get created at class/function definition. You can even access them via whatever.func_defaults

tef
May 30, 2004

-> some l-system crap ->
code:
def foo(arg=None):
    if arg is None: 
        arg = []
    arg.append("foo")  
    return arg

tef fucked around with this message at 17:53 on Jul 28, 2010

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum
I figured it was an efficiency thing, just took my by surprise when I saw it

deichkind42
Feb 22, 2004
Ok, does anyone know how to properly write windows filenames in python 2.7?

I've tried target_dir = r"d:/pythonbackup/" but that fucks everything up.
I need a detailed explanation because i have been googling this for 20 minutes and all the explanations on the web fail on my machine for some reason. :/

I've also tried double backslashes like "C:\\backup\\" but that just gives out a windows error that it can't find the dir (probably because of the double backslashes)

deichkind42 fucked around with this message at 07:54 on Jul 29, 2010

leterip
Aug 25, 2004

deichkind42 posted:

Ok, does anyone know how to properly write windows filenames in python 2.7?

I've tried target_dir = r"d:/pythonbackup/" but that fucks everything up.
I need a detailed explanation because i have been googling this for 20 minutes and all the explanations on the web fail on my machine for some reason. :/

I've also tried double backslashes like "C:\\backup\\" but that just gives out a windows error that it can't find the dir (probably because of the double backslashes)

I recently saw a suggestion on solving this problem from here (it has a long write up on this problem). You do
code:
dir_name = os.path.normpath("c:/a_directory/")
and let it fix the forward slashes to backslashes.

unixbeard
Dec 29, 2004

I have a list of data and would like to iterate through sequential subsets of it, it looks like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and i want:

[1,2,3]
[2,3,4]
[3,4,5]
...
[8,9,10]


i have this, which im happy with:

code:
def gen_n(data, n=10):
    for i in xrange(len(data)):
        if i + n > len(data):
            raise StopIteration
        yield data[i:i+n]

a = [1,2,3,4,5,6,7,8,9,10]
for b in gen_n(a, 3):
    print b
but i'm just wondering if there's a way i can do it as a one liner with list comprehensions or some other way, e.g. for b in [some magic]

edit: i realise you can also have

code:
def gen_n(data, n=10):
    for i in xrange(len(data) - n + 1):
        yield data[i:i+n]

leterip
Aug 25, 2004
code:
>>> data = range(9)
>>> n = 3
>>> for b in (data[i:i+n] for i in xrange(len(data) - n + 1)):
...     print b
... 
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]

leterip fucked around with this message at 16:17 on Jul 29, 2010

tef
May 30, 2004

-> some l-system crap ->
code:

>>> x = range(1,11)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> zip(x[:], x[1:], x[2:])
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

leterip
Aug 25, 2004

tef posted:

code:

>>> x = range(1,11)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> zip(x[:], x[1:], x[2:])
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]


Very nice. This is a version that generalizes to any n:

code:
>>> x = range(1, 11)
>>> n = 3
>>> zip(*(x[i:] for i in xrange(n)))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

o.m. 94
Nov 23, 2009

I have some software I use for work that depends on Python 2.x, but I want to do some stuff with 3.x for my own personal ends, is there a way I have have both installed concurrently, and choose which one to use?

Lurchington
Jan 2, 2003

Forums Dragoon

oiseaux morts 1994 posted:

I have some software I use for work that depends on Python 2.x, but I want to do some stuff with 3.x for my own personal ends, is there a way I have have both installed concurrently, and choose which one to use?

On windows you're going to need to set up your path correctly using the environment variables section: http://docs.python.org/using/windows.html

On OS X it kind of depends, but I use MacPorts and this stackoverflow post gives kind of an overview (assuming you have MacPorts setup)

I haven't developed on linux in awhile, but I always controlled it with putting the right python version in path via a source command.

Kire
Aug 25, 2006
Can someone please tell me how to get Notepad++ to run a python file?

I have program.py and even when I hit f5 in Notepad++, all it does is ask me to locate a file (instead of running the file I have open like IDLE), and when I select "program.py" a cmd window just blinks in and out, nothing happens. This is on WinXP.

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum

Kire posted:

Can someone please tell me how to get Notepad++ to run a python file?

I have program.py and even when I hit f5 in Notepad++, all it does is ask me to locate a file (instead of running the file I have open like IDLE), and when I select "program.py" a cmd window just blinks in and out, nothing happens. This is on WinXP.
http://www.google.com/search?q=run+python+file+with+notepad%2B%2B&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
->
http://www.daniweb.com/forums/thread151270.html

nbv4
Aug 21, 2002

by Duchess Gummybuns
I have a script that I wrote that includes a couple files and modules. The source tree looks like this:

code:
client
  setup.py
  tsclient
    tsup    <-- the script I want added to path
    utils.py
    mutagen
      blah.py
      blah.py
      ...
    colorama
      blah.py
      blah.py
      ...
I'm trying to configure my setup file so that when you run it, it installs everything so that the script file, when invoked will be able to import all of it's dependencies, also the script "tsup" gets added to the system PATH so that you can invoke it directly. I also don't want mutagen and colorama to be added to the path because I have modified them, and I don't want it to overwrite anything.

Here is my setup.py:

code:
from distutils.core import setup

setup(name='tsclient',
      version='1.0',
      scripts=['tsclient/tsup'],
     )
is this correct? I'm reluctant to test it, because once you have it installed, you can't uninstall, so theres kinda no going back.

king_kilr
May 25, 2007
I have no idea if it works, use pip+virtualenv. pip has an uninstall, plus if that fails (rare) you can always blow away the entire venv.

unixbeard
Dec 29, 2004

leterip posted:

Very nice. This is a version that generalizes to any n:

code:
>>> x = range(1, 11)
>>> n = 3
>>> zip(*(x[i:] for i in xrange(n)))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

hah cool! thanks very much guys

Hughlander
May 11, 2005

Is there a genericish template system like you'd find in Django in the standard library? What I'm looking to do is:
1) Read in a Key/Value pair text file where not all known keys will be specified.
2) Read in a template file.
3) Write out an instance of the template based on what was read in 1/2 IE:

Data:
FirstName = Bob
Title = Your uncle


{% if FirstName %}
Hello {{ FirstName }}
{% else %}
Dear Anonymous
{% endif %}

(Note I'm using Django's template language just 'cuz that's what I'm thinking of ATM but it doesn't need to look like it as long as it can have conditional blocks.)

I'd like to build/deploy the whole thing with IronPython and have it in a large source control project without any external dependences if possible...

Is there anything like this?

tripwire
Nov 19, 2004

        ghost flow

Hughlander posted:

Is there a genericish template system like you'd find in Django in the standard library? What I'm looking to do is:
1) Read in a Key/Value pair text file where not all known keys will be specified.
2) Read in a template file.
3) Write out an instance of the template based on what was read in 1/2 IE:

Data:
FirstName = Bob
Title = Your uncle


{% if FirstName %}
Hello {{ FirstName }}
{% else %}
Dear Anonymous
{% endif %}

(Note I'm using Django's template language just 'cuz that's what I'm thinking of ATM but it doesn't need to look like it as long as it can have conditional blocks.)

I'd like to build/deploy the whole thing with IronPython and have it in a large source control project without any external dependences if possible...

Is there anything like this?
Theres a template class under the string module. It should have all the functionality youre looking for, unless I'm missing something.

Actually, scratch that. The template class in the standard library doesn't do conditional substitution like that.

tripwire fucked around with this message at 18:49 on Jul 30, 2010

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?

Hughlander posted:

Is there a genericish template system like you'd find in Django in the standard library? What I'm looking to do is:
1) Read in a Key/Value pair text file where not all known keys will be specified.
2) Read in a template file.
3) Write out an instance of the template based on what was read in 1/2 IE:

I don't think you'll find it in the standard library, but there's this: http://jinja.pocoo.org/2/

Lurchington
Jan 2, 2003

Forums Dragoon
I googled around and Tempita seems to be on topic at least

Hughlander
May 11, 2005

Lurchington posted:

I googled around and Tempita seems to be on topic at least

Assuming the docs are correct and it's still just a single 700 line module, I can probably add the 1 file to source control and use it. Thanks!

Lurchington
Jan 2, 2003

Forums Dragoon
Alright, I have an in-person technical interview for a python development job, and it's my first one ever really (I've been doing project management for the last 6 years).

It hasn't been stated, but I think I'd be working with Django and probably relational databases of one kind or another.

Those of you who've done a python dev tech interview, were there any good resources that you thought helped prepare you? Or alternatively, anything non-job specific you had to think harder about besides "what are list comprehensions?" I know I'll be whiteboarding something during the interview, and although I'm confident, it'd be silly to not refresh some things.

edit:

So far, I'm going to be brushing up on multiprocessing vs. threads, along with the Global Interpreter Lock

edit2:

VVV I've name dropped the big libraries I've used before, so yeah, I need to make sure I'm clear there. You also mentioned some I haven't used so that's a point.

Lurchington fucked around with this message at 21:28 on Aug 2, 2010

tripwire
Nov 19, 2004

        ghost flow
I haven't myself done a python dev interview but I think it wouldn't hurt to be able to say you know the basics of a few popular python libraries/frameworks like maybe twisted or eventlet, numpy, tkinter or maybe pyqt or pygtk (some kind of gui experience basically), although you have Django covered.

b0lt
Apr 29, 2005

Lurchington posted:

Alright, I have an in-person technical interview for a python development job, and it's my first one ever really (I've been doing project management for the last 6 years).

It hasn't been stated, but I think I'd be working with Django and probably relational databases of one kind or another.

Those of you who've done a python dev tech interview, were there any good resources that you thought helped prepare you? Or alternatively, anything non-job specific you had to think harder about besides "what are list comprehensions?" I know I'll be whiteboarding something during the interview, and although I'm confident, it'd be silly to not refresh some things.

edit:

So far, I'm going to be brushing up on multiprocessing vs. threads, along with the Global Interpreter Lock

edit2:

VVV I've name dropped the big libraries I've used before, so yeah, I need to make sure I'm clear there. You also mentioned some I haven't used so that's a point.

It might be helpful to brush up on itertools/functools, they're pretty handy and will make your whiteboard examples more impressive.

Adbot
ADBOT LOVES YOU

nbv4
Aug 21, 2002

by Duchess Gummybuns
Does anybody know of a RSS feed or something one can subscribe to thats comprehensive on all the goings on of the python community? Apparently there was a loving pycon 20 minutes from where I live a few days ago but I missed it because I had no idea it was going on.

  • Locked thread