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
Tap
Apr 12, 2003

Note to self: Do not shove foreign objects in mouth.
Noob Question:

Is there a way to add a path where your scripts are located for the python interpreter to read from so I don't have to insert the path everytime I want to execute a script?

For example, instead of running:

code:
python /Users/{myname}/Documents/Programming/Projects/htdocs/python_scripts/odbchelper.py
I want to be able to run

code:
python odbchelper.py
Thanks in advance.

Adbot
ADBOT LOVES YOU

deimos
Nov 30, 2006

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

Tap posted:

Noob Question:

Is there a way to add a path where your scripts are located for the python interpreter to read from so I don't have to insert the path everytime I want to execute a script?

For example, instead of running:

code:
python /Users/{myname}/Documents/Programming/Projects/htdocs/python_scripts/odbchelper.py
I want to be able to run

code:
python odbchelper.py
Thanks in advance.

Why don't you put python_scripts on your PATH, give odbchelper.py the proper header (shebang line: #!/usr/bin/env python
) and chmod +x it and just run odbchelper.py?

You can also symlink odbchelper.py to a directory already on your PATH.

deimos fucked around with this message at 16:44 on Dec 29, 2009

Tap
Apr 12, 2003

Note to self: Do not shove foreign objects in mouth.

deimos posted:

Why don't you put python_scripts on your PATH, give odbchelper.py the proper header (shebang line: #!/usr/bin/env python
) and chmod +x it and just run odbchelper.py?

You can also symlink odbchelper.py to a directory already on your PATH.

Man, I feel like a tard. Thanks :)

wins32767
Mar 16, 2007

I have an object mapped to a db record through SQLAlchemy that I'm trying to pass the contents of through xml-rpc. Is there a quick way of mapping attributes of an object to a dictionary?

king_kilr
May 25, 2007

wins32767 posted:

I have an object mapped to a db record through SQLAlchemy that I'm trying to pass the contents of through xml-rpc. Is there a quick way of mapping attributes of an object to a dictionary?

Really really quick is obj.__dict__.

wins32767
Mar 16, 2007

Yes, that's exactly what I was looking for. Thanks.

Dwanyelle
Jan 13, 2008

ISRAEL DOESN'T HAVE CIVILIANS THEY'RE ALL VALID TARGETS
I'm a huge dickbag ignore me
Hey, complete Python newbie here, just picking it up over the last day or so.

I've got a question. Here's some code I've written:

import random

print('Welcome to combat! An orc is attacking you! Do you wish to attack back?(yes or no)')

attackChoice = 0

input()

attackChoice = input()

if attackChoice == yes:
number = random.randint(1, 20)
number = str(number)
print = ('Your attack roll was ' + number)



Basically, what I want it to do, is if the user types in yes and hits enter, the program will generate a random number between 1 and 20, and tell the user "your attack roll was (whatever the number is).

However, when I run the program and type in yes and hit enter, nothing happens. When I then go to close the program, an error will come up telling me that "yes" in undefined. I thought I had tied it to the attackChoice variable? Or am I completely off base?

tef
May 30, 2004

-> some l-system crap ->
try raw_input() instead of input(), also you'll need quotes around the string "yes" in the program.

code:
>>> def ask():
...     value = raw_input('How are you ?')
...     print "This is how you are", value
... 
>>> ask()
How are you ?tired
This is how you are tired
>>> 

tef fucked around with this message at 19:07 on Dec 30, 2009

Ussr
Sep 17, 2004

Wait, what?

Thalantos posted:

-code-

Hey buddy, couple of things.

You don't need this, attackChoice = 0
This is incorrect syntax, print = ('Your attack roll was ' + number)
You don't need this, input()
--edited out wrong code--
and add quotes around yes because its a string not a variable. if attackChoice == "yes":

edit: code removed

Ussr fucked around with this message at 20:58 on Dec 30, 2009

king_kilr
May 25, 2007
I think he might be using py3k (since print = doesn't syntax error immediately), in which case doing input() instead of raw_input() is correct.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

If people are starting to use that reasonably often, we should probably put a note in the OP telling people to make it clear. (And to not use it at all yet, if they can.)

Ussr
Sep 17, 2004

Wait, what?

king_kilr posted:

I think he might be using py3k (since print = doesn't syntax error immediately), in which case doing input() instead of raw_input() is correct.

I'm sorry, that's my mistake. input() instead of raw_input() for 3.1. And yes print = ("string") wont error, it'll just not display the print text after the input is entered.

Ussr fucked around with this message at 20:59 on Dec 30, 2009

Dwanyelle
Jan 13, 2008

ISRAEL DOESN'T HAVE CIVILIANS THEY'RE ALL VALID TARGETS
I'm a huge dickbag ignore me

Jonnty posted:

If people are starting to use that reasonably often, we should probably put a note in the OP telling people to make it clear. (And to not use it at all yet, if they can.)

Yeah, I've got version. 3.1.1

Should I be using something else?

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

Thalantos posted:

Yeah, I've got version. 3.1.1

Should I be using something else?

If you're using Python for fun, 3.x is fine. If you're trying to do something useful, use 2.6 because many libraries aren't available for 3.x yet.

Dwanyelle
Jan 13, 2008

ISRAEL DOESN'T HAVE CIVILIANS THEY'RE ALL VALID TARGETS
I'm a huge dickbag ignore me

A A 2 3 5 8 K posted:

If you're using Python for fun, 3.x is fine. If you're trying to do something useful, use 2.6 because many libraries aren't available for 3.x yet.

Yeah, I'm just trying to learn how to program. I found an online book that's actually been really helpful in learning to grok the concepts, which is cool.

I'm thinking I'd mostly write RPGs or strategy games.

Ussr
Sep 17, 2004

Wait, what?
You could probably be fine sticking with 3.1 since you're running a 3.1 interpreter anyway. There are a few significant differences between 2.6 and 3.1 that you will want to know if you're looking to do any serious programming. 2.6 will probably be the more common language when it comes to libraries, tutorials and the community for a couple of years.

If you wanted you could become a master of 3.1 and start porting the libraries over on your own. That would earn you a poo poo ton of geek cred... I'd love you for it.

edit: differences between 3.0 and 2.6 http://docs.python.org/dev/3.0/whatsnew/3.0.html

Dwanyelle
Jan 13, 2008

ISRAEL DOESN'T HAVE CIVILIANS THEY'RE ALL VALID TARGETS
I'm a huge dickbag ignore me

Revolver posted:

You could probably be fine sticking with 3.1 since you're running a 3.1 interpreter anyway. There are a few significant differences between 2.6 and 3.1 that you will want to know if you're looking to do any serious programming. 2.6 will probably be the more common language when it comes to libraries, tutorials and the community for a couple of years.

If you wanted you could become a master of 3.1 and start porting the libraries over on your own. That would earn you a poo poo ton of geek cred... I'd love you for it.

edit: differences between 3.0 and 2.6 http://docs.python.org/dev/3.0/whatsnew/3.0.html

Well, I think that might be a ways off, but I'm always looking to challenge myself. What are libraries? Are those anything like modules?

king_kilr
May 25, 2007

Thalantos posted:

Well, I think that might be a ways off, but I'm always looking to challenge myself. What are libraries? Are those anything like modules?

Libraries are just modules that intend to be reused. So for example there's the standard library. It consists of a bunch of modules for doing things (dealing with dates, times, csv files, your operating system, spawning new procceses, etc.). Plus there are *tons* of open source libraries for python!

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

I've only really skimmed through the changes, so was sort of under the impression that running that utility on 2.x compatible libraries would make them 3.x compatible instead. What more than that, and maybe some other superficial stuff, needs to be done? It looks like the C API has changed a fair bit, but what about pure Python stuff?

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Jonnty posted:

If people are starting to use that reasonably often, we should probably put a note in the OP telling people to make it clear. (And to not use it at all yet, if they can.)

I'm going to add it to the op tomorrow; and no - I'm not going to tell them not use it.

Scaevolus
Apr 16, 2007

Jonnty posted:

I've only really skimmed through the changes, so was sort of under the impression that running that utility on 2.x compatible libraries would make them 3.x compatible instead. What more than that, and maybe some other superficial stuff, needs to be done? It looks like the C API has changed a fair bit, but what about pure Python stuff?

I doubt 2to3 handles the new division scheme properly in all cases.

Scaevolus fucked around with this message at 04:21 on Jan 2, 2010

chips
Dec 25, 2004
Mein Führer! I can walk!
I think the point of the 2to3 tool is that you rework your 2.x code into forward compatible 2.6 code that can then be translated automatically to give valid 3.x code. So for example, as Scaevolus said, you'd need to make sure all your division operators are appropriate and that you aren't using any features that will be removed.

http://docs.python.org/dev/3.0/whatsnew/3.0.html#porting-to-python-3-0 explains the process pretty simply.

chips fucked around with this message at 18:18 on Jan 1, 2010

maskenfreiheit
Dec 30, 2004
Edit: doublepost

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

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

GregNorc posted:

return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]

Missing closing parenthesis here.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

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

No Safe Word
Feb 26, 2005

GregNorc posted:

Ah I see.

Why did interpreter thought the error was on line 15 instead of line 13? (Probably would be good for me to know this for future debugging)

Because that's where it thought the parentheses were closed for that one and so it really thought that Card(3,3 was unclosed within the other parentheses.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

GregNorc posted:

Ah I see.

Why did interpreter thought the error was on line 15 instead of line 13? (Probably would be good for me to know this for future debugging)

Because it was waiting for something else in the brackets, or the end of them, and instead got your next line which isn't what it wants. When you get a syntax error like that (in pretty much any programming language actually) always be aware that the actual error may happen before the syntax checker notices it.

tripwire
Nov 19, 2004

        ghost flow
The flipside of that is you can use parenthesis to split things up onto multiple lines for clarity.

Rather than

code:
def foo( parameters_a, parameters_b, parameters_c = 'default', parameters_d = None, parameters_e = True):
    <some code>
I'd use that as an opportunity to do this instead:
code:
def foo( parameter_a,
         parameter_b,
         parameter_c = 'default',
         parameter_d = None,
         parameter_e = True):
    <some code>
Wherever you have a parenthesis you can do that.

I think this may violate the python style guide, but I prefer the way it looks.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

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

UnNethertrash
Jun 14, 2007
The Trashman Cometh
I'm sure there is a better way, but since I've never even slightly contributed before I suppose I'll take a bash at it.

You could make a dictionary where the keys are the strings "hand1" etc. and the values are the objects. So it would be something like:

code:
d = dict()
for x in range(4):
    d["hand" + String(x + 1)] = Hand()
If this is a bad idea then let me know and I'll delete the whole thing because I'm just guessing anyway/trying to be helpful for once.

Edit: I suppose you could simplify this same idea by making a list (Hands) of the objects, and then just referring to them by the indices. So in your case "hand1" is hands[0].

UnNethertrash fucked around with this message at 23:54 on Jan 2, 2010

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

GregNorc, you should try out the python forums beginner section, when I first started programming that's what I did, it allowed me to ask dumber questions and there's a lot of people willing to slowly explain stuff to you.

They don't mind if you ask 10 questions a day.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

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

tehk
Mar 10, 2006

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

GregNorc posted:

How could I write a loop so that if say, the value of num_hands was say, 15, I could create 4 hands... one named hand1, one named hand2, one named hand3 and so on?

Thanks for the help.
I would do something like making Deck a generator which pulls cards randomly from a pool of items.

code:
# Make the Deck class a generator of sorts that has a method like next(), or
# in this case dealcard() which grabs another random card from the deck. 
# It should also have some thing like Deck.cards or __len__

stud_deck = Deck()

def deal(deck, players, cards):
    if players * cards > deck.cards:
        raise ValueError("%d cards requested, while only %d cards provided in the deck"
                         % (players * cards, deck.cards))
    game = {}
    for player in xrange(1, players + 1):
        game["hand" + str(player)] = [deck.dealcard() for card in xrange(cards)]
    return game

mydeck = deal(stud_deck, 4, 17)

for key in mydeck:
    print key, mydeck[key]
edit: Woops I left my window open too long without refreshing.

tef
May 30, 2004

-> some l-system crap ->

GregNorc posted:

I've got a class called "hand" which inhereits a bunch of stuff from a class "deck'. It also has a few methods of it's own.

A card is not a type of deck. What operations apply to both? And can you easily substitute a single card for a deck of cards?

I.e a Cuckoo is a type of bird, but a Single Cuckoo is not a type of flock.

Inheritance is a very easy way to shoot yourself in the foot.

I would suggest avoiding classes altogether and just living with tuples of (1,"hearts") until you've got your head around some of the larger concepts.

tef fucked around with this message at 04:57 on Jan 3, 2010

blorpy
Jan 5, 2005

Wait just a second, GregNorc. A child murderer like yourself shouldn't be drawing people into this without telling them that their help may be part of a war crime. It's not really fair.

tef
May 30, 2004

-> some l-system crap ->
Python by default doesn't care about the death of children:

quote:

signal.SIG_DFL
This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCHLD is to simply ignore it.

tef
May 30, 2004

-> some l-system crap ->
Finally, avoiding modelling this problem beyond using a tuple:

code:
>>> def deal(nhands, ncards):
...     deck = [(x,y) for x in xrange(1,14) for y in "SHCD"]
...     dealt = random.sample(deck, nhands*ncards)
...     return [dealt[n::nhands] for n in range(0,nhands)]
... 
>>> deal(3,2)
[[(3, 'S'), (6, 'D')], [(9, 'D'), (7, 'S')], [(13, 'C'), (10, 'C')]]
:q:

tripwire
Nov 19, 2004

        ghost flow

tef posted:

Python by default doesn't care about the death of children:
aahahahahha

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

tef posted:

Python by default doesn't care about the death of children:

:rimshot:

Adbot
ADBOT LOVES YOU

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

I'm using urllib2 to download a rar file, but its coming up as corrupt despite it being the correct size. What's something special I need to do?

  • Locked thread