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
Thermopyle
Jul 1, 2003

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

Shaocaholica posted:

How do I use non scrolling output? For instance, if I want to draw a progress bar in the terminal? Is there something I should be using other than print and sys.stdout.write()?

I typically do something like:

code:
for i in range(10):
    print str(i) + "\r",
The \r returns to the line beginning and the comma at the end suppresses the newline.

Adbot
ADBOT LOVES YOU

Shaocaholica
Oct 29, 2002

Fig. 5E

Thermopyle posted:

The \r returns to the line beginning and the comma at the end suppresses the newline.

That didn't work with python 3.1 in windows. Sorry if I didn't mention that before. I got a similar behavior with calling 'cls' and writing my own message but I'm not sure if this is a good way to do it. And it would obviously not work in a *nix OS.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Ncurses?

Shaocaholica
Oct 29, 2002

Fig. 5E

KARMA! posted:

Ncurses?

Not available for windows.

Shaocaholica
Oct 29, 2002

Fig. 5E
Well, here's a new one. How can I get a list of partitions and their labels in windows? Not just drive letters but also their string labels.

Edit: nm, found it:
code:
t = win32api.GetVolumeInformation("C:\\")

Shaocaholica fucked around with this message at 09:49 on Jul 6, 2010

b0lt
Apr 29, 2005

Shaocaholica posted:

That didn't work with python 3.1 in windows. Sorry if I didn't mention that before. I got a similar behavior with calling 'cls' and writing my own message but I'm not sure if this is a good way to do it. And it would obviously not work in a *nix OS.

If by non scrolling, you mean not appending a newline to everything you call print on, print("foo", end="").

Shaocaholica
Oct 29, 2002

Fig. 5E

b0lt posted:

If by non scrolling, you mean not appending a newline to everything you call print on, print("foo", end="").

Note quite. I mean clearing the whole terminal between writes so you can animate a progress bar, etc. Most CLI encoding tools do this and so do most text based downloaders on *nix. Another tool that comes to mind is *nix 'top' which updates the whole terminal without appending.

ATLbeer
Sep 26, 2004
Über nerd

Shaocaholica posted:

Not available for windows.

wcurses

Hughlander
May 11, 2005

Shaocaholica posted:

How do I use non scrolling output? For instance, if I want to draw a progress bar in the terminal? Is there something I should be using other than print and sys.stdout.write()?

http://code.activestate.com/recipes/576986-progress-bar-for-console-programs-as-iterator/

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Shaocaholica posted:

That didn't work with python 3.1 in windows. Sorry if I didn't mention that before. I got a similar behavior with calling 'cls' and writing my own message but I'm not sure if this is a good way to do it. And it would obviously not work in a *nix OS.

That's just because it's a python2 style print statement. Most people assume python 2 unless specifically told otherwise.

Change it to something like print('%s\r' % i, end="") and it does work.

Shaocaholica
Oct 29, 2002

Fig. 5E

Ok, I got that working and it seems to do what I want but it only works if you only write one line.

Thermopyle
Jul 1, 2003

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

Shaocaholica posted:

Ok, I got that working and it seems to do what I want but it only works if you only write one line.

I understand your frustration with this.

I first learned to program nearly two decades ago using QBasic, which had the awesome LOCATE statement which moved the cursor to any location on the text console. I wrote a whole text-based windowing system with that.

Python's abilities in this area have left me wanting more.

yippee cahier
Mar 28, 2005

Sailor_Spoon posted:

That's just because it's a python2 style print statement. Most people assume python 2 unless specifically told otherwise.

Change it to something like print('%s\r' % i, end="") and it does work.

print('%s' % i, end="\r") might be a little cleaner looking

Stabby McDamage
Dec 11, 2005

Doctor Rope

Thermopyle posted:

I understand your frustration with this.

I first learned to program nearly two decades ago using QBasic, which had the awesome LOCATE statement which moved the cursor to any location on the text console. I wrote a whole text-based windowing system with that.

Python's abilities in this area have left me wanting more.

I know exactly what you mean, and I believe that's what ncurses is for.

The reason it's not as easy is that QBasic is built on DOS, which has a very simple terminal with fixed sizing. The modern terminal is much more complicated, and the common case it was designed for (stream IO) isn't really compatible with canvas-like operations. So you need a lot more software than just a locate() function to get it right...what happens when the user resizes the terminal?

Anyway, in most cases, if you're writing a curses app, you're clearly doing something fairly complicated, so I'd consider decoupling the operation from the interface, like deluge does.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

sund posted:

print('%s' % i, end="\r") might be a little cleaner looking

print(i, end="\r") :P

sonic bed head
Dec 18, 2003

this is naturual, baby!
I am using myconnpy instead of the usual mysql db connector because I don't want to try to compile it on many different machines. The problem I am having is figuring out how to escape strings appropriately. I can't find an escape method on the db. Any idea how I can do it correctly? Thanks.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

sonic bed head posted:

I am using myconnpy instead of the usual mysql db connector because I don't want to try to compile it on many different machines. The problem I am having is figuring out how to escape strings appropriately. I can't find an escape method on the db. Any idea how I can do it correctly? Thanks.

Try oursql. It has real parameterization so you don't need to worry about that crap.

sonic bed head
Dec 18, 2003

this is naturual, baby!

MEAT TREAT posted:

Try oursql. It has real parameterization so you don't need to worry about that crap.

I'm trying to avoid using the compiled mysql libraries. Something written in native python would be the best.

clams
Apr 10, 2007

rawr.
i've been doing some programming with pygame recently and since switching over to a mac (snow leopard) i have been getting 'no module named pygame' import errors.

i'm using NetBeans 6.9 RC2 with Python 2.6.5 and pygame 1.9.1

i've tried re-installing both python and pygame but i really have no idea what i'm doing when it comes to configuring IDEs. how do i make NetBeans see pygame?

tripwire
Nov 19, 2004

        ghost flow

clams posted:

i've been doing some programming with pygame recently and since switching over to a mac (snow leopard) i have been getting 'no module named pygame' import errors.

i'm using NetBeans 6.9 RC2 with Python 2.6.5 and pygame 1.9.1

i've tried re-installing both python and pygame but i really have no idea what i'm doing when it comes to configuring IDEs. how do i make NetBeans see pygame?

Is netbeans using your python 2.6.5 installation? I've heard it uses some internal jython compiler instead and thats probably the problem you're experiencing. See if you can find some option to specify which python its using.

Haystack
Jan 23, 2005





clams posted:

i've been doing some programming with pygame recently and since switching over to a mac (snow leopard) i have been getting 'no module named pygame' import errors.

i'm using NetBeans 6.9 RC2 with Python 2.6.5 and pygame 1.9.1

i've tried re-installing both python and pygame but i really have no idea what i'm doing when it comes to configuring IDEs. how do i make NetBeans see pygame?

Something is probably loving up your pythonpath. I had something similar happen recently; it turned out that a random .pth in my site-packages folder was redirecting an important part of my import namespace.

Shaocaholica
Oct 29, 2002

Fig. 5E
Can someone show me where the documentation is that explains how this works:
code:
>>> M = [[1, 2, 3], [4,5,6], [7,8,9]]
>>> [row[1] for row in M]
[2, 5, 8]
Also, what other not common ways to do stuff are there with Python?

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

Shaocaholica posted:

Can someone show me where the documentation is that explains how this works:
code:
>>> M = [[1, 2, 3], [4,5,6], [7,8,9]]
>>> [row[1] for row in M]
[2, 5, 8]
Also, what other not common ways to do stuff are there with Python?

This is probably what you want: http://docs.python.org/tutorial/datastructures.html#list-comprehensions

Thermopyle
Jul 1, 2003

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

Shaocaholica posted:

Also, what other not common ways to do stuff are there with Python?

I like that you can use conditionals in list comprehensions.

code:
>>> [row[1] for row in M if row[2] > 3]
[5, 8]
>>> [row[1] for row in M if row[2] > 3 or row[2] == 3]
[2, 5, 8]

tripwire
Nov 19, 2004

        ghost flow

Thermopyle posted:

I like that you can use conditionals in list comprehensions.

code:

>>> [row[1] for row in M if row[2] > 3]
[5, 8]
>>> [row[1] for row in M if row[2] > 3 or row[2] == 3]
[2, 5, 8]


The ternary is also really useful in comprehensions:

['%d is even'%i if (i%2)==0 else '%d is odd'%i for i in xrange(20)]

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

haha I never thought of that

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Shaocaholica posted:

Can someone show me where the documentation is that explains how this works:
code:
>>> M = [[1, 2, 3], [4,5,6], [7,8,9]]
>>> [row[1] for row in M]
[2, 5, 8]
Also, what other not common ways to do stuff are there with Python?

I don't know if this is what you really meant to say, but list comprehensions are a common way to do things in python. They are generally preferred in many situations that would be done with map or filter in other languages.

Mr. Clark2
Sep 17, 2003

Rocco sez: Oh man, what a bummer. Woof.

As part of my ongoing process to teach myself Python, I'm trying to write a small application that will take some user input and post it to twitter. I wrote a console version of the program that works great but I want to try and make a GUI version as well.
Here is what I have so far (please keep in mind that I am extremely new to programming)
code:
# Imports
from tkinter import *
import urllib.request

# Define post_to_twitter function
def send_to_twitter(msg):
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API",
                                  "http://twitter.com/statuses", "my username", "my password")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)
    params = urllib.parse.urlencode ( {'status' : msg} )
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.xml", params)
    resp.read()

# Create the window
app = Tk()
app.title("Twitter")
app.geometry("300x200+200+100")

# Create the text entry field
message = Text(app, height = 5, width = 150, wrap = "word")
message.pack(padx = 10, pady = 10)
contents = message.get("1.0", END)


# Create the button to post
post = Button(app, text = "Post", command = send_to_twitter(contents))
post.pack()

# Create the button to clear the text entry field
clear_button = Button(app, text = "Clear", command = message.delete(1.0, END))
clear_button.pack()

app.mainloop()
The problem is this: absolutely nothing gets posted to twitter. Additionally, the "Clear" button doesnt clear the text box. I know for sure that the send_to_twitter function works, I copied it from a book and I tested it from the console. I'm guessing that my problem lies in the ("1.0", END) part of the code not actually getting the contents of the text box, but according to this page (not quite half way down): http://effbot.org/tkinterbook/text.htm it says, "To fetch the text contents of the widget, use the get method: contents = text.get(1.0, END)". Maybe I'm using the wrong indexes? Can someone please point me in the right direction? Thanks in advance.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

Mr. Clark2 posted:

As part of my ongoing process to teach myself Python, I'm trying to write a small application that will take some user input and post it to twitter. I wrote a console version of the program that works great but I want to try and make a GUI version as well.
Here is what I have so far (please keep in mind that I am extremely new to programming)
code:
# Imports
from tkinter import *
import urllib.request

# Define post_to_twitter function
def send_to_twitter(msg):
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API",
                                  "http://twitter.com/statuses", "my username", "my password")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)
    params = urllib.parse.urlencode ( {'status' : msg} )
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.xml", params)
    resp.read()

# Create the window
app = Tk()
app.title("Twitter")
app.geometry("300x200+200+100")

# Create the text entry field
message = Text(app, height = 5, width = 150, wrap = "word")
message.pack(padx = 10, pady = 10)
contents = message.get("1.0", END)


# Create the button to post
post = Button(app, text = "Post", command = send_to_twitter(contents))
post.pack()

# Create the button to clear the text entry field
clear_button = Button(app, text = "Clear", command = message.delete(1.0, END))
clear_button.pack()

app.mainloop()
The problem is this: absolutely nothing gets posted to twitter. Additionally, the "Clear" button doesnt clear the text box. I know for sure that the send_to_twitter function works, I copied it from a book and I tested it from the console. I'm guessing that my problem lies in the ("1.0", END) part of the code not actually getting the contents of the text box, but according to this page (not quite half way down): http://effbot.org/tkinterbook/text.htm it says, "To fetch the text contents of the widget, use the get method: contents = text.get(1.0, END)". Maybe I'm using the wrong indexes? Can someone please point me in the right direction? Thanks in advance.

I'm not at all familiar with tkinter, so there may be other problems, but the one I can see is in your creation of the Button. You're passing the result of the function you mean to pass as the "command" argument, rather than the actual function. To do that, take away the brackets at the end. So, for instance, the first one should be

code:
post = Button(app, text = "Post", command = send_to_twitter)
instead.

Mr. Clark2
Sep 17, 2003

Rocco sez: Oh man, what a bummer. Woof.

Jonnty, thanks for the response. I tried what you suggested and then this error is generated when clicking on the Post button:
code:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
    return self.func(*args)
TypeError: send_to_twitter() takes exactly 1 positional argument (0 given)
Any other suggestions?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Off the top of my head:
code:
message = Text(app, height = 5, width = 150, wrap = "word")
message.pack(padx = 10, pady = 10)

# Create the button to post
post = Button( app, text = "Post", command = lambda: send_to_twitter(message.get(1.0, END)) )

Mr. Clark2
Sep 17, 2003

Rocco sez: Oh man, what a bummer. Woof.

Avenging Dentist posted:

Off the top of my head:
code:
message = Text(app, height = 5, width = 150, wrap = "word")
message.pack(padx = 10, pady = 10)

# Create the button to post
post = Button( app, text = "Post", command = lambda: send_to_twitter(message.get(1.0, END)) )

Both buttons work perfectly now, thanks! My book completely failed to mention the whole 'lambda' bit. If it's not too much trouble could you give me a brief explanation of that part?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
A = lambda: foo() is equivalent to def A(): foo()

Basically a lambda is a way of defining a one-statement function inside of another expression. Generally when talking about lambdas people will also mention some stuff about closures, which I'm using. This isn't particular to the lambda syntax, since a regular function declaration (possibly inside of another function body) does this too. A closure pulls in the local variables you have and lets you reference them inside your inner function.

If you want to know more, a search for "closure" will give you plenty of details.

No Safe Word
Feb 26, 2005

So apparently Numpy supports Python 2.x and 3.x with the same codebase now and will be released soon but is available in their SVN trunk now:

http://www.mail-archive.com/numpy-discussion@scipy.org/msg26524.html

tripwire
Nov 19, 2004

        ghost flow

No Safe Word posted:

So apparently Numpy supports Python 2.x and 3.x with the same codebase now and will be released soon but is available in their SVN trunk now:

http://www.mail-archive.com/numpy-discussion@scipy.org/msg26524.html

gently caress yeah!!! About time.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

Avenging Dentist posted:

A = lambda: foo() is equivalent to def A(): return foo()

Fixed. :eng101:

Chris Awful
Oct 2, 2005

Tell your friends they don't have to be scared or hungry anymore comrades.
Has anyone run into the following error while trying to compile a script using pyopengl and pygame with py2exe? Google has left this issue unresolved.

code:
Traceback (most recent call last):
  File "Goon.py", line 3, in <module>
  File ".\OpenGL\GL\__init__.py", line 2, in <module>
    from OpenGL.raw.GL import *
  File ".\OpenGL\raw\GL\__init__.py", line 6, in <module>
    from OpenGL.raw.GL.constants import *
  File ".\OpenGL\raw\GL\constants.py", line 7, in <module>
    from OpenGL import platform, arrays
  File ".\OpenGL\arrays\__init__.py", line 22, in <module>
    formathandler.FormatHandler.loadAll()
  File ".\OpenGL\arrays\formathandler.py", line 37, in loadAll
    cls.loadPlugin( entrypoint )
  File ".\OpenGL\arrays\formathandler.py", line 44, in loadPlugin
    plugin_class = entrypoint.load()
  File ".\OpenGL\plugins.py", line 14, in load
    return importByName( self.import_path )
  File ".\OpenGL\plugins.py", line 28, in importByName
    module = __import__( ".".join(moduleName), {}, {}, moduleName)
  File ".\OpenGL\arrays\strings.py", line 8, in <module>
    psas = ctypes.pythonapi.PyString_AsString
  File "ctypes\__init__.pyo", line 366, in __getattr__
  File "ctypes\__init__.pyo", line 371, in __getitem__

  AttributeError: function 'PyString_AsString' not found

Shaocaholica
Oct 29, 2002

Fig. 5E
How do I get pyQt running in windows? I've installed "PyQt-Py3.1-gpl-4.7.4-1.exe" and Python 3.1 but when I go to get SIP, all I get are sources. Am I supposed to get a prebuilt version for windows somewhere?

Edit: oh wait, does PyQT only work with 32bit python?

Edit2: WTF, according to this:

http://images.autodesk.com/adsk/files/pyqtmaya2011.pdf

I've got to build PyQt and SIP for 64bit windows and I also need a compiler installed (VS2008). I don't mind building stuff in other OSs but I've never not been able to find prebuilt binaries for windows.

Shaocaholica fucked around with this message at 22:23 on Jul 14, 2010

Kosani
Jun 30, 2004
Ni ni.
I'm trying to write a python script that takes 10 or so jumbled words as an input and checks them against a much bigger list of words in order to, uh, 'unjumble' it.

my plan was basically this:

the characters in every word in the main list are re-arranged alphabetically. The characters of the input words are also re-arranged alphabetically. This way the jumbled words can be matched up and then spit back out as a non-jumbled word.

My problem is that I don't even know where to begin. So far I've basically figured out how to get python to retrieve a text file and list each word as a re-arranged jumble of characters arranged alphabetically.

code:
text_file = open("wordlist.txt", "r")
for line in text_file:
    print sorted(line)
text_file.close()
it gives me an output that looks like this:
code:
['\n', '\r', 'l', 'm', 'n', 'o', 'o', 'o', 'p', 'y']
['\n', '\r', 'l', 'm', 'n', 'o', 'o', 's']
['\n', '\r', 'm', 'm', 'o', 'o', 'o', 'o']
['\n', '\r', 'm', 'o', 'r', 's', 't', 'y']
['\n', '\r', 'n', 'o', 'o', 'o', 'r', 't', 't']
['\n', '\r', 'n', 'o', 'o', 'p', 's', 'y']
['\n', '\r', 'o', 'p', 'p', 'r', 's', 't', 'u']
['\n', '\r', 'o', 'p', 'r', 's', 's', 't']
except a lot longer. I have no idea where to go from here. I really want to learn but man I feel like its kinda brutal figuring stuff out on your own for the first time.

Kosani fucked around with this message at 01:35 on Jul 15, 2010

Adbot
ADBOT LOVES YOU

No Safe Word
Feb 26, 2005

change that to print ''.join(sorted(line)) and you will get the strings you're looking for

  • Locked thread