SoulMazer 26 Posting Whiz in Training

Another problem; SoulMazer's code doesn't work. Yes, it gives you a time, but it doesn't end the action. Sorry if I'm taking up time, but I'm desperate to finish this game of mine. :(

What do you mean? The code prompts you for a string, and if you do not enter one within X seconds, it prints some messages. Yes, I do have to admit that it does not cancel the original raw_input call, so the user can still input text, but that's why I originally said it was not truly possible.

If you look back to the links I provided in my first post, it provides alternatives to raw_input for both Windows in Linux without a GUI.

If you want more specific help, please be more specific with your problem, as woooee stated.

SoulMazer 26 Posting Whiz in Training

EDIT: As woooee posted, Tkinter's after function would probably be optimal if you plan on creating a GUI for your script. If not, then the following is probably what you are looking for:

Well apparently I was slightly wrong in my last post. Although raw_input() does block, it is indeed possible to get around with threads. In the piece of code I created myself, (similar to diwakar's) I tested it within an IDE and it did not work. However, when I ran it under normal conditions, it did.

Here's the code if you would like:

#!/usr/bin/python

import threading
from time import sleep

got_input = False

def printStuff():
    print
    print "Sorry, you didn't enter anything."
    print "Have a nice day."

class TimeThread(threading.Thread):
    def __init__(self, max_):
        threading.Thread.__init__(self)
        self.max_ = max_
        
    def run(self):
        sleep(self.max_)
        if (got_input == False): # the time is up: if the user didn't enter anything, print stuff.
            printStuff()
        
time_thread = TimeThread(3)
time_thread.start()
print "Enter your name: "
name = raw_input("> ")
got_input = True # if this code is executed, it means the user did input something
print "Welcome,", name
SoulMazer 26 Posting Whiz in Training

Sadly, an easy alternative to raw_input that does not block (that is portable) is not too easy to find.

I tried to create a version myself, but apparently raw_input even blocks other threads in the program from printing to the console. It's pretty strange.

However, if this is just for yourself or only for one platform, take a look at these postings I found around the web:

Windows
Linux

Good luck.

SoulMazer 26 Posting Whiz in Training

Sorry, I know this code is for Python 2.x, but hopefully it can point you in the right direction. There is a piece of code that I did NOT write myself but I implemented it in one of my programs. It basically creates a few text widgets in a loop and puts them in a list, also binding the scroll bar to a custom "scrolling" function. I don't think it would be too difficult to adapt this code and rather than binding the scroll bar itself, just bind arrow keys or buttons to the custom "scrolling" function. Good luck. I've pasted the code below; an example of how to implement it is given at the bottom.

from Tkinter import *

class CustomListbox(Frame):
    def __init__(self, master, lists):
	Frame.__init__(self, master)
	self.lists = []
	for l,w in lists:
	    frame = Frame(self); frame.pack(side=LEFT, expand=YES, fill=BOTH)
	    Button(frame, text=l, bg="#000000", fg="green", activeforeground="#999999", activebackground="#000000", relief=FLAT, highlightthickness=1, highlightbackground="#414141", highlightcolor="#414141", font=("Calibri", 9)).pack(fill=X)
	    lb = Listbox(frame, bg="#000000", fg="green", highlightthickness=1, width=w, borderwidth=0, selectborderwidth=0,
			 relief=FLAT, exportselection=FALSE)
	    lb.pack(expand=YES, fill=BOTH)
	    self.lists.append(lb)
	    lb.bind('<B1-Motion>', lambda e, s=self: s._select(e.y))
	    lb.bind('<Button-1>', lambda e, s=self: s._select(e.y))
	    lb.bind('<Leave>', lambda e: 'break')
	    lb.bind('<B2-Motion>', lambda e, s=self: s._b2motion(e.x, e.y))
	    lb.bind('<Button-2>', lambda e, s=self: s._button2(e.x, e.y))
	frame = Frame(self); frame.pack(side=LEFT, fill=Y)
	Label(frame, borderwidth=1, relief=RAISED).pack(fill=X)
	sb = Scrollbar(frame, orient=VERTICAL, command=self._scroll, bg="black", activebackground="#313131")
	sb.pack(expand=YES, fill=Y)
	self.lists[0]['yscrollcommand']=sb.set

    def _select(self, y):
	row = self.lists[0].nearest(y)
	self.selection_clear(0, END)
	self.selection_set(row)
	return 'break'

    def _button2(self, x, y):
	for l in self.lists: l.scan_mark(x, y)
	return 'break'

    def _b2motion(self, x, y):
	for l in self.lists: l.scan_dragto(x, y)
	return 'break'

    def _scroll(self, *args): …
SoulMazer 26 Posting Whiz in Training

Are you looking for something along the lines of tkSnack? I cannot help you with integrating it into your C program, but from experience it is a highly dependable library that is quite easy to use; it is also cross-platform (at least for Windows & Linux). Its one downside is that it requires Tkinter in order to function.

EDIT: Are you looking for a library or a pre-written music player?

SoulMazer 26 Posting Whiz in Training

Well, it doesn't even look like deepak's code is Python. I'm not quite sure what is going on with that.

Anyways, I do not see any immediate problems why your code should not work except for the constant calling of the function "create_top." You call it eight times? That would mean you create eight canvases with eight background images? Am I missing something or is that your most apparent problem?

EDIT: If this is actually tyonyjv's code, I will definitely not try to question its methods; his GUI algorithms are above my skill level. He will unquestionably know more about it than I do, so try to ask him politely. Good luck.

SoulMazer 26 Posting Whiz in Training

Why do they have to make everything so difficult.....

Well, I have some marginally good news. Some users with the same problem as you created a library to hopefully make the connection process easy. Pyfacebook's home: link. This is the current home: do not use the Google code page, as it is supposedly outdated. You can find examples in the "examples" directory on github (link) or from the facebook developer's area (link).

Hopefully that will make things easier.

SoulMazer 26 Posting Whiz in Training

It's probably not working because you are not supplying all the required arguments. Sadly, it looks like Facebook wants quite a few arguments to log in such as authentication token and api key, but the Facebook devs have provided some information on all of it: http://wiki.developers.facebook.com/index.php/Authorization_and_Authentication_for_Desktop_Applications.

Good luck.

SoulMazer 26 Posting Whiz in Training

The error is being raised because it is trying to find the integer value of the character '[', which is apparently part of your list. You could either put in a try/except statement to 'pass' when you run into those, or print out the contents of the list and manually remove bogus entries.

Just post back if you need help with any of that.

SoulMazer 26 Posting Whiz in Training

Only a few questions more actually. In the part of:

cursor.execute("SELECT * FROM mytable") # Select everyone in the table
results = cursor.fetchall()
for entry in results:
    print entry

1. What is what I call (a string line, array, etc)??
2. And how do I call an specific data??

1. What do you mean? Are you asking what type of objects the results are? The actual variable 'results' is an array which contains an array for each entry. All of the data in these arrays is strings.

2. You mean how can you only select certain results from the table? Let's say you need to look up John Doe's zip code - just change line 22 from my last post into this: cursor.execute("SELECT * FROM mytable where name = 'John Doe'")

SoulMazer 26 Posting Whiz in Training

It's really useful, I appreciate but I have some questions.
1. After creating a db, how do I call their objects?
2. The db must still running while my application works or only when I need to insert or call something in the db?
3. Can I create more then one db for my applicate? In the case of yes, how do I work with all of them (switch between db).
3. And if you can explain me more of how do I get something from the db.

PD: excuse me if I don't catch something quickly, thats because I'm new at python

1. I'm not sure if I understand what you're asking. Are you asking how to manipulate a database after it has been created? I think you might be mixing up "table" and "database." The database is the entire thing, and it contains tables. A database can be created with this library by simply putting in any file name to a line of code like my line 17 (NOTE: When I refer to line numbers, I am referring to my last post). It doesn't matter if it already exists or not: if it does, the program simply accesses it; if it doesn't, the program creates a new database. Once you have this database, you can create "tables" inside of it. These tables are what actually contain your data...I am manipulating them in lines 27-41 of my code.

2. You can close the handle …

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

Yes, you should probably just copy that code into a separate file and then import it into your program. From there, you can create the widget in your main script similarly to a normal widget. This example would be some sort of a music player:

import MultiListbox

frame = Frame(root, relief=SUNKEN)
mlb = MultiListbox.MultiListbox(frame, (('Title', 15), ('Artist', 15), ('Length', 12)))
for i in range(1000):
    mlb.insert(END, ('Test Song %d' % i, 'Test Artist %d' % i, 'Length %d' % i))
mlb.pack(expand=YES,fill=BOTH)

Post back if you have any other questions.

SoulMazer 26 Posting Whiz in Training

Well, I had the same exact problem a few months ago. I used the code found here (link), and found it is pretty good, but not perfect. For example, if you click within one of the listboxes and scroll with the mouse wheel, they do not scroll synchronously. But that's the best I could find. Good luck.

SoulMazer 26 Posting Whiz in Training

Try this:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self, param1, param2):
	threading.Thread.__init__(self)
	self.param1 = param1
	self.param2 = param2
	
    def run(self):
	print "[Client1 Thread] The value of param1 is", self.param1
	print "[Client1 Thread] The value of param2 is", self.param2
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self, param1, param2):
	threading.Thread.__init__(self)
	self.param1 = param1
	self.param2 = param2
	
    def run(self):
	print "[Client2 Thread] The value of param1 is", self.param1
	print "[Client2 Thread] The value of param2 is", self.param2
	# Enter code here for client 2
	
threadOne = Client1Thread("hello", "world")
threadTwo = Client2Thread(12, 15)

threadOne.start()
threadTwo.start()
SoulMazer 26 Posting Whiz in Training

When I started threading in Python, I had the exact same problem. It's quite difficult to find a very basic example of it. Let me try to give you one using the scenario you described.

I'm not quite sure how you are going to connect to the two client machines, so I'll leave that up to you. This is probably the most simple threading example you can have:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client1 Thread"
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client2 Thread"
	# Enter code here for client 2
	
threadOne = Client1Thread()
threadTwo = Client2Thread()

threadOne.start()
threadTwo.start()

If you need help with any of it, feel free to post back.

EDIT: There's a code snippet by a1eio that also shows a basic example of threading quite well. Link.

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

I have to say that's pretty good for your first little program. I just have one little suggestion: You don't need to do print('\n') to print a new line, you can simply use print to print a new line (correct me if I am wrong about 3.x, but this is true for 2.6).

The only other thing I can say is...expand it. First, try adding a menu option of deleting a name from the list. Next, allow the user to also enter a phone number for the name (hint: you can use a dictionary). To get a little more practice you can also try putting it into a class. It would be a very good habit to get into early.

Good work and good luck in the world of programming.

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

Well, my mistake, vegaseat was correct. I got confused as the "print d" statement printed out only the "c" variable so I assumed that it was only set to "c". What?! Python...not-intuitive? That's a first!

Thank you for the correction vegaseat.

SoulMazer 26 Posting Whiz in Training

Okay, when you are prompted, type nothing, and just press enter, the variable is set to the following: ""

As for the reason why your code doesn't work:

The line "d = (a and b and c)" is actually doing the following:

d = a
d = b
d = c

So, it is overwriting the value of d three times. Unless I am mistaken, this is not what you want. This is more like what you want (this is the "long way")

a = raw_input("Enter your first name:")
b = raw_input("Enter your last name:")
c = raw_input("Enter your phone number:")

if a == "":
	print "You did not give your first name."
if b == "":
	print "You did not give your last name."
if c == "":
	print "You did not give your last name."

print "Thank you!"

Post back if you have any more questions.

SoulMazer 26 Posting Whiz in Training

Instead of hi-jacking a thread, please make a new one. But are there still no answers for my problem.

Sorry, I had a brain fart. My first post said you should change the file to a .pyc (WRONG), you should make it a ".pyw" as jice said.

To do this, just save the file as a .pyw file instead of a .py from whatever text editor you are using and it should work.

Alternatively, you could use the "withdraw()" method of your root window. Example:

import Tkinter
root = Tk()
root.withdraw()
SoulMazer 26 Posting Whiz in Training

Don't want to hijack this but I'm interested in compiling a tkinter gui app with py2exe -- the catch -- I'm using python 3.1.1 or whatever the latest version is.

I only see py2exe up until 2.6/7?

I used cxfreeze, and it gave me a .exe file... however when I open the .exe file it just displays a console window for about 1/10 of a second and then closes. I think it has something to do with tkinter because when I used cxfreeze on a plain old user input, then print user input program it worked fine.

Should I just make my code in 2.6 or is there a better solution for converting a tkinter gui app into a .exe?

I don't think Tkinter is your problem, the fact that you are using Python 3.x is the problem. As far as I know, py2exe is not compatible with Python 3.0x. I would probably just convert all my code to 2.6/7 for the time being if I were you.

SoulMazer 26 Posting Whiz in Training

You have two options.

1. Save the file as a .pyc instead of a .py.
2. Try "root.withdraw()". (replace root with whatever you named your root widget)

Or you could compile it with py2exe if you want to get fancy and Windows only. (if you choose this option, let me know, there's an extra step)