SoulMazer 26 Posting Whiz in Training

Hi all, I'm working on a (Python) program which, in short, is a threaded TCP socket server which creates a new "tab" in a wx.Notebook widget for every incoming connection it sees. I've run into a strange problem where when I call notebook.AddPage(...), one of three things happens:

  1. A "tab" correctly appears for the new page
  2. No new "tab" appears, even though if I call GetPageCount() on the notebook, it returns the correct value
  3. I receive the following error: "*** glibc detected *** python: double free or corruption (fasttop): 0x000000000164dbe0 ****" followed by a very long backtrace with a cryptic memory map.

Since it would be inconsiderate to post all of my code here, I wrote a little script (based on something I found online) which also exhibits this behavior (although it works correctly most of the time).

import wx
from wx.lib.pubsub import Publisher
import thread
import time

# Some classes to use for the notebook pages.  Obviously you would
# want to use something more meaningful for your application, these
# are just for illustration.

class PageOne(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        t = wx.StaticText(self, -1, "This is a PageOne object", (20,20))

class PageTwo(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        t = wx.StaticText(self, -1, "This is a PageTwo object", (40,40))

class PageThree(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        t = wx.StaticText(self, -1, "This is a PageThree object", (60,60))


class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Simple Notebook Example", size=(600, 500))
        Publisher.subscribe(self.NewPage, "add.page")

        # Here we create a panel and a …
Gribouillis commented: An exemplar of well written post +13
SoulMazer 26 Posting Whiz in Training

I have another post entitled 'understanding wxPython' in which my code runs but fails to build the scroll bars as shown by my python programming book. Note that the code in the book is running on Windows and mine is running on Ubuntu.

I tested this myself, and I can see what you are saying. When running it under Vista, you can see the little grayed-out scrollbars, but you cannot use them.

However, on Ubuntu, there are no scrollbars at all.

I am guessing this is simply due to the OS, not your code. I think your window manager is configured so that scrollbars are not shown unless they are needed, like in your case. Since there is not a long selection of text to display, there is no use in having scrollbars.

If you add text to this widget, I'm thinking it will do the right thing and add scrollbars.

Let me know if this is in fact true. Good luck.

SoulMazer 26 Posting Whiz in Training

I found a solution! I am still using Tkinter's after method to run asyncore's loop function, but instead of using asyncore.loop(), I use asyncore.poll(0). If I call that function every 100ms or so, it no longer has an effect on Tkinter's main loop.

Victory.

vegaseat commented: congrats +10
SoulMazer 26 Posting Whiz in Training

It just so happens I used this exact library to store information for my media player! I cleaned up the code a bit and just included some basic operations. (songDict is a dictionary which contains the name, artist, album, etc. of various songs -- I find it easiest to put information already in a dictionary into a database)

#!/usr/bin/python
# sqlite3 example

import sqlite3

"""
songDict:
the key is the song
songDict[0] = path
songDict[1] = artist
songDict[2] = album
"""

class Database:
    def __init__(self):
        try:
            self.conn = sqlite3.connect('songs.db')
        except sqlite3.OperationalError: # Can't locate database file
            exit(1)
        self.cursor = self.conn.cursor()
        
    def createDatabase(self):
        cmd = "CREATE TABLE allsongs(path VARCHAR(100), name VARCHAR(50), artist VARCHAR(50), album VARCHAR(50))"
        self.cursor.execute(cmd)
        self.conn.commit()
        
    def insertSongs(self, songDict):
        for song in songDict:
            cmd = """INSERT INTO allsongs(path, name, artist, album) VALUES("%s", "%s", "%s", "%s")""" % (song, songDict[song][0], songDict[song][1], songDict[song][2])
            print "Inserting", song+"..."
            self.cursor.execute(cmd)
        
        self.conn.commit()
        
    def getSongs(self):
        songDict = {}
        cmd = "SELECT * FROM allsongs"
        self.cursor.execute(cmd)
        results = self.cursor.fetchall()
        for song in results:
            songDict[song[0]] = (song[1], song[2], song[3])

        return songDict
        
    def closeHandle(self):
        'Closes the connection to the database'
        self.conn.commit() # Make sure all changes are saved
        self.conn.close()

If you want me to explain any of it, feel free to ask.

SoulMazer 26 Posting Whiz in Training

The code looks a lot better now. It's very smart to only handle text writing via one function/thread, this will hopefully prevent any further errors. Clever use of CallAfter too.

SoulMazer 26 Posting Whiz in Training

The documentation is pretty much nonexistent, but you can find plenty of examples by searching the web for "python win32 simulate mouse click" or something similar.

Simulate a mouse click:

import win32api
import win32con

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)

click(100, 100) # simulate mouse click at 100px, 100px

Simulate a key press:

Download SendKeys from here.
Then:

from SendKeys import SendKeys
SendKeys('Hello{SPACE}world{ENTER}')
SoulMazer 26 Posting Whiz in Training

So is there a possibility to get a macro, which presses keys and clicks when the user presses a key, written in python?

So, let me see if I have this right. You want a script to emulate mouse clicks/key presses when the user presses a certain key (ALT + F, for example)? If so, then it depends on what OS you're running. I'll assume you're running Windows for now.

This should get you started:

Download pyHook here.
Download win32 extensions (pythoncom) here.

#Detecting keystrokes as events
import pyHook
import pythoncom

def OnKeyboardEvent(event):
    print event.Ascii

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()

while True:
    pythoncom.PumpMessages()

If you are by chance running Linux or another OS with X11 as its windowing system, I can give you one piece of advice: don't do it unless you have to. Just don't. If you're really determined, you can search for hours for some documentation for xbindkeys. If you need help with xbindkeys, post back. I have enough experience with it to help you get started.

Good luck with your scripting.

EDIT: If you want to do things the EASY way, check out AutoHotkey. You could probably write the entire script in about 5 minutes.

SoulMazer 26 Posting Whiz in Training

Yes, you can make it work by using a tuple as the value. Example:

numbers = {}

name = "Mario"
number = "555-5555"
address = "322 Main Street"
email = "mlopez@aol.com"

numbers[name] = (number, address, email)

print numbers["Mario"][0]  # 555-5555
print numbers["Mario"][1]  # 322 Main Street
print numbers["Mario"][2]  # mlopez@aol.com
SoulMazer 26 Posting Whiz in Training

I'm not sure this is possible, but I have had some results with the following:

port = 80
proto = getservbyport(portnum)
print proto

I'm not quite sure why it returns "www", I would expect "http", but maybe Python has a way of translating it. You might have to research it yourself, but I hope this is a help.

joehms22 commented: This is exactly what I needed. +1
SoulMazer 26 Posting Whiz in Training

If you're just doing this for yourself and are not too concerned about efficiency, this should suffice:

from socket import * 

if __name__ == '__main__':
	target = "localhost"
	targetIP = gethostbyname(target)
	print 'Starting scan on host ', targetIP

	#scan reserved ports
	for i in range(20, 1025):
		s = socket(AF_INET, SOCK_STREAM)

		result = s.connect_ex((targetIP, i))

		if(result == 0) :
			print 'Port %d: OPEN' % (i,)
		s.close()

You could always consult Wikipedia's reserved port list to tell what service a user is most likely running.

Also, if you are interested in efficiency (by means of threading), just post back and I'll give you some more code.

SoulMazer 26 Posting Whiz in Training

Hi, I'm looking for a little help with the function "getattr". Here's my code:

class MyClass:
      def __init__(self):
            trycmd = getattr(self, "cmd_testing")
            try:
                  trycmd()
            except:
                  print "Fail."
                  
      def cmd_testing(self):
            print "Victory!"
            
obj = MyClass()

So, when I run this code, I get the output "Fail.". I'm not sure what I'm doing wrong, but as I have tested a little more, I have come to the conclusion that it is not finding the right method (cmd_testing). How can I make this work?

Thanks in advance.

EDIT: My bad, I found out I did a really stupid mistake. I forgot the "None" argument when I set the "trycmd" variable. Problem resolved.

SoulMazer 26 Posting Whiz in Training

So, I have a rather simple question today. I'll try to explain it by using an example. Let's say there is a line of HTML in the page "www.mywebsite.com/py" that says "<tr colData0='Friday'>". However, this line of code can change to be "Sunday", "Tuesday", etc. What would be the easiest way for me to extract the data (Monday, Wednesday, etc.) from that line of code via a Python script?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Ok, well I am JUST beginning to learn Java, and I have run into a little stumbling block. I am attempting to write a little applet, but it doesn't seem to want to run.

My Java code:

import java.awt.*;
import java.applet.*;

public class TestApplet extends Applet {
	public void paint(Graphics g) {
			g.drawString("Please work my little applet!", 20, 30);
	}
}

My HTML:

<HTML>
<HEAD><TITLE>Test Applet</TITLE></HEAD>
<BODY>
<applet code="TestApplet.class" width="300" height ="300">
</BODY>
</HTML>

So...I'm not quite sure where I am going wrong. I receive no errors while compiling and there isn't much code for me to mess up.

Could anybody help me with this problem?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training
print 'Hello ' + name

Try this:

print "Hello,", name

The why:

If you use the code: "string1"+"string2"
You get the following: string1string2
However, if you use this: "string1","string2"
You get: "string1 string2" (notice the space)

cohen commented: Thanks for your Python help! It worked well! +2