?

Log in

LiveJournal for python.

View:User Info.
View:Friends.
View:Calendar.
View:Memories.
You're looking at the latest 20 entries. Missed some entries? Then simply jump back 20 entries.

Tuesday, October 19th, 2010

Subject:Grabbing image from foreign window via PyQt / Linux
Posted by:oversider_kosma.
Time:8:00 pm.
Greetings!

Please pardon my poor english, if readable at all. It isn't native language.

There is my PyQt application and there is window of some Other Program running at the same X11 display.

I found a good and easy receipt how to grab whole screen using QPixmap.grabWindow.

But I need to grab not the whole screen. Only image from this Other Program's window. Just like KSnapShot does it when I choose "window under cursor" and "not include window decorations" options.

QPixmap.grabWindow receives winId as it first parameter, but I don't know how can I get winId if I know PID of that Other Program or title of its window.

I've tried to google it but failed. =\
I've also tried to look into KSnapShot source code to understand how they had done it; but it seems like my Cpp or Qt level is not enough for understanding that.


Is there a more or less easy way to get winId of that foreign window or maybe some another overall way to grab image from foreign program window via Python?

Thanks!

PS: Sorry, if this question is stupid. I'm not very cool at Python and new to Qt.
Comments: Read 1 orAdd Your Own.

Friday, October 8th, 2010

Subject:Python 3 module import problem
Posted by:vorpal.
Time:1:07 pm.
Hi all!

Quick Python 3 question. I have a module I wrote in Python 2 and I'm trying to make it compatible with 3, but I'm having a bizarre error that I'm sure is extremely simple to fix. Here's the situation:

I have a directory for my module, say mymodule. Inside, I have an __init__.py file, and another file, say myfile.py. In __init__.py, I have the statement:

import myfile

However, when I'm in the directory containing mymodule, and I execute:

import mymodule

I get the following error:

ImportError: no module named myfile

This didn't happen in Python 2, and I'm not sure why it's happening in Python 3 or how to get __init__.py to properly search its own directory for modules when doing imports.

Can someone please help me or point me in the right direction?

Thanks so much, folks!
Comments: Read 2 orAdd Your Own.

Tuesday, April 6th, 2010

Subject:urlopen failing when used on Livejournal
Posted by:evilhat.
Time:7:20 pm.
I maintain a Python-based Livejournal client, Charm.

Today, my client authentication attempts consistently fail on timeouts. I picked my code apart, trying to figure out what the heck had gone wrong, since http://www.livejournal.com/interface/flat is perfectly accessible via brower.

However, calling urllib.urlopen() or urllib2.urlopen() on the interface URL fails.
For that matter, doing so on http://www.livejournal.com fails.

Anyone have any explanation for why this should be the case, and how to fix it? It's definitely not my computer -- I've now tested three machines, three different versions of Python, and various other URLs (including the posting interface for Deadjournal), and I'm pretty certain that the issues seem restricted to Livejournal.

wget, by the way, also fails, although not 100% of the time:

--2010-04-06 19:21:33--  http://www.livejournal.com/interface/flat
Resolving www.livejournal.com... 208.93.0.128
Connecting to www.livejournal.com|208.93.0.128|:80... connected.
HTTP request sent, awaiting response... No data received.
Retrying.

--2010-04-06 19:22:06--  (try: 2)  http://www.livejournal.com/interface/flat
Connecting to www.livejournal.com|208.93.0.128|:80... connected.
HTTP request sent, awaiting response... No data received.
Retrying.

--2010-04-06 19:22:39--  (try: 3)  http://www.livejournal.com/interface/flat
Connecting to www.livejournal.com|208.93.0.128|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 53 [text/plain]
Saving to: `flat'
Comments: Read 6 orAdd Your Own.

Monday, March 22nd, 2010

Subject:Python v. Tcl/Tk (denting & tweeting)
Posted by:tonytraductor.
Time:8:28 pm.
python v. tcl/tkSo. I have now made two little denter/tweeter programs (to send updates to twitter.com and identi.ca), one with Tcl/Tk, the other with Python. I figured a little comparison, perhaps, was in order.
If you look at them, of course, they look, well, just about the same. Tkinter is, after all, analogous to Tk.

 

The Tcl/Tk program made it incredibly simple to display the response from the remote server, which I haven't succeeded in doing with the python script, yet. Both rely on calling an external program (curl) to send updates, rather than relying on the languages' built-in tools. I could probably work out HTTP POST in tcl rather painlessly. I did try to use python's urllib to post, unfruitfully, and resorted back to calling curl.


the code for both programs is available at the above wiki links

The Tcl/Tk program, which has the added feature of displaying the server response, has only 47 lines of code, 245 words, 1844 characters. It took me less than an hour to write it.
The Python program, however, which does precisely the same exact thing as the tcl/tk program, without displaying the server response, has 104 lines of code, 564 words, and 4073 characters. It took me the better part of a day to write it.  Oh, but the python program tells you if your update is too long, something I didn't program into the tcl/tk script, yet.  There's a plus.

 

One must ask oneself, of course, is this a testament to the power and simplicity of tcl/tk? Or, is it simply an indication of my lack of skill with python?

I can't answer that defnitively, but, to me, it really looks like tcl/tk is a bit more efficient. Admittedly, I'm not a very skilled programmer at all, in truth. Timewise, of course, I have been writing tcl/tk for a couple of years, and only just now delving into python. As such, I was able to throw the tcl/tk program together quickly, while, my efforts to "translate" my tcl/tk program into python required a bit of research on the syntax for writing tkinter guis, and other elements. It just really looks to me as though Python/Tkinter takes a lot more code to do the same thing. I really have drawn that conclusion. Especially building a gui, it seems, is more cumbersome with tkinter than with simple, good old tcl/tk. I know there are other means of building a gui with python (wxwidgets, pygtk, pyqt, etc.), but I wanted to try the one most similar to that with which I am already familiar, and, I believe it is a fairer comparison when using a similar gui ToolKit.

 

At this juncture, I do have to say, I feel a great loyalty and deep affinity for tcl/tk. I don't understand why it isn't in wider use, frankly. It is an incredibly powerful language, used for a vast array of purposes, and, in my opinion, is probably the easiest programming language to learn (of course, I haven't tried them all), especially for a beginning programmer. One can be up and running, creating useful programs in a relatively short time. I also feel the need to give kudoz to the tcl/tk community and the tcl.tk wiki, which is replete tons of example code, detailed explanations, and great resources for learning how to program in tcl/tk. The tcl-ers that hang out at #tcl on irc.freenode.net, additinoally, are extremely helpful, and patient. They won't hold your hand, but they'll tolerate a newbie, and point them in the right direction, without any snobbishness or derision.

I can't say the same for my experiences with pythonistas. Their irc channel was a little less friendly, imho. Maybe I just caught them on a bad day, or maybe I was having a bad day. After all, Pythonistas are known for having a sense of humor. Admittedly, I was frustrated when I finally went to their channel for a bit of support, and frustrated, whiny n00b is no fun to play with, any way. Moreover, the python community does have a lot of documentation available online. Nonetheless, to me, it seems that it is written for other programmers, not for the uninitiated, so, is not so easily read as much of the tcl/tk resources. Their sample code is not well explained, where someone new to programming can really make sense of it. This may also be a function of time, since tcl/tk has been around a bit longer than python.

 

I do want to make it very clear: I'm really not here to pick on python. I know that it's a powerful language with a great many uses, and a favorite of a great many real hackers who know a lot more about programming than I do. I will continue to learn to write it, and believe it will serve me quite well for various purposes, and I believe I will continue to have fun learning it. But, I think I might continue to point out how tcl/tk is much easier and seemingly efficient, too...

 
Comments: Read 27 orAdd Your Own.

Saturday, November 7th, 2009

Subject:"truncate" the beginning of a file?
Posted by:6ferrets.
Time:4:08 pm.
I hope somebody's still out there!

I haven't looked at Python in years, but I'm hoping to come up with a quick & easy way to remove the first X characters from a file, something like file.truncate but from the beginning of a file.

Does that already exist, or will I need to do it by hand? Thanks!
Comments: Read 2 orAdd Your Own.

Thursday, June 11th, 2009

Subject:There's something I'm not understanding with lambdas here
Posted by:ivorjawa.
Time:10:34 am.
This isn't behaving at all how I would expect:


>>> nodes = [ [1], [2], [], [4], [], [] ]
>>> nodes
[[1], [2], [], [4], [], []]
>>> lam = [(lambda : node) for node in nodes]
>>> lam[0]()
[]
>>> lam[1]()
[]
>>> lam[2]()
[]
>>> lam[3]()
[]
>>> lam[4]()
[]
>>> lam[5]()
[]
>>> 

>>> nodes = [ [1], [2], [3], [4], [5], [6] ]
>>> lam = [(lambda : node) for node in nodes]
>>> lam[0]()
[6]
>>> lam[1]()
[6]



eta
I guess I'm not the only person to have run into this:

Python’s lambda is broken!

And the hideous, absolutely insane fix is:


>>> lam = [lambda node=node: node for node in nodes]
>>> lam[0]()
[1]
>>> lam[1]()
[2]
Comments: Read 4 orAdd Your Own.

Tuesday, December 2nd, 2008

Posted by:sciucaro.
Time:7:27 am.
Not that I can do much with it now, but I'm curious if Pygame and online systems like Twisted or just the plain Socket and Threading modules work hand in hand, to make online graphical games.

Like how would it work? The last time I worked with sockets which was like 2 or so years ago, I was only able to send text back and forth, and that's about all I knew how to make it do, because I don't think it takes anything else other than strings, so that's how I got a text messaging program going...

What kind of information would I need to send to and from the server so that any party connected to the server can share the same game world. Would it be correct if the server held the game and data and did the blitting operations for each player's camera, and then send that blitted surface as a pickled variable to the client and have the client blit that pickled variable to the screen and then update? Or is there another way around?

I remember there were two types, one was called SOCK_STREAM which was like a stream-handling socket for on-the-spot signals like a text message, while SOCK_DATAGRAM (correct?) handled larger chunks of code, like for website HTMLs and thus was slower. I know STREAM would be used to send a signal to the server, probably in a string, but how would I return an entire surface to be displayed on the client right back at runtime.

I'm in the middle of snooping around OpenRTS (which was written in Python) to get an idea of what happens, so I know it can be done, but I thought I'd ask to see how it's done and which way would be easier or proper to work with.

thanks in advance
Comments: Read 5 orAdd Your Own.

Friday, November 21st, 2008

Posted by:sciucaro.
Time:4:58 pm.
Yet again I have another Pygame question, and I apologize in advance if my question is very unclear.

After tearing a few games apart from the website, I saw that the games use something like "chapters" or "scenes", where there is a class of something like the "Main Menu" loop, or like a "Level1" loop, etc.

So what I found was that the main file, the .py file I open to run the game initially, would serve as the mother loop that collects returned results from these objects as they close to open up the next object when the iteration reads it.

For example, the game runs and automatically opens up a title/mainmenu loop object, and when a selection is made, the loop closes out, returning some form of data like a string or number back to the mother loop, and the next iteration of the mother loop would read that returned number, and open up the proper loop object, such as a high scores list or the first level.

My question is:

How do I get to communicate with the game's global constants while inside of an object's loop that would be running the section of the game I'm playing?

Like if I'm in the main menu, how would I get my selection to return the selection I want to open up the next loop object. Or while I'm in the game in a loop playing the level, how would I be able to get the camera object or the random.seed variable I had set up already in the main file so I don't have to create more instances inside the class?

The only way I got past this was to put everything I want inside the class as parameters when I call the Start() function to get its loop running. Unless I'm wrong, I would think that's pretty unnecessary, especially if I opened the game through the main file, where I should be able to communicate between everything easily.

Thanks in advance. btw you are all great help
Comments: Read 3 orAdd Your Own.

Sunday, November 16th, 2008

Subject:Unclear On Global Variable Use
Posted by:dotplaid.
Time:11:50 pm.
Hi all,

I have defined global variables that I *think* are passed to functions, but I'm running into a problem:

code under cut....Collapse )

While debugging I get the following error while converting from Cylindrical to Spherical:

Traceback (most recent call last):
  File "/home/dotplaid/PythonMyStuff/coordinate_transformer.py", line 86, in <module>
    radius, theta, phi = spherical("cylindrical", radius, theta, height)
  File "/home/dotplaid/PythonMyStuff/coordinate_transformer.py", line 52, in spherical
    phi = round(math.atan(radius/height),3)
UnboundLocalError: local variable 'radius' referenced before assignment


I presume that the error is thrown because I'm using the variable radius incorrectly, but I don't see how. I would really much rather not rename radius in order to use it, so I changed the order of use in the cylindrical and spherical functions thinking that I could use the radius that was passed in and then re-evaluate it.

Any insights that don't involve creating temporary (local) variables are most appreciated.

All the best,
.plaid

Comments: Read 7 orAdd Your Own.

Tuesday, October 28th, 2008

Subject:Time zones and DST?
Posted by:6ferrets.
Time:5:54 pm.
Given a date and a time zone, how do I tell whether that date is standard or daylight-saving time? Seems to me that this ought to be simple, but I'm going cross-eyed trying to find it in the library reference.
Comments: Read 5 orAdd Your Own.

Saturday, October 18th, 2008

Subject:to unicode from utf-8 back to utf-8 -- am I doing something pointless?
Posted by:util.
Time:2:34 pm.
In the following, does the conversion from UTF-8 bytes to Unicode and back again do anything useful other than validating the UTF-8?
import codecs
s = foo() #byte string
u = unicode(s, 'utf-8')
out = codecs.open('test.txt', 'w', 'utf-8')
out.write("%s\n" % u)
out.close()
If I'm fairly confident about the encoding, could I just as well say the following?
out = open('test.txt', 'w')
out.write("%s\n" % foo())
out.close()
Thanks!
Comments: Read 1 orAdd Your Own.

Tuesday, September 9th, 2008

Posted by:sciucaro.
Time:5:54 pm.
In Pygame, using 2D graphics, when you are trying to make a side-scroller or some sort of game that might allow for camera-like effects similar, do you have to update the entire background and level to give the effect of moving your character in it, or is there some sort of camera trick where only the character moves instead of the whole level, and there's some display object that will just follow the character and whatever is inside it will display?

I wish I had some sort of graphic to explain this. Like:

Imagine a big square (the level or background), a character (your character), and a small hollow rectangle (what the screen displays),all visibly on top of each other. When you move the character, does the hollow rectangle stay stationary and the character have a limited range to move, and the whole level square is what is moving for the effect? Or can the character freely move, have the rectangle follow the character and the level stay stationary?

Or is there an even better way to do this?

Thanks in advance.
Comments: Read 7 orAdd Your Own.

Sunday, September 7th, 2008

Subject:OOP and framework cooperative reuse...
Posted by:f_lynx.
Time:12:39 pm.
I've been hitting this problem for a couple of years now...

here it is, in short: we have an algorithm or a set of algorithms that operate on one or several "terms", this is usually called a framework and implemented as a relatively monolithic entity (usually but not necessarily), with several customization points, and is used by replacing/customizing these points to configure or change the provided functionality. there are numerous examples of this approach among which are the Python's logging package and the Twisted framework, to name a couple of big ones, on the smaller scale there are things like UserDict, ...etc. this approach works quite well but has two rather big weaknesses:

  1. the bigger things get the more unnecessary complexity of design and implementation there are and in some (if not most) cases this also relates to complexity of use...

  2. a framework is extremely hard to to implement in a way for it to be reused several times within one context...




the second point may need a little explaining. let us consider this example: we have several frameworks that simplify pythons dict creation and use, these usually require the user to define only tree or four special methods and implement the rest of the dict interface on top of that... quite straight forward, indeed. so to demo the above concept let's try and implement an object that acts as a dict and at the same time responds to a special attribute interface, both protocols access different data stores and are essentially independent, but are almost identical in their base functionality.
read on...Collapse )
Comments: Read 5 orAdd Your Own.

Sunday, August 24th, 2008

Posted by:sciucaro.
Time:8:58 pm.
In wxPython, how do you manage the toggle on the TipProvider dialog that manages whether or not you want to see it again as you open the program? When I do it and leave the checkmark empty, and reopen the program, the dialog box is still present.

Like, is there an attribute for that checkbox in the dialog object so that when you click OK when the checkbox is off, you can change a line of text in the tip.txt file to manage the toggling, via read/write info in the tip file?

#enable_tip=0
#the above line is the toggle.
tip 1
tip 2

What I assume would be done is a method that opens this file with read/write, read the first line, last character to make sure it's on or off. If it's 1, enable, if not, then don't show it. I can always call the tip box back open so I can toggle that checkmark, but I can't find the attribute for that checkmark so I can do like:

pseudocode
if tipdialog is wx.ID_OK and checkbox is False:
write 0 in the first line of the tip file

Or is there another way around this?

EDIT:

Also, if I were to turn it off, but reopen the dialog in the middle of the program, how can I keep it off until I turn it on again?
Comments: Read 1 orAdd Your Own.

Thursday, July 10th, 2008

Posted by:sciucaro.
Time:12:29 am.
In wxPython, when I am making a new 'frame', I find it to be a cluster to the code when I am adding the methods for the Menu events, along with other functions for the program. It makes the program unnecessarily larger for one file, and I want to break it down to make it easier to maintain.

Is there a way I can store the methods in a separate .py file to import into the main program as methods for the main application frame object? Every other time I try, an error comes up, and it must be because there's a focus conflict or the way I wrote it.

This is what I would have:

frame object
- def __init__ stuff (initialize the frame, size, position, title, etc.)
- Menu setup (Piece together the main menu on top like submenus and listed menus)
- frame setup (sizers, buttons, etc.)
- LOTS of methods for different events

startup

What I think I want to do is move the methods to another .py file so it can be maintained like a library of methods, and the main program can import it easily.

Anything I could be missing?

Thanks in advance.
Comments: Read 3 orAdd Your Own.

Monday, April 14th, 2008

Posted by:zambarra.
Time:2:18 pm.
Hi all, I am new to the language and I'd like to solicit your opinion on the following behavior:

~$ python
Python 2.5.2 (r252:60911, Apr  8 2008, 21:49:41)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 3; b = 2
>>> c = 1+1
>>> a,b,c
(1, 2, 2)
>>> if c == (a or b): print 'success'
...
>>> if c == (b or a): print 'success'
...
success
>>>

Thanks,
z
Comments: Read 7 orAdd Your Own.

Wednesday, February 13th, 2008

Subject:Not so lost, but still a little.
Posted by:shootthecore.
Time:6:33 pm.
OK. After my first vague post, that was perhaps a bit more scatterbrained that I would have liked it to be due to being utterly frustrated, I decided to meet up with my professor to clarify some of the things I was confused about and it helped a lot. So, much, in fact, that I finished 2/3's of my computational linguistics assignment. I'd like to now elaborate about the assignment, what I was confused about, and what the solutions were. At the end of this clarification, I once again ask for help about the last bit that I am still stuck on!

The entire assignment revolves around a module written by the professor meant to illustrate some examples of FSA (Finite State Automata), both deterministic (only one possible transition between states; no epsilon transitions allowed) and non-deterministic (could be one or more possible transitions between states; epsilon transitions allowed). These FSA reflect "Sheep Language," which can be represented by the regular expression [ba*!] (one 'b' followed by one or more 'a' followed by '!').

The first exercise was to modify the NFSA class's 'recognize' method (verifies whether or not a given string belongs to Sheep Language and returns True or False) so that the user could specify whether a FIFO (First in First Out) search or LIFO (Last in First out) search would be implemented by the method. The original program only was capable of implementing a LIFO search, so the solution here was to create a new keyword argument (I called this depthFirst, which is another name for the LIFO search) and added a conditional to the recognize module, for which if depthFirst is True, it'd go through the original LIFO search, which uses a stack via pop(). If depthFirst is False, it'd instead go through my added code, which uses a queue via pop(0) (e.g. FIFO). I must have read the documentation on using lists as queues and stacks about 50 times, but for some reason it just didn't click.

OK, so the second exercise was to add a new method to the DFSA class that could return whether or not a given string was in the Sheep Language's complement language (e.g. strings that use the same alphabet as Sheep Language, but do not contain the actual strings in Sheep Language, such as 'abb!b') OK, so for this, I had to add a sink state (also known as a fail state) to the DFSA used. This means that all strings not in the Sheep Language are condemned to this sink state, never to leave. I then added a complement method to the DFSA class, which basically used the same code as recognize, except it accepts strings that end NOT IN a valid final state, and rejects those that do end in a valid final state. This way, strings not in the Sheep Language get accepted, but those strings still must have the same alphabet.


NOW, what I am stuck on...
The professor had us construct another NFSA that has epsilon transitions at every one of its states. This results in an infinite loop since an epsilon transition allows the search to go to the next state without moving the tape forward. Since it can do this at every state, the tape NEVER moves forward. The goal here is to modify the NFSA class so that these sort of detrimental NFSA return a ValueError. In theory, I THINK I know what I have to do, and I wanted to meet with the professor today, however, all of his courses and office hours were canceled for the day and so I did not get to meet with him.

Here is what I think I must do, but still do not know exactly how to accomplish it:
Keep track of what pops out of the agenda list (the list that contains the states to be looked at and the index number of the tape) and append that to a new 'closed' list. Before new items are added to the agenda, make sure that we aren't repeating ourselves. If we are, return ValueError. If not, add next thing to agenda.

For anyone interested in helping, the original code is here and the FSA I am dealing with is in Exercise 3 of this document.
Comments: Read 1 orAdd Your Own.

Saturday, February 9th, 2008

Subject:Completely lost...
Posted by:shootthecore.
Time:5:51 pm.
Hello, I am a linguistics major who has recently gotten pretty interested in the subfield of computational linguistics. The courses at school in this subject rely upon programming in Python, and though I've purchased a self-teaching book as well as searched through documentation, I'm finding myself a bit lost with regards to making Python do what my first assignment wants me to do. I am not sure if these sort of posts are allowed here, but if someone in the community would be willing to help clarify some things to me over aim or something, I would cry tears of joy.

My aim name is sairoplane or sarieses

Thank you!
Comments: Read 5 orAdd Your Own.

Saturday, December 15th, 2007

Subject:Useful FTP utility module
Posted by:nomadphoenix.
Time:1:41 am.

Found this while researching some improvements for an automated file grabber library:

http://ftputil.sschwarzer.net/trac

Basically it objectifies the FTP transaction, providing iterators for directory listings, File like objects for remote files, and a number of os.path like function/methods that I've found to be an incredible improvement over my own Python newb abilities.

Comments: Add Your Own.

Wednesday, December 5th, 2007

Subject:One convert at a time
Posted by:grimmtooth.
Time:1:36 pm.
Actually, if you read XKCD, you already saw this. And if you don't, you'll wonder what the fuss is all about.

Nevertheless: http://xkcd.com/353/

Wait until he tries from __future__ import *
Comments: Read 1 orAdd Your Own.

LiveJournal for python.

View:User Info.
View:Friends.
View:Calendar.
View:Memories.
You're looking at the latest 20 entries. Missed some entries? Then simply jump back 20 entries.