Re: [Tutor] Compile py to exe in ubuntu
On 10-02-10 20:40, Harya Dananjaya wrote: Can I compile my python source to exe in ubuntu? Like said before, you need Windows for this. if I can do it, which compiler can do it? I use py2exe to compile my Python/PyGTK application. I build it on my Windows XP machine and it works on Windows 2000 to Windows 7 without installing anything else (like Python). Try GUI2exe for a nice graphical interface. Cheers, Timo Thanks you, Harya Dananjaya ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Cannot open SQLite database
Hello all, my program uses SQLite as database and everything worked fine until now. I have over 3000 downloads of my program, but I got 2 mails this week from people who get this error: OperationalError: unable to open database file I searched the net, and all problems seem to be of a not writeable directory or passing a tilde to connect to the database. As far as I know, this isn't the case with my program. Here is some code: # Get the application data folder # This will return: C:\Documents and Settings\user\Application Data\myapp PREFDIR = os.path.join(os.environ['APPDATA'], 'myapp') # Connect to the database def db_connect(): conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) # This line gives the error conn.text_factory = str cursor = conn.cursor() return (conn, cursor) I noticed that the 2 users that got the error are Russian, so I thought that the Russian characters would cause problems. I tried on my Linux and Windows machines with some Russian names, but thet doesn't seem the problem. Some help is appreciated :-). Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cannot open SQLite database
On 25-02-10 00:03, ALAN GAULD wrote: Does the file actually exist where you say it does? It doesn't need to exist, it will be created if it isn't found. Of course I should have known that! It points to the path/folder then... It is on Windows XP, and in the logfile it says it uses the directory: C:\Documents and Settings\user\Application Data\myapp That directory should always be writeable for the user, no? Not on my PC its Read Only And I have administrator rights. A normal user is even more likely to be limited. And a Guest account definitely would be. Hmm that's strange. I thought the application data folder is the correct folder on Windows systems to put your configuration files. And until now, it worked perfectly for every user. What should be the correct folder then? Cheers, Timo HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cannot open SQLite database
2010/2/25 ALAN GAULD > > > What should be the correct folder then? > > I don't know! To be honest I was surprised by the result too. > Personally I tend to either use the application folder or the registry. > But the app folder doesn't work for user specific settings unless > you have a separate file based on user ID. > > Its very odd. > > In fact Windows explorer appears to be lying. I just tried creating > a file using Python and it worked perfectly. But Explorer definitely > claims its R/Only! I also tried the ATTRIB command from DOS > and it does not show it as Read only. > > Cygwin shows it as readonly for world access but open for user > and group. The security tab in exporer shows it read/write for > admins and me. (It doesn't show a world setting) > > So I think that was a red herring, sorry. > It also looks like the Read Only check box in the main Explorer > property dialog tab doesn't mean what it says... > > Alan G. > I just thought of something, and it can't be that the folder isn't writeable. Because I asked the user for the logfile that my program produces, and it is located in the same folder as where the database should be. So if the folder wasn't writeable, the creation of the logfile would have caused an error too. So I'm a bit stuck about this one. Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sending mail
Hello, I was wondering what the best way is to send an email through my program? I want the user to send an email with an attachment. I do have a webspace, should I use the smtplib module if my webhost supports it (I have to ask though), or should I put a script on my space and communicate with that? Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sending mail
2010/3/25 Timo > Hello, > > I was wondering what the best way is to send an email through my program? I > want the user to send an email with an attachment. > > I do have a webspace, should I use the smtplib module if my webhost > supports it (I have to ask though), or should I put a script on my space and > communicate with that? > > Cheers, > Timo > I worked on the following code. It works, but not for attachments. On the webserver I have: http://python.pastebin.com/9m8MXxuR And inside my program I then do: form = urllib.urlencode([("from", send_from), ("to", send_to), ("subject", subject), ("body", body), ("attachment", attachment)]) webbrowser.open(url + "?" + form) So, 2 questions: - Is this a good way of sending mails over my webhost through my program? - Attachments don't work because I'm sending the path to the file, and ofcourse the cgi script can't find it. How should I solve this? Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recent Documents
On 27-05-10 20:45, John Storta Jr. wrote: I am working on an app that runs in gnome and uses gtk. I am extremely new to Python. (been working with it for all of 2 days). I am wanting to add a 'Recent Documents' menu option to the app. Gnome tracks your recent documents -- apparently in a file called '.recently-used.xbel' in your home directory. So as to avoid reinventing the wheel, does anyone know of any examples of accessing the Gnome recently used file list from within Python? Or is there some samples of how to implement something independently? It seems like the type of thing that would be fairly common as part of integrating a Python app with Gnome. I cannot image every app maintains their own list of recently used docs when it is already stored within the desktop. If anyone has any ideas, please let me know. PyGTK has some widgets that deal with that. See the PyGTK reference manual and see the widgets that start with "Recent*". Cheers, Timo Thanks, John S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Uploading a file (non-form)
Hello, I am searching and searching and searching and ... Still haven't found the solution. Basicly, I want to upload a file to my http server. The user shouldn't have to do anything for this, so a userform on my webpage is a no-go. For just text, I managed to do it with a form, but fill it in automaticly through the code. Like: Clientside: form = urllib.urlencode([("text", "Some example text")]) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(None)) opener.open(urllib2.Request(url, None, USER_AGENT), form) Serverside: form = cgi.FieldStorage() text = form['text'].value Now I can use 'text' on the server, for mailing etc. But I really can't manage to do this with a file. Anyone can give me a helping hand here? Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to add extra Vbox fields dynamically
On 20-06-10 04:04, Lang Hurst wrote: OK, I just did the ugliest hack, from someone who only seems to do ugly hacks. I set up a bunch of textview areas and defaulted them to 'not visible'. Then as I loop through my query results, I make them visible one at a time. Well, it works perfect, but it just doesn't seem right for some reason. You also posted this on the PyGTK mailing list, which is the correct place for these problems. Please post your PyGTK questions only there, do not double post. I'll answer you there. Cheers, Timo Lang Hurst wrote: I hope that I'm asking this in the right place. I don't have too much trouble hacking together command line stuff, but the GUI part is a struggle for me. I created a UI in glade. It has a couple of Vboxes for information. The final box is filled with a TextView. In my program, I'm connecting to a database and pulling out a series of records. As it stands, I can pull out all the records and view them in the TextView, but I would like to be able to have each result be a separate TextView (which I then have to figure out how to make clickable...) Right now, this part looks like: query = 'SELECT subject, chapter_module, credits, final_test_score, notes FROM credits WHERE id=' + student[0][6] cursor.execute(query) credits = cursor.fetchall() temp = '' for credit in credits: sub_buf = 15 - len(credit[0]) chap_buf = 15 - len(credit[1]) cred_buf = 5 - len(credit[2]) score_buf = 5 - len(credit[1]) temp = temp + credit[0] + " " * sub_buf + credit[1] + " " * chap_buf + "Credits: " + credit[2] + " " * chap_buf + "Score: " + credit[3] + "\n\nNOTES: " + credit[4] + "\n" + " " * 5 + "-" * 50 + "\n\n" # I would like to loop something here # to have multiple text areas added buff = self.builder.get_object('textview1').get_buffer() buff.set_text(temp) This works fine. It pulls the records out of the database, and then cats the results together and throws it into my TextView. I'm happy with the results so far, but I would like to be able to click on each record if I see something that needs to be modified. As always, any help is appreciated. Also, can anyone recommend a good book for gtk + glade + python? I went out and bought Learning Python, but book at B&N that were remotely GUI related seems very outdated or just tkinter related, and just about all the gtk+python examples and tutorials don't use glade. Thanks again. -Lang ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Contents of Tutor digest, Help with hangman
On 19-07-10 18:20, John Palmer wrote: Thanks a lot for the help guys, but when I use the getpass.getpass(Enter your word here, I get a different response to what you get. This is what happen with mine: >>> import getpass >>> s = getpass.getpass("Enter your word here: ") Warning: Password input may be echoed. Please enter your secret word: hangman >>> s 'hangman' >>> This may not be really helpful, but I am using Ubuntu 10.04 too and have no problems. Running in the Gnome terminal: $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import getpass >>> s = getpass.getpass("Enter your word here: ") Enter your word here: >>> print s blah Cheers, Timo I'm guessing that its something to do with the "Warning: Password may be echoed" line. In the documentation it says: "If echo free input is unavailable getpass() falls back to printing a warning message to stream and reading from sys.stdin and issuing a GetPassWarning." But i'm not sure what that means, sry to be a pain, and again thanks for all the help. I did manage to find another solution which is just to print a large number of blank lines, which just moved the line with the word in it off the screen, but I don't really like it to be honest. The getpass module seems to be the best solution i just don't understand why its not working for me. Regards John On 19 July 2010 16:02, <mailto:tutor-requ...@python.org>> wrote: Send Tutor mailing list submissions to tutor@python.org <mailto:tutor@python.org> To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org <mailto:tutor-requ...@python.org> You can reach the person managing the list at tutor-ow...@python.org <mailto:tutor-ow...@python.org> When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: A file containing a string of 1 billion random digits. (Peter Otten) 2. Re: A file containing a string of 1 billion random digits. (ALAN GAULD) 3. Re: A file containing a string of 1 billion random digits. (Richard D. Moores) 4. Re: A file containing a string of 1 billion random digits. (Richard D. Moores) 5. Re: Contents of Tutor digest, help with Hangman program (Steven D'Aprano) 6. Re: Contents of Tutor digest, help with Hangman program (bob gailer) 7. Re: A file containing a string of 1 billion random digits. (Steven D'Aprano) -- Message: 1 Date: Mon, 19 Jul 2010 15:45:43 +0200 From: Peter Otten <__pete...@web.de <mailto:pete...@web.de>> To: tutor@python.org <mailto:tutor@python.org> Subject: Re: [Tutor] A file containing a string of 1 billion random digits. Message-ID: mailto:1...@dough.gmane.org>> Content-Type: text/plain; charset="ISO-8859-1" Richard D. Moores wrote: > On Mon, Jul 19, 2010 at 04:51, Peter Otten <__pete...@web.de <mailto:pete...@web.de>> wrote: >> bob gailer wrote: >> >>> Check this out: >>> >>> import random, time >>> s = time.time() >>> cycles = 1000 >>> d = "0123456789"*100 >>> f = open("numbers.txt", "w") >>> for i in xrange(n): >>> l = [] >>> l.extend(random.sample(d, 1000)) >>> f.write(''.join(l)) >>> f.close() >>> print time.time() - s >> >> Note that this is not random. E. g. the start sequence "0"*101 should >> have a likelyhood of 1/10**101 but is impossible to generate with your >> setup. > I not sure exactly what you mean, because I don't fully understand > that '*' (despite Alan's patient explanation), but if you run > > import random > cycles = 10 > d = "0123456789"*10 > for i in range(cycles): > l = [] > l.extend(random.sample(d, 100)) > s = (''.join(l)) > if s[:4] == '0101': > print(s) > > You'll see a bunch of strings that begin with "0101" > > Or if you run > > import random > cycles = 50 > d = &quo
Re: [Tutor] Problem with input() and unicode string
On 28-07-10 18:05, Alex wrote: Hello, I have a problem with this code: # -*- coding: latin-1 -*- year = u'año, ò, ó, ç' print year year = input(u'Introduce el año:') print year raw_input() The first print statement works as expected, both in IDLE and when double-clicking the file for a console view. The second one works in IDLE, but just flashes by when double-clicking the file, due to an error report I can't see. I don't have a solution, but call your script from the commandline to stay open after exceptions. Or try some things in the Python interactive prompt: >>> year = input(u'Introduce el año:') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 14: ordinal not in range(128) Cheers, Timo I believe the problem is that input prompt doesn't support unicode strings, which means I can't use my language for prompts? Could someone please tell me how to fix it or provide a workaround? Thanx. Using Python 2.7 under win32. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing scripts and apps for Internet consumption
On 01-08-10 00:40, Eric Hamiter wrote: On Sat, Jul 31, 2010 at 4:48 PM, bob gailer <mailto:bgai...@gmail.com>> wrote: Please post that code, and the URL you use to invoke it. test.py: this works on my laptop but not on the server http://pastebin.com/ChjUzLRU Just a wild guess, but maybe it is failing on the following line: with open("grocery_list.txt") as grocery_list: The with statement was introduced in Python 2.5, and if I look at my own webhost, they are still with Python 2.4. Make a script that prints the Python version (with sys.version_info or sys.version for example) or ask your webhost. You can also put this on top of your script, so it shows you a nice Python traceback instead of an error: import cgitb cgitb.enable() Cheers, Timo test-working.py: this works on both laptop & server http://pastebin.com/iLNTrGdW both available for execution here: http://erichamiter.com/xkred27/ Do you import cgi? Yes. There is a companion module (cgitb) that captures exceptions and returns the traceback to the web browser. I tried that as well. I'm sure I'm missing something fundamental here, but that's kind of obvious since I posted I don't know what I'm doing in the first place! :) Thanks, Eric ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14-09-10 09:28, Roelof Wobben wrote: Hello, Strip ('"'') does not work. Still this message : SyntaxError: EOL while scanning string literal Review it again, see how many quotes you are using. For example, this won't work either: >>> s = 'foo'bar' You need to escape the quotes with a backslash, like: >>> s = 'foo\'bar' >>> print s foo'bar Cheers, Timo So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character. Roelof From: st...@pearwood.info To: tutor@python.org Date: Tue, 14 Sep 2010 09:39:29 +1000 Subject: Re: [Tutor] wierd replace problem On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote: On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano wrote: On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote: How about using str.split() to put words in a list, then run strip() over each word with the required characters to be removed ('`") Doesn't work. strip() only removes characters at the beginning and end of the word, not in the middle: Exactly, you first split the words into a list of words, then strip each word Of course, if you don't want to remove ALL punctuation marks, but only those at the beginning and end of words, then strip() is a reasonable approach. But if the aim is to strip out all punctuation, no matter where, then it can't work. Since the aim is to count words, a better approach might be a hybrid -- remove all punctuation marks like commas, fullstops, etc. no matter where they appear, keep internal apostrophes so that words like "can't" are different from "cant", but remove external ones. Although that loses information in the case of (e.g.) dialect speech: "'e said 'e were going to kill the lady, Mister Holmes!" cried the lad excitedly. You probably want to count the word as 'e rather than just e. And hyphenation is tricky to. A lone hyphen - like these - should be deleted. But double-dashes--like these--are word separators, so need to be replaced by a space. Otherwise, single hyphens should be kept. If a word begins or ends with a hyphen, it should be be joined up with the previous or next word. But then it gets more complicated, because you don't know whether to keep the hyphen after joining or not. E.g. if the line ends with: blah blah blah blah some- thing blah blah blah. should the joined up word become the compound word "some-thing" or the regular word "something"? In general, there's no way to be sure, although you can make a good guess by looking it up in a dictionary and assuming that regular words should be preferred to compound words. But that will fail if the word has changed over time, such as "cooperate", which until very recently used to be written "co-operate", and before that as "coöperate". -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14-09-10 17:44, Roelof Wobben wrote: 9 stripped_words = words.strip(".,!?'`\"- ();:") Hello Joel, Your solution works. Im getting grazy. I tried it two days with strip and get a eof error message and now no messages. Look at the backslash! It doesn't strip the backslash in the string, but it escapes the double quote following it. I don't know how people can explain it any better. You *do* see that this doesn't work, right? >>> s = "foo"bar" So you can't do this either: >>> word.strip(",.!";:") You need to escape the quote between the quotes: >>> word.strip(".,!\";:") Timo Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] working with empty lists
On 16-09-10 06:05, Rance Hall wrote: Im working on a little piece of test code to test an idea for a larger script. Here is what I've got so far: l = [] for i in range(0,10) l.append(i) for i in range(0,10) print('%s. %s' % (i, l[i]) This gives me: 0. 0 1. 1 2. 2 etc which is what I expect, but what I want is to get something like 0. 1 1. 2 2. 3 . so that the output is clearly different on either side of the "." You could do this: >>> l = [] >>> for i in range(1, 11): ... l.append(i) ... >>> for index, i in enumerate(l): ... print('%s. %s' %(index, i)) ... 0. 1 1. 2 2. 3 3. 4 etc. Cheers, Timo I tried changing the append to l.append(i+1) which almost worked but the output started with 1. 2 I was curious what happend to the 0. 1 line I know this means that I'm not understanding exactly what append actually does. I know that my ide shows that the list as other functions like insert, etc. Can someone explain to me whats the best way to add a value to a list that is not long enough to accept it, without playing with the indexes, it appears I currently am playing with them. I know generally that we aren't supposed to care about the indexes but this is eventually going to be part of a menuing system that displays the index, so I do have a legit need to care about what is happening to the list index. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Connecting my users
Hello, I have the following idea, but no clue how to implement this. I want my users to be able to connect to other users (with the same program) and chat with them and exchange files. Ideally without server interaction. Now I heard about peer-to-peer and bittorrent protocol etc. But don't know where to start or that I'm even at the right path. So if anyone can point me into the right direction of a framework or protocol I should use for this, it would be appreciated. Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Connecting my users
On 01-10-10 11:25, Nitin Pawar wrote: have a look at this http://bytes.com/topic/python/answers/826973-peer-peer-chat-program Thanks, but that still uses a server. And even one that I can't control! If it has to be with server interaction, than as little as possible is preferred and option to put it on my own. Cheers, Timo On Fri, Oct 1, 2010 at 2:49 PM, Timo <mailto:timomli...@gmail.com>> wrote: Hello, I have the following idea, but no clue how to implement this. I want my users to be able to connect to other users (with the same program) and chat with them and exchange files. Ideally without server interaction. Now I heard about peer-to-peer and bittorrent protocol etc. But don't know where to start or that I'm even at the right path. So if anyone can point me into the right direction of a framework or protocol I should use for this, it would be appreciated. Cheers, Timo ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Nitin Pawar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Stopping a webservice
Hello, I have written a Python script that constantly checks for incoming connections. It is a class and runs a while loop until shutdown is set to True. Something like: class Connection(object): def __init__(self): self.shutdown = False def mainloop(self): while not self.shutdown: print "We keep checking..." I have written a GUI and when I click the Quit-button, I do "connection.shutdown = True", which works great. The plans are to run this on my webserver. I created a webpage with a start and stop button, the starting works great. But how could I remember this class to call "class.shutdown = True" any given time when I press the stop button? Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Complete Shutdown
On 01-11-10 21:01, Chris King wrote: Dear Tutors, How do I completely shutdown a computer without administrative rights using a simple python script. I once came across the following when playing with dbus. import dbus bus = dbus.SystemBus() bus_object = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer") bus_object.Shutdown(dbus_interface="org.freedesktop.Hal.Device.SystemPowerManagement") This will shutdown your computer immediatly. You can substitute the "Shutdown" method with "Suspend", "Hibernate" or "Reboot". Cheers, Timo Sincerely, Me, Myself, and I ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] ConfigParser re-read fails
Hello all, I use a file for my program that I read with ConfigParser. I append all sections of this file into a treeview (using pyGTK). The user can add, edit or remove sections, options and values. These I write back to the file and then update the treeview. The problem is that it doesn't update, the values are still the same. How can I re-read the configuration file? This is (very simple) what I do: conf = ConfigParser.RawConfigParser() configFile = 'config.cfg' conf.read(configFile) fill_treeview() def fill_treeview() # Do the treeview stuff here def button_clicked() write_config(section, option, value) conf.read(configFile) # It needs to be re-read here fill_treeview() def write_config(section, option, value) if not conf.has_section(section): conf.add_section(section) conf.set(section, key, value) conf.write(open(configFile, 'w')) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Shelve: remove dictionary from list
Hello all, I'm using the Shelve module to store dictionaries in a list as a value of a key. So: key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] The problem is I can't remove a dictionary from the list. import shelve s = shelve.open('file') try: for index, value in enumerate(s['key']): if value['keyA'] == 1 and value['keyB'] == 2: del value[index] finally: s.close() If I do some printing in between, I can see the dictionary actually gets removed, but doesn't get saved. Any ideas why? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shelve: remove dictionary from list
Kent Johnson schreef: On Tue, Mar 3, 2009 at 12:18 PM, Timo wrote: Hello all, I'm using the Shelve module to store dictionaries in a list as a value of a key. So: key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] The problem is I can't remove a dictionary from the list. import shelve s = shelve.open('file') try: for index, value in enumerate(s['key']): if value['keyA'] == 1 and value['keyB'] == 2: del value[index] finally: s.close() If I do some printing in between, I can see the dictionary actually gets removed, but doesn't get saved. Any ideas why? From the shelve docs: By default, mutations to persistent-dictionary mutable entries are not automatically written back. If the optional writeback parameter is set to True, all entries accessed are cached in memory, and written back at close time; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated). In other words, by default, shelve does not know about changes you make to mutable values. You can either - open the shelve with writeback=True - explicitly store the modified value back into the shelve: key = s['key'] # modify key s['key'] = key s.close() Kent Sorry, I should have known this myself since I do this to append data to it. Stupid mistake. Don't know why I didn't do this when deleting data. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Shelve doesn't free up memory
Hello, I have a PyGTK application where the user is able to click on a button, then a new dialog pops up with a treeview and the program fills this view with data from a shelve. Everything works, the data is being added to the treeview. The only problem is, that when I close the dialog, it doesn't free the memory. So when I click the button again, the same amount of memory is added being used. Then close the window, click again, again the same amount of memory, and so on... Now it only takes about 5 to 8 mb, but this shouldn't be. I do call the shelve.close(), but that doesn't do it apparently. Do I need to do something when I close my window? Here are parts of the code: # Result window => Called when button is clicked import Results class ResultWindow: def __init__(self): # Build the dialog and the treeview... self.get_results() def get_results(self): self.liststore.clear() for person in self.persons: dics = Results.read_result(person) if not dics: continue for dic in dics: date = dic['date'] point = dic['point'] place = dic['place'] out = dic['out'] self.liststore.append([date, point, place, out]) # Results file import shelve def read_result(person): results = [] s = shelve.open(RESULTFILE) try: results = s[person] except KeyError: #print "No results for this person" pass finally: s.close() return results ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shelve doesn't free up memory
Emile van Sebille schreef: Timo wrote: # Results file import shelve def read_result(person): results = [] s = shelve.open(RESULTFILE) try: results = s[person] Maybe passing this out prevents s from being garbage collected? What do you mean by passing out? I also tried gc.collect(), but no difference. Emile except KeyError: #print "No results for this person" pass finally: s.close() return results ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Alternative for Shelve
Hello all, I have an issue with the Shelve module. It works great for my needs, the only problem is that a file made with Shelve isn't interchangable between different computers. I want my data to be exchanged between users. Does someone have an alternative to Shelve? It must be able to contain keys and values, and the values are a list of dictionaries. For example: 1234567 = [{'date' : '2009-05-11', 'location' : 'Germany'}, {'date' : '2009-05-04', 'location' : 'France'}] 7654321 = [{'date' : '2009-03-12', 'location' : 'Belgium'}, {'date' : '2009-04-23', 'location' : 'Spain'}] And so on... Thanks, Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternative for Shelve
Alan Gauld schreef: "Timo" wrote I have an issue with the Shelve module. It works great for my needs, the only problem is that a file made with Shelve isn't interchangable between different computers. I thought it would be. What kind of computers are you having issues with? And what kind of issues? Currently only tested between Ubuntu and Windows on the same computer. This is the end of the traceback: bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- : unsupported hash version: 9') Does someone have an alternative to Shelve? It must be able to contain keys and values, and the values are a list of dictionaries. A SqlLite database? With record where the fields correspond to your dictionary entries. ID:Date:Location 1234567 = [{'date' : '2009-05-11', 'location' : 'Germany'}, {'date' : '2009-05-04', 'location' : 'France'}] 7654321 = [{'date' : '2009-03-12', 'location' : 'Belgium'}, {'date' : '2009-04-23', 'location' : 'Spain'}] populating your dictionary becomes a matter of extracting the data: SELECT DATE, LOCATION FROM DATA WHERE ID = key SQLite has the advantage that the atabase is a single file and it is portable across platforms provided they have Sqlite installed. And its part of the Python standard library. Examples of using Sqlite in the databases topic of my tutorial. Thank you. I will check the tutorial. Timo HTH, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternative for Shelve
Kent Johnson schreef: On Mon, May 11, 2009 at 1:39 PM, Timo wrote: Hello all, I have an issue with the Shelve module. It works great for my needs, the only problem is that a file made with Shelve isn't interchangable between different computers. I want my data to be exchanged between users. Does someone have an alternative to Shelve? It must be able to contain keys and values, and the values are a list of dictionaries. Try the pickle module. Kent I went from Pickle to Shelve because I couldn't store my wanted list of dictionaries in Pickle. Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternative for Shelve
Kent Johnson schreef: On Tue, May 12, 2009 at 3:59 AM, Timo wrote: Alan Gauld schreef: "Timo" wrote I have an issue with the Shelve module. It works great for my needs, the only problem is that a file made with Shelve isn't interchangable between different computers. I thought it would be. What kind of computers are you having issues with? And what kind of issues? Currently only tested between Ubuntu and Windows on the same computer. This is the end of the traceback: bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- : unsupported hash version: 9') shelve relies on the anydbm module for storage. anydbm may use any one of several actual database implementations (dbhash, gdbm, dbm or dumbdbm) depending on what is available. I guess you have different modules available on the two machines. You can find out which module is being used like this: In [7]: import anydbm In [8]: anydbm._defaultmod Out[8]: I get the same result, only I have Python 2.6 on my Ubuntu installation and 2.5 on Windows. Maybe that is the problem. But still, then the user can't upgrade without breaking their database. Also tried: >>> import whichdb >>> whichdb.whichdb('mydb.db') 'dbhash' Same result on both. Timo You could force the use of a common db module by opening the file explicitly. For example, to use dumbdbm, which is slow, simple and guaranteed to be available, something like this (untested) should work: import dumbdbm from shelve import Shelf shelf = Shelf(dumbdbm.open('myfile', 'c')) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternative for Shelve
Kent Johnson schreef: On Tue, May 12, 2009 at 4:00 AM, Timo wrote: Kent Johnson schreef: Try the pickle module. I went from Pickle to Shelve because I couldn't store my wanted list of dictionaries in Pickle. What was the problem? You should be able to create a dict whose values are lists of dicts. This would correspond to the dict-like object you get from shelve. Then the whole dict could be pickled. For example: In [10]: import pickle In [11]: d=dict() In [12]: d[1234567] = [{'date' : '2009-05-11', 'location' : 'Germany'}, {'date' : '2009-05-04', 'location' : 'France'}] In [13]: d[7654321] = [{'date' : '2009-03-12', 'location' : 'Belgium'}, {'date' : '2009-04-23', 'location' : 'Spain'}] In [14]: s = pickle.dumps(d) In [15]: s Out[15]: "(dp0\nI7654321\n(lp1\n(dp2\nS'date'\np3\nS'2009-03-12'\np4\nsS'location'\np5\nS'Belgium'\np6\nsa(dp7\ng3\nS'2009-04-23'\np8\nsg5\nS'Spain'\np9\nsasI1234567\n(lp10\n(dp11\ng3\nS'2009-05-11'\np12\nsg5\nS'Germany'\np13\nsa(dp14\ng3\nS'2009-05-04'\np15\nsg5\nS'France'\np16\nsas." In [16]: d2 = pickle.loads(s) In [17]: d2 Out[17]: {1234567: [{'date': '2009-05-11', 'location': 'Germany'}, {'date': '2009-05-04', 'location': 'France'}], 7654321: [{'date': '2009-03-12', 'location': 'Belgium'}, {'date': '2009-04-23', 'location': 'Spain'}]} Kent Hmm, I apparently missed something when I was researching it. I got mislead by the thing that Pickle can only have one key, but if you do it like this, I can indeed store multiiple ID's. I will check this out. Thanks, Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sorting a list
Hello, I don't think this should be difficult, so maybe I look over it. But I can't seem to find the solution. I have a list with one word and a couple of numbers. Now I want the word to be kept in the first location and the numbers to be sorted. So this: [4, 6, 'word', 3, 9] should be: ['word', 3, 4, 6, 9] Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting a list
Emile van Sebille schreef: On 5/13/2009 9:25 AM Timo said... Hello, I don't think this should be difficult, so maybe I look over it. But I can't seem to find the solution. I have a list with one word and a couple of numbers. If this is always the case you can use the sort method of lists, then relocate the last entry to the front -- >>> a = [4, 6, 'word', 3, 9] >>> a.sort() >>> a.insert(0,a.pop()) >>> a ['word', 3, 4, 6, 9] >>> Thanks all for your answers. I think I will go for this solution (should have come to it myself). Thanks, Timo HTH, Emile Now I want the word to be kept in the first location and the numbers to be sorted. So this: [4, 6, 'word', 3, 9] should be: ['word', 3, 4, 6, 9] Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] int to bytes and the other way around
I have written a program that uses a C++ module as backend. Now I found out that I can use Python to call an underneath C lib. That's nice, so I don't need to Popen() the C++ module. I have a problem though with some info that is returned (always an integer). I'll try to explain a bit, this is what I found out so far. There are 4 options in the program. The first 3 options go up to 18 and the fourth to 7. If all options are set to 0, the returned int is 0. If the first option is set from 1 to 18, this is what I get returned. However, for option 2, I get 256, 512, 768, 1024, etc. For option 3 I get 65536, 131072, 196608, etc, etc. And for option 4: 16777216, 33554432, etc. Ok, that's nice so far. But if option 1 is set to 4 and option 2 is set to 8 and option 3 is set to 10 (for example), I get this returned: 657412 The C++ module counts the bytes. First byte = option1, second byte = option2 etc. u8 *options = (u8 *)&result[1]; option1 = options[0] option2 = options[1] option3 = options[2] option4 = options[3] How will I approach this in Python? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating an exe
proportio...@msn.com schreef: hi, thanks to all that helped with my list question yesterday. i have now finished my program the way i want it. is there a way to compile my program so that people without python can see what i have made? Works great with py2exe. Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generating unique ID
Thanks for all the answers. I'm using SQLite as database and will try the ROWID. Timo Modulok schreef: I'm writing an application which will hold a database of people. Ofcourse, people can have the same name, so I want to stock them with an unique ID. I've searched and found some things: - uuid.uuid4() - id(name) - os.urandom(n) But they seem overkill to me. Well, maybe not id(). What should I use the best for this? Maybe examples of other programs that do something alike? Use the auto-increment feature of your database database management backend. (Assuming you're using a database backend like MySQL, postgresql, etc.) In MySQL your database description would look something like this (with any other fields you need): # MySQL table description: CREATE TABLE IF NOT EXISTS mytable ( `uid`BIGINT unsigned NOT NULL auto_increment unique, `uname` CHAR(32) NOT NULL default "guest", PRIMARY KEY (`uid`)); You could use MySQLdb (third party python module) to talk to the MySQL process with Python. Other database managers have similar abilities. os.urandom(n) Random numbers are random, NOT unique. If you're using your own backend, like a text file or whatever, stop. Take the time to learn to use a database manager like postgresql or MySQL or whatever. They have already solved many of the problems you're now facing. It will be well worth the time and frustration. Otherwise, you'll have to parse your database and get the previously used value and then increment that. However, this solution will fail if there are multiple processes, or threads accessing the data concurrently. To solve that problem you'll have to introduce some manner of mutex to gurantee that only one process has access to the unique data at any given time. Things get complicated. All of these problems have already been solved with other database managers. Use them! In a pinch, with a low volume database for non-critical data, you could probably get away with using a Unix epoch style timestamp with sufficient granularity. But even this is in no way, "guaranteed" to be unique. It's just, "probably unique". It would look like this: import time time.time() 1256796357.661967 If it absolutely must be unique, use a database manager that can make that guarantee. Best of luck! -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nul file in Windows
Dave Angel schreef: Timo List wrote: For my program I disable the py2exe log feature by routing output to the nul-file. Code: if win32 and py2exe: sys.stdout = open("nul", "w") sys.stderr = open("nul", "w") This always worked fine. Today, I received an email from a user with the following error: IOError: [Errno 2] No such file or directory: 'nul' Now, I thought the nul-file always existed, shouldn't it? Is there another way to disable output, if this one fails? Cheers, Timo All you need is an object that behaves like a file, but does nothing with the data sent to it. That's what duck-typing is all about. I haven't tried it, but I'd start by making a new class: class NullFile(object): def __init__(self, *arg, **kwarg): pass def write(self, data, *arg, **kwarg): pass def close(self, *arg, **kwarg): pass and just say sys.stdout = NullFile() Thanks, this is what I was looking for. If you get any exceptions, you could add new methods to this file, accordingly. I already catch exceptions with my own function: sys.excepthook = self.exception_hook Disabling stdout and stderr is to prevent py2exe from generating it's own logreport on exceptions. Cheers, Timo DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] search the folder for the 2 files and extract out only the version numbers 1.0 and 2.0.
I find regular expressions alwys hard to get, so here is my solution: >>> import glob >>> glob.glob('C:\\Users\\blueman\\Desktop\\allFiles\\MyTest[0-9].[0-9].zip') Cheers, Timo MARCUS NG schreef: Hi all, I am really new to python and I am trying to create a script that looks at file versions of a particular file I have 4 files in a folder. One called myTest1.0.zip, myTest2.0.zip, test3.txt and test4.zip in a directory/folder called allFiles on my desktop. so the file structure is as such C:\Users\blueman\Desktop\allFiles\myTest1.0.zip and C:\Users\blueman\Desktop\allFiles\myTest2.0.zip Aim: what is the best way to look into the allFiles directory, and only search the folder for the 2 files myTest1.0.zip and myTest2.0.zip to extract out only the version numbers 1.0 and 2.0. what i have for my script so far is import os #path of scripts folder path="C:/Users/blueman/Desktop/allFiles/" dirList=os.listdir(path) for fname in dirList: print fname so I did think of listing the file names in an array only to realise that I wouldn't know which index to query if this script is going to be automated. what is the best way to obtain the version numbers of the 2 files? thank you for your time. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactive mode questions
Op 25-12-09 17:49, rick schreef: I'm working my way through Mr Lutz's "Learning Python", and I come to this snippet (page 271): while True: reply = input('Enter text:') Try this: reply = raw_input('Enter text: ') Cheers, Timo if reply == 'stop': break print(reply.upper()) which works "as advertised" in an interactive session, but not in a script. Yes, I tried tossing the script to both versions of interpreter, it doesn't work with either 2.6 or 3.1. text given as input results in NameError: name 'text' is not defined. numerical input results in AttributeError: 'int' object has no attribute 'upper' either way, enclosing the input in quotes works. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Copy file as root
Hello, I'm writing a program in Python/pyGTK and I need to be root 2 times. The first time is to open a file, let's say menu.lst. I use os.system('gksudo gedit /boot/grub/menu.lst'), so that works. But what if I have a copy of the file on my desktop? I use shutil.copyfile() to copy the file from /boot/grub/ to /home/user/Desktop, but ofcourse need to be root to copy it back. So, how can I use shutil.copyfile() with gksudo to ask the password? Or is the another good way to do this in Python? Greets, Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy file as root
John Fouhy schreef: > On 11/06/2008, Timo <[EMAIL PROTECTED]> wrote: > >> Hello, I'm writing a program in Python/pyGTK and I need to be root 2 >> times. The first time is to open a file, let's say menu.lst. I use >> os.system('gksudo gedit /boot/grub/menu.lst'), so that works. But what >> if I have a copy of the file on my desktop? I use shutil.copyfile() to >> copy the file from /boot/grub/ to /home/user/Desktop, but ofcourse need >> to be root to copy it back. >> So, how can I use shutil.copyfile() with gksudo to ask the password? Or >> is the another good way to do this in Python? >> > > Presumably you could do os.system('gksudo cp > /home/user/Desktop/menu.lst /boot/grub') ? > > Yep correct, but this isn't the "Python" way I think. Ah well, I'll use this as a solution for now and see if I find something else. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Checking the desktop environment
Hello all, in my program I need to know what desktop environment the user is running. I figured this piece of code works, but apparently not on every Linux distro. On Ubuntu it did the trick, but then I heard of someone who runs SLiM that he get's an error with this. if os.environ['DESKTOP_SESSION'].startswith('kde'): print "Running KDE" So, does anyone know a water-proof solution for desktop environment checking? Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking the desktop environment
Thanks for your explanation. Apparently it's not possible to detect it in all cases, but it would be nice to detect it for regular users, so people who have a default install. Well, my program needs a text-editor and a graphical box for root-password. So it checks for the desktop environment so it could set these things to gedit and gksudo for Gnome and kate and kdesu for KDE. Timo Alan Gauld schreef: > "Timo" <[EMAIL PROTECTED]> wrote > >> Hello all, in my program I need to know what desktop environment the >> user is running. > > A few years ago I would have said that meant you had a broken > design since it was very bad practice for any program to depend > on the users environment. nfortunately recent developments in > Linux/X mean that the whole concept is broken that one more > environmentally wawre program probably is no big deal! > > But there are caveats that mean you will probably never get > it right in every case. The best you cvan probably do is detect > if the environment is one of a fixed set known to work with > your code.# > > But bear in mind that the user can switch envirojnemts while > your code is running, or may even be runningmultiple > environments simultaneously on virtual windows etc. > > Thats why the users environment should be left as as > something for the user and the programming environment > for the programmer. > >> I figured this piece of code works, but apparently not >> on every Linux distro. On Ubuntu it did the trick, but then I heard of >> someone who runs SLiM that he get's an error with this. >> >> if os.environ['DESKTOP_SESSION'].startswith('kde'): >>print "Running KDE" > > That would only find out if KDE was beiong used and only > if the user (or cofig scripts) has not modified the variable. > >> So, does anyone know a water-proof solution for desktop environment >> checking? > > I don't think such a thing can exist on a Unix/X system. An > approximation will be the best you can get. > > Can you explain why you need to know? > In most situations there should be a generic way to do it. > > > Alan G. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Check for file in different dirs
I want to check for a file in 3 directories. If the file is found in 1 of the dirs then do something, if the file was found in 2 or 3 dirs, then do something else. I know the paths and filename. How can this be done? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] "Analyzing" music with Python
I'm sorry if I don't use correct names etc.. What I want is to analyze a music file that is playing. Not sure if analyze is the good word for it. I just want to get info about the song in realtime when it is playing. Info about the current pitch and so. Let's say like most visualisation plugins in music players. The visualisations move on the music. I don't want to write such a plugin, but I want to get info to do something similar. Damn, hope this makes sense. Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: "Analyzing" music with Python
>if pitch == csharp: >runmyprogram(now) Yep, that is something what I'm looking for. And maybe with some other thing than pitch too (don't know what you can get from a sound file). But I looked at most of the examples of the modules and couldn't find anything like this. W W schreef: Forgot to reply to all... -- Forwarded message -- From: *W W* <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>> Date: Fri, Sep 5, 2008 at 11:54 AM Subject: Re: [Tutor] "Analyzing" music with Python To: Timo <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>> On Fri, Sep 5, 2008 at 11:26 AM, Timo <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>> wrote: Thanks for the link, found some of those things already, but not yet a solution. I'll try to make myself a bit clearer. What I want is to execute commands when the music changes. So actually a sort of visualization, but instead of drawing weird things on the screen, I want to execute commands. That's not terribly different, you might just have to hack their code to something else. So instead of: if pitch == csharp: drawsomething(blue) you would modify it to: if pitch == csharp: runmyprogram(now) or something to that effect. I'm not sure how they've implemented their visualization, but they're going to have some type of notification. Perhaps it's continuous, so you create a threshold. HTH, Wayne W W schreef: On Fri, Sep 5, 2008 at 8:34 AM, Timo <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> <mailto:[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>>> wrote: I'm sorry if I don't use correct names etc.. What I want is to analyze a music file that is playing. Not sure if analyze is the good word for it. I just want to get info about the song in realtime when it is playing. Info about the current pitch and so. Let's say like most visualisation plugins in music players. The visualisations move on the music. I don't want to write such a plugin, but I want to get info to do something similar. Damn, hope this makes sense. I'm not sure what the library would be... you probably don't need access to the music file, but the soundcard (that's my guess anyway). this link (google: python sound visualization) may be a good place to start http://wiki.python.org/moin/Audio/ HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Downloading Files from the net
What is the best/correct way to download files from a webpage? www.example.com/example.mp3 for instance. I know how to open the site (with urllib), but have no idea how to write the file to the harddisk. Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Downloading Files from the net
Mark Tolonen schreef: "Timo" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] What is the best/correct way to download files from a webpage? www.example.com/example.mp3 for instance. I know how to open the site (with urllib), but have no idea how to write the file to the harddisk. Quick and dirty, if example.mp3 isn't too big to fit in memory at once: import urllib fin = urllib.urlopen('http://www.example.com/example.mp3') fout = open('example.mp3','wb') fout.write(fin.read()) fin.close() fout.close() -Mark Ok, this is what I found too, tested it and it worked. But this "if example.mp3 isn't too big to fit in memory at once" makes me "worry". Ofcourse not for a simple mp3, but if it is a much larger file. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Downloading Files from the net
Kent Johnson schreef: On Sun, Sep 28, 2008 at 12:51 PM, Timo <[EMAIL PROTECTED]> wrote: What is the best/correct way to download files from a webpage? www.example.com/example.mp3 for instance. I know how to open the site (with urllib), but have no idea how to write the file to the harddisk. urllib.urlretrieve() will do it if you don't need anything fancy like authentication. Kent Ok thanks, this works! And this would be the best way to do it? Also some larger, around 100-200mb, files? Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sort of database & "family tree" question
Hello, I'm writing an application that stores people with some info. I'm doing this with ConfigParser and it works, but currently (for testing), there are only 10 persons in it. What if I add, let's say, about 500-600 or even more? Is this still a good choice? So my entry's look like this (more or less ;)): [person1] firstName = foo lastName = bar father = person2 mother = person3 Now, I want to make a family tree out of this, something that looks like the following scheme (hope the formating will be kept): For person "foo bar", on his father-side, and mother-side the same. | father | father--< | | mother person2--< | | father | mother--< | mother Greets, Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort of database & "family tree" question
Alan Gauld schreef: Timo wrote So my entry's look like this (more or less ;)): [person1] firstName = foo lastName = bar father = person2 mother = person3 And I assume you are reading these into a Person class and storing these classes in a persons dictionary? Then to access a father becomes: x = 'Person5' print Persons[x].father.firstName Can you explain this a little more for me please? The current way of reading the data is this: parser = ConfigParser.ConfigParser() parser.read(personFile) def get_info(person) infoDic = {} infoDic['first'] = parser.get(person, 'firstName') infoDic['last'] = parser.get(person, 'lastName') infoDic['father'] = parser.get(person, 'father') infoDic['mother'] = parser.get(person, 'mother') return infoDic But maybe it can be done better. Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort of database & "family tree" question
Alan Gauld schreef: "spir" wrote > The current way of reading the data is this: > > def get_info(person) >infoDic = {} >infoDic['first'] = parser.get(person, 'firstName') >infoDic['last'] = parser.get(person, 'lastName') >infoDic['father'] = parser.get(person, 'father') >infoDic['mother'] = parser.get(person, 'mother') >return infoDic TYhis is almost the same but you are using a dict. A sligtly more readable version is to define a class Person: class Person: def __init__(self, parser): self.first = parser.get(person, 'firstName') Hey Alan, thanks for that explanation! But the class you gave, does almost the same thing as my function. We both store the info in a dic, so to retrieve info for a certain person, we both have to do the same thing. Or am I missing something here? If so, I would love to hear it! Because I have to admit that when I program, I rarely use classes. Yes, its not normal and the class probably should be called ParsedPerson or somesuch. I ws trying to mimic the current code style as much as possible, that was the reason for the decision. Normally I would agree with you and use: class Person: def __init__(self, first, last, father, mother): self.first = first self.last = last self.father = father self.mother = mother If I do it like this, I will have to parse all the data from the file and then send them to this class and then call this class again to retrieve it. Then I like my function better. But again, I would love to hear if I'm wrong. Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Question
On 25-11-10 08:00, Mac Ryan wrote: On Thu, 25 Nov 2010 00:58:23 + Adam Bark wrote: Ah yes always avoid giving your modules names that appear in the standard library. It goes wrong, sometimes in unexpected ways. I was wondering... apart from checking each name individually, is there any easy-peasy way to get a list of names used in the standard library (I am thinking to something like "dir()"? This is the webpage I always use for searching an appropriate module: http://docs.python.org/modindex.html Cheers, Timo Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Opening and closing SQLite db
Hello, I use SQLite in my application as database, but I think I'm doing something wrong. Currently, I open a connection and cursor object every time I do an operation (insert, select, update, ...) and close it afterwards. Now I was wondering if it wouldn't be better to open the connection if my application starts, and commit and close when the user quits. Is this save? Can data be selected if I haven't commit anything? Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Opening and closing SQLite db
On 26-12-10 19:31, Noah Hall wrote: >Which is suggestible just in case the app or program crashes during use. (To O.P) Indeed, though in such cases you must rely on your programmers instinct to make the right decision - what applies for certain instances of an application doesn't always conform with what applies for other instances. For example, committing every event is hardly ideal for something such as a media player, but may be correct for something handling vital data to the system. The user gets some dialogs where he can click a save-button, so that looks like a perfect place to commit changes. But to be sure, it is perfectly safe and valid to open the database on program startup, commit changes during the process and close it on exit (or unhandled exception)? Cheers, Timo There's no "one fits all feet" rule for such things - as you program and develop more and more applications and programs, listen to your users, and your bug tests. It'll come almost naturally after a while. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python on Ubuntu 10.10?
On 15-01-11 02:17, Joel Knoll wrote: Hello, I am new to programming and to Python. I've been using Python with IDLE on Windows Vista for a few weeks now. (And I'm loving it!) However, I'm thinking about switching to Ubuntu 10.10. If I download Ubuntu, will I still be able to use the IDLE environment? I am really quite fond of it (mostly because it's what I know!). To use Python in Ubuntu, will I have to do any additional downloading, or do Python and IDLE come built in and ready to use? You should try the default text editor that comes with Ubuntu, called Gedit. You can tweak it very nicely so it shows linenumbers and so on. There are also very useful plugins. It is all I ever use and when I need to write some code in Windows, it bugs me how bad IDLE really is. Cheers, Timo Thanks for your time, JC Knoll ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] noobie question,,,error related
On 31-01-11 04:27, walter weston wrote: I get this error when I try and load the datetime module, Traceback (most recent call last): File "C:/Python27/TIMED_PROGRAM.py", line 2, in datetime.ctime() AttributeError: 'module' object has no attribute 'ctime' why is this? The error says why this is. The function ctime() isn't in the datetime module. You should have a look at the documentation [1] where you can see that ctime is a method for the date object [2] or the datetime object [3]. Cheers, Timo [1] http://docs.python.org/library/datetime.html#module-datetime [2] http://docs.python.org/library/datetime.html#datetime.date.ctime [3] http://docs.python.org/library/datetime.html#datetime.datetime.ctime ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] urgent help required! invalid syntax
On 18-02-11 09:42, lim chee siong wrote: > > > Hi, > > I was writing a module for the black-scholes pricing model in python, > but I keep getting this error message: > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\blackscholes.py", line 25 > d2=d1-v*sqrt(t) That's not the whole traceback, is it? > > This is the code in my blackscholes.py file: > #Black-Scholes model > > [snip] > > def dividend(s,x,r,t,v): > d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t)) > d2=d1-v*sqrt(t) > > [snip] > > > What is wrong here? What do I need to change? Check the line before the line which throws a syntax error. Have a good look at it and you will see you are missing a character. Cheers, Timo > Thanks! Quick reply will be much appreciated because the deadline is > tomorrow! > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble executing an if statement with a string from an input
On 18-04-11 05:11, Sylvia DeAguiar wrote: The code runs fine on python shell (from run module) but when I try to execute the program from its file, it always prints out c, regardless of the input. What is wrong? Thanks for any help :) x = input("a, b, or c:") Enter a debug print statement here to see what 'x' really is: print repr(x) Cheers, Timo if x == "a": print ("a") elif x == "b": print ("b") else: print ('c') ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Gtk - relational data display and edit
On 26-04-11 17:34, bod...@googlemail.com wrote: Hi, I am reading in data from a csv file which will be in a format like this User1, attrib1, attrib2 User2, attrib1, attrib2 Etc. And need to display this in a window. My initial thought was to use gtk.Entry widgets because I will need to edit this data, but I don't think this will work as I will also need to read the data back, in relation to the user column, e.g I will have something like [Psuedocode] For I in entries: A = usercolumn B = attrib1column C = attrib2column Somefunction(A,B,C) [/psuedocode] I don't think I could use this method with entry boxes as I have no idea how many entries there will be (column length will be fixed) so I can't create the entry widgets beforehand Use a gtk.Treeview for displaying this kind of data. You can also have editable cells inside a treeview so the user can change the data. Cheers, Timo Anyone have any suggestions? Thanks, Bodsda Sent from my BlackBerry® wireless device ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with exceptions please
On 14-05-11 05:05, Wayne Werner wrote: On Fri, May 13, 2011 at 7:48 PM, Lea Parker <mailto:lea-par...@bigpond.com>> wrote: Hello I have another assignment I am trying to fine tune. The idea is to make sure exceptions work. I have come up with a problem when testing my code. When I enter a golf score for a player the program returns the ‘error that has occurred’. I only want it to do this if someone doesn’t enter an number. I don't have a lot of time to look at it right now, but what happens when you remove the final except? Having a catch-all can hide all sorts of exceptions. If you remove that, then python should tell you what kind of error it got. That traceback will be much more helpful than 'error that has occurred'. I agree. Something is throwing an exception you don't expect. If you do want to catch it and exit gracefully, you can replace: except: print 'An error occured.' with: except Exception, exc: print 'An error occured:\n' + exc Cheers, Timo If that doesn't help you fix the problem, then remember the three things you need: 1. What did I do? 2. What did I expect would happen? 3. What happened instead? For 3, that also means that you should post all the (relevant) output. That means errors, and usually correct output, especially if there's not a whole lot of it. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making a script part of the terminal
On 20-05-11 19:43, michael scott wrote: Okay, my title might be undescriptive, let me try to explain it better. I want to take a script I've written and make it usable by typing its name in the terminal. Perfect example is the python interpreter. You just type in the word python to the terminal and then the interpreter runs. I know other programs can do this as well (like mozilla or nautilus or rhythmbox). So how do I make my scripts executable from the terminal? I can only speak for Linux, but your script should be in a directory that is in the PATH variable of your environment. The reason why you can just enter a program name in the terminal, is because these should be in /usr/bin or /usr/local/bin and these are in PATH. Type this in the terminal to see which ones: echo $PATH You can either put your script in one of those directories or add on to PATH. Cheers, Timo What is it about you... that intrigues me so? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Importing classes when needed
Hello all, I have a question about how this is done the best way. In my project I have a folder with multiple file parsers, like this: - src -- main.py -- parsers --- __init__.py --- parser1.py --- parser2.py The parsers just contain a class which do the work. When the user clicks a button, I want to show all available parsers and use the choosen one when the user clicks "ok". Is it ok to place the following code in the __init__.py? from parser1 import Parser1 from parser2 import Parser2 def get_parsers(): return [Parser1(), Parser2()] If so, is it ok to do a get_parsers() everytime the user clicks a button? Because that will initialize the parsers over and over again, right? Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GTALK and PYTHON
On 16-06-11 11:00, Dipo Elegbede wrote: Hi All, I want to write an application in python with which I can log into gtalk. Kindly point me to any documentation with which I can move on. Not to be rude, but did you use Google before asking here? There are a lot of examples and how-to's. You could also look at the program Emesene, they have a feature to login to GTalk. Cheers, Timo Advices too would be of great help.. Thanks. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com <http://www.dudupay.com> Mobile Banking Solutions | Transaction Processing | Enterprise Application Development ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html files to pdf document
On 20-06-11 17:34, arun kumar wrote: HI, i have a some 100 plus html individual files.I want to convert them to a single pdf document programatically. How to convert them in python. Are there any functions,modules or libraries for python to achieve this. Just a question, but did you use Google before asking here? Because the first hit when searching for "python html to pdf" looks like it should do what you want. Cheers, Timo -- Thank you Arun Kumar http://clicknscroll.blogspot.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipping files and Mysql
On 27-06-11 21:45, gagnr...@verizon.net wrote: I am trying to write a script that will dump a mysql db and then zip the file. I do know about mysqldb, but I was wondering if there is anything native to the libraries that will allow me to do this without using a seperate piece. Then after I gather the DBs, I need to zip them. I wrote the following, but wanted to know if I am heading in the correct direction. zipfile.zipfile(/myfiles/my_db/, w, zip_stored) Well, for what it's worth, I'm using the zipfile module as well in one of my projects to make a backup of the user's configuration directory. Which works pretty good. Do have a good look though at the documentation or find some examples through your search engine, because the above line won't work at all. Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic program question
On 24-07-11 22:59, Alexander Quest wrote: Hello- I am running Python v 3.1.1. As an exercise, I wrote a simple coin flipper program, where the computer flips a coin 100 times and then prints out the number of heads and tails. My program crashes immediately if I run it normally through the command line, but if I go to "Run- Run Module," it seems to work just fine. I can't seem to figure out why. I've pasted the relevant code below- any help will be greatly appreciated. Thanks! If I read it correctly, you probably *think* it crashes because when you run this script from the terminal, it will close right after it finishes so you can't see any output. See the last line for the solution. import random print("\tWelcome to the 'Coin Flipper' program!") counter = 0 heads = 0 tails = 0 while counter < 100: the_number = random.randint(1, 2) if the_number == 1: heads += 1 else: tails += 1 counter += 1 print("\nI flipped the coint 100 times.") print("It came up heads", heads, "times and tails", tails, "times.") print("\n\nPress the enter key to exit.") Change this line to: input("\n\nPress any key to exit.") Cheers, Timo _ -Alex ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python 2.3.4, how to use os.system and collect it's output to a file.
On 02-08-11 17:40, Thirupathaiah Gande (tgande) wrote: Hi, I have Python 2.3.4. Is there some reason for this? You probably should update to 2.7 if possible. Then have a look at the Subprocess module documentation. There are some examples which should get you on the way. Cheers, Timo I want to use os.system command and collect a command’s output to a file. But it is not collecting all the output. It is truncating.. Code is as below. cmd = "%s rl -comp %s@%s/%d >> %s" % (C_CMD, i, branch, x, temp_acme_rl_log) cmd_res = os.system( cmd ) What I am missing? Thanks gande ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting from a single module to a package
On 06-08-11 01:38, Emile van Sebille wrote: On 8/5/2011 4:22 PM Tim Johnson said... * Christopher King [110805 12:03]: To make a package, you make a folder named what you want to name the package, for example: virus_toolkit. Then you make a file in it called __init__.py. This is what you import if you import the virus_toolkit. You usually put documentation and general functions in this But you can provide for both methods if in tlib.__init__ you provide for backward compatibility. # current way import tlib as std std.htmlButton(*arglist) # New way, after transition import tlib as std in tlib.__init__, include the following: import html htmlButton = html.button And print a deprecation warning when people use it like this. That way you let them know this method could be removed in a next version. See the warnings module. Cheers, Timo std.html.button(*arglist) #OR import html from tlib html.button(*arglist) Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Adding index numbers to tuple
Hello, Maybe a bit confusing topic title, probably the example will do. I have a tuple: t = ('a', 'b', 'c', 'd') And need the following output, list or tuple, doesn't matter: (0, 'a', 1, 'b', 2, 'c', 3, 'd') I tried with zip(), but get a list of tuples, which isn't the desired output. Anyone with a solution or push in the right direction? Cheers, TImo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
On 16-08-11 20:46, Susana Iraiis Delgado Rodriguez wrote: Hello List! I just started to use PyGTK and Glade to create graphical interfaces, my python interpreter version is 2.6.6; I also install the GTK2 Runtime enviroment and Glade 3.6.6. I also installed in my computer pycairo-1.8.10.win32-py2.6.exe, pygobject-2.26.0-1.win32-py2.6.exe and pygtk-2.16.0+glade.win32-py2.6.exe so my graphic application will look and work fine. I tried to do an example in order to get familiar with this new tool, but when I run the script I got the next message: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import glade1 ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow) ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible) ** Message: pygobject_register_sinkfunc is deprecated (GtkObject) >>> My code is: import pygtk pygtk.require("2.0") import gtk import gtk.glade gtk.glade is deprecated, you should use the builtin gtk.builder instead (Google for examples). You should also get the latest GTK/PyGTK versions from the PyGTK website. There is a really nice all-in-one installer! Cheers, Timo class MainWin: def __init__(self): self.widgets = gtk.glade.XML("ejemplo_glade.glade") signals = { "on_entry1_activate" : self.on_button1_clicked, "on_button1_clicked" : self.on_button1_clicked, "gtk_main_quit" : gtk.main_quit } self.widgets.signal_autoconnect(signals) self.label1 = self.widgets.get_widget("label1") self.entry1 = self.widgets.get_widget("entry1") def on_button1_clicked(self, widget): texto = self.entry1.get_text() self.label1.set_text("Hola %s" % texto) if __name__ == "__main__": MainWin() gtk.main() Does my python libraries are the correct ones for my interpreter? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Another question about graphics.
Op 10-11-11 06:03, Nathaniel Trujillo schreef: I am using python version 2.7.2. I put the version of livewires for python 2.x in the right folder this time and after running the following program I got a different error message. Here they are. program # New Graphics Window # Demonstrates creating a graphics window from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop() error message Traceback (most recent call last): File "C:/Python27/new_graphics_window.py", line 6, in games.init(screen_width = 640, screen_height = 480, fps = 50) AttributeError: 'module' object has no attribute 'init' Well, the error says it all. The games module has no init method. You should probably see the livewires documentation or mailing list for such questions. The chance for getting your third-party module questions answered is pretty small here. Cheers, Timo Thanks for the help. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running windows media player
Op 15-11-11 04:29, MD.Mahbubur Rahman schreef: Hello friends, I need to run mp3/ogg files with Windows Media Player from a python script. I have the following code which only can start Windows Media Player. But I dont know how to run a mp3/ogg file with this instance of Windows Media Player: I don't have Windows, so can't test, but according to this Microsoft page [1], you can give some comandline parameters to WMP. Cheers, Timo [1] http://support.microsoft.com/kb/241422/en-us from pywinauto import application app = application.Application() try: wmp = app.start_( # connect_(path = ur"C:\Program Files\Windows Media Player\wmplayer.exe") except application.ProcessNotFoundError: print "Error Message " Can someone help me? Br Mahbub ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IndentationError:
Op 16-11-11 09:46, lina schreef: On Wed, Nov 16, 2011 at 4:31 PM, Andre Engels wrote: On Wed, Nov 16, 2011 at 9:21 AM, lina wrote: it still complaining. I set the gedit, use space not tab, Now I even typed space by space, avoid using tab, it still has the same problem. How can I fixed it? The line if list1[i][j] != list1[i][j+1]: still contains a tab, thus it is now indented negative 3 spaces plus a tab plus 3 spaces compared to the encompassing loop, which is problematic both because there is a negative number in there and because it differs from the rest of the lines in the same loop (6 spaces) Thanks, fixed, seems my gedit has problem? the preference setting using space, not Tab, really headache about it, sometimes. Gedit won't alter existing tabs when adjusting that setting. So that tab was probably already there, or you copy-pasted it from some other source. Cheers, Timo Thanks again, -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to handle conjunction operators
Op 27-11-11 20:02, Hugo Arts schreef: On Sun, Nov 27, 2011 at 7:52 PM, surya k wrote: Hi, Could you please tell me why this isn't working and how can I make it possible... Consider this code.. name = raw_input("Enter your first name: ") if name[0] == ("m" or "f" or "b") : rhyme = name[1:] What I want here is.. If the name starts with 'm' or 'f' or 'b', The first letter should be removed. But this isn't happening here. This is a very common error. Fact is, the or operator just isn't distributive with respect to the == operator like that, and for good reason. What you want is either this: if name[0] == "m" or name[0] == "f" or name[0] == "b": or, more idiomatically, you can use the in operator like this: if name[0] in ("m", "f", "b"): Or even shorter: if name[0] in "mfb": Cheers, Timo HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] where python is used in real world
Op 04-12-11 08:47, surya k schreef: I don't understand why python doesn't provide executable files for the source code. I am using py2exe for building executables and I found that, it doesn't completely change code into binary but creates dll files and python libraries to run that particular code. This process makes program very large although it isn't. I think Windows is the only operating system which doesn't come with Python pre-installed (except some exotic ones). But on Windows, you do install JVM to run Jave programs, .NET, Flash, ... why not the Python interpreter to run Python programs? Cheers, Timo 1. Why doesn't python doesn't offer executable file ? 2. If one wants to make a commercial software using python, how can he hide the code? 3. However, if one wants to make an open source software, as python doesn't offer executable files, how people make those so as to distribute their products to people? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary to variable copy
Op 08-12-11 10:03, sunil tech schreef: /Can i copy the content if a dictionary in to another variable, with out any link between the dictionary & the variable? / Have a look at the copy module [1], or use the builtin dict.copy() method. Cheers, Timo [1] http://docs.python.org/library/copy.html#module-copy / if so, please teach. / ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pygame blinking text
Op 12-12-11 15:01, Cranky Frankie schreef: My Python presentation is just about complete. As a nice ending I want to do a pygame program that displays the group's .jpg, with the words "Thank You!" blinking, say on for a second and off for a second. Unfortunatley, I can't get the works to blink, but I can get them to appear for a short time: from livewires import games, color Looks like you're not using pygame, but livewires. Why not try their mailinglist, I bet their knowledge is better than this *Python beginners* list. Cheers, Timo games.init(screen_width = 640, screen_height = 480, fps = 50) bg_image = games.load_image("AEMUG640x480.JPG", transparent = False) games.screen.background = bg_image ty_message = games.Message(value = "Thank You!", size = 100, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 100, after_death = 0) games.screen.add(ty_message) games.screen.mainloop() I tried putting the ty_message block in a WHILE TRUE loop, and that didn't work. Then I tried the same with the games.screen.add(ty_message) line and that didn't work either. I think what might work is if I can find a way to delete the ty_message and readd it, over and over in a loop with a delay, bu: games.screen.delete(ty_message) doesn't work - delete is not a valid method. Is there any way to get blinking text with pygame? This is not a deal breaker, but I thought the blinking text would be neat. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] timedelta, difference calculation
Op 12-12-11 20:46, rail shafigulin schreef: i found something interesting during the timedate difference calculation import datetime import time def main(): mydatetime = datetime.datetime.now() time.sleep(1) mydatetime2 = datetime.datetime.now() diff = mydatetime - mydatetime2 Lie Ryan explains how to read the output below, but you made a little error here. Let's have a little example: >>> x1 = 1 >>> x2 = x1 + 1 >>> print(x1 - x2) -1 >>> print(x2 - x1) 1 So you should substract mydatetime from mydatetime2, not the other way around. Cheers, Timo print(diff) if __name__ == '__main__': main() if you run this code the result you get will be -1 day, 23:59:59 at least that is what i'm getting. i was expecting to get -1 second. diff object is of type timedelta. this kind of objects represent duration, at least that is what i understood from the documentation (http://docs.python.org/release/3.1.3/library/datetime.html#timedelta-objects). so, is this a bug in the timedelta implementation or is it me not understanding documentation properly? any help is appreciated. ps. i'm using python 3.1 on a windows xp machine. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to print the match middle part out
Op 15-12-11 17:52, lina schreef: Hi, For following: aaa model 0 bbb acb model 1 ccc How can I set regexp1 as "model 0" and end "model 1" so the final print out will be: model 0 bbb acb Just iterate over the lines (file or string) and retrieve the lines from the wanted line, until the line you're not interested in anymore. something like this: data = """aaa model 0 bbb acb model 1 ccc""" result = [] first_reached = False for line in data.split('\n'): if line == 'model 0': first_reached = True if line == 'model 1': break if first_reached: result.append(line) print result Cheers, Timo above is a very simple example, Thanks for any advice, Best, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python logger
Op 28-12-11 18:13, rail shafigulin schreef: has anyone used python logger before? i'm trying to adapt it for my workplace. right now it is pretty simplistic for me. i'm trying to generate extra output by the LoggerAdapter. however i'm getting errors. specifically i get the following message: Traceback (most recent call last): File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit msg = self.format(record) File "/usr/lib/python3.1/logging/__init__.py", line 650, in format return fmt.format(record) File "/usr/lib/python3.1/logging/__init__.py", line 438, in format record.message = record.getMessage() File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting Without reading the code, you are passing too many arguments for a format string. >>> msg = 'one arg %s and a second %s' >>> msg % ('foo', 'bar', 'baz') # Pass 3 arguments Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Cheers, Timo i'm using this <http://docs.python.org/release/3.1.3/library/logging.html#using-loggeradapters-to-impart-contextual-information> documentation. any here is my code import logging import logging.handlers class TestInfo(object): def __init__(self, test_name = None, description = '', notes = '', expected = None, actual = None, status = 'Fail', timestamp = None): self.__test_name = test_name self.__description = description self.__notes = notes self.__expected = expected self.__actual = actual self.__status = status self.__timestamp = timestamp def __getitem__(self, name): """ To allow this instance to look like a dict. """ result = None if 'test_name' == name: result = self.__test_name elif 'description' == name: result = self.__description elif 'notes' == name: result = self.__notes elif 'expected' == name: result = self.__expected elif 'actual' == name: result = self.__actual elif 'status' == name: status = self.__status elif 'timestamp' == name: timestamp = self.__timestamp else: result = self.__dict__.get(name, "?") return result def __iter__(self): """ To allow iteration over keys, which will be merged into the LogRecord dict before formatting and output. """ names = ['test_name', 'description', 'notes', 'expected', 'actual', 'status', 'timestamp'] names.extend(self.__dict__.keys()) return names.__iter__() def main(): testinfo = TestInfo( test_name = 'myname', description = 'mydescription', notes = 'mynotes', expected = 'myexpected', actual = 'myactual', status = 'Fail', timestamp = 'mystamp') mylogger = logging.getLogger('mylogger') mylogger.setLevel(logging.DEBUG) filehandler = logging.FileHandler('test.log') filehandler.setLevel(logging.DEBUG) mylogger.addHandler(filehandler) mylogadapter = logger.LoggerAdapter(mylogger, testinfo) mylogadapter.info <http://mylogadapter.info>('this is a log message', testinfo) if __name__ == "__main__": main() any help on how to add extra output parameters is appreciated. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Database Scripting
Op 08-02-12 20:20, Brad Hudson schreef: Thanks for the responses Alan & Modulok. I will start with SQLAlchemy and see where it takes me. I was looking for something similar a couple of months ago and chose to use SQLObject over SQLAlchemy. In my eyes it was much easier to use. Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to start with Glade.
Op 05-03-12 10:31, Ganesh Kumar schreef: Hi Guys, I am new to GUI, I know little bit python, But I do know, How to start with Glade and how to combine with .glade file to python. please guide me.. This is more of a question for the PyGTK mailing list. This is the bare minimum you need: import gtk builder = gtk.Builder() builder.add_from_file("mywindow.ui") gtk.main() Ofcourse, alot more can/needs to be done, like connecting signals. You should have a google session for "pygtk glade" or something similar and plenty of good tutorials and blogposts will show up that will explain these things. Timo -Ganesh Did I learn something today? If not, I wasted it. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] gtk.TreeView displays all right on Windows, but can't see the values on Ubuntu
Op 25-04-12 06:41, Lion Chen schreef: Hi, All, Hi, please fix your formatting, the indentation is a big mess and makes it impossible to read. You should also ask your question on the PyGTK mailing list, not here. first thanks the people who gave helps to me, :) now i encountered another question... my first program LionCalculator, works ok on Windows, but there is a problem on Ubuntu. LionCalculator has a function that can store the previous calculation results to the gtk.ListStore((gobject.TYPE_STRING, gobject.TYPE_BOOLEAN, gobject.TYPE_STRING)) for i in xrange(12): self.results_store.append(["F%d" % (i+1), None, None]) when pressed F1--F12 or click the gtk.CellRendererRadio, the gtk.Entry will get the corresbonding values stored in ListStore. when i run the program on Windows, no problem, i can see everything that should display on the screen. but when i run it on Ubuntu, i can't see the "F1" -- "F12" in the ListStore, can't see the calculation results that should also display on ListStore, only the gtk.CellRendererRadio showed. i don't understand... and when i add "print ...get_store()[0][0]" and run it again, it print "F1"! strange... and when i press F1 or F2..., the result will copy to the entry, although it does not display in the TreeView, strange... the following are codes: #in class ResultsView.. def make_view(self): # make ListStore for storing results self.results_store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_BOOLEAN, gobject.TYPE_STRING) #to store 12 calculation results, the results_store[0][0] is "F1--F12" for i in xrange(12): self.results_store.append(["F%d" % (i+1), None, None]) self.results_view = gtk.TreeView(self.results_store) #f_renderer is for "F1" -- "F12" f_renderer = gtk.CellRendererText() f_renderer.set_property( 'editable', False ) f_renderer.set_property("size", 5) f_renderer.set_property("cell-background", "cyan") #when clicked bt_renderer, it will copy the corresbonding values to gtk.entry bt_renderer = gtk.CellRendererToggle() bt_renderer.set_property('activatable', True) bt_renderer.set_property("radio", True) bt_renderer.set_property("cell-background", "grey") bt_renderer.connect("toggled", self.ready_cp, self.results_store) #txt_renderer is for storing calculation results txt_renderer = gtk.CellRendererText() txt_renderer.set_property( 'editable', False ) txt_renderer.set_property("size", 5) txt_renderer.set_property("cell-background", "green") #i guess the problem is in the following, but i don't know where it exactly is, ok in Windows, can't show in Ubuntu... bt_column = gtk.TreeViewColumn("F1--F12") bt_column.pack_start(f_renderer, True) bt_column.pack_start(bt_renderer, False) bt_column.set_attributes(f_renderer, text=0) #set active to be clickable. and the bt_columen is #corresbonding to results_store columne 1 bt_column.add_attribute(bt_renderer, "active", 1) #and txt_column is corresbonding to the store column 2 txt_column = gtk.TreeViewColumn("Calculation Results ", txt_renderer, text=2) self.results_view.append_column(bt_column) self.results_view.append_column(txt_column) self.results_view.show() return self.results_view #in class LionCalc def __init__(self): .. self.results_view = ResultsView() right_vbox.pack_start(self.results_view.make_view(), True, True, 0) win.show_all() could anybody give me help? thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to create self contained Windows executables (.exe files) from python scripts
Op 18-05-12 01:02, Brad Hudson schreef: Can someone point me to information on how to create Windows .exe files from python 2.7.3? The py2exe method (www.py2exe.org <http://www.py2exe.org>) appears to only be available for python 2.6 from the sites I've seen. I distribute a PyGTK application that is written in Python 2.7 and compiled with Py2exe, so it's possible. When looking at the downloads, there are -py2.7 versions available: http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/ Timo Thanks in advance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] entering text on web site
Op 14-06-12 04:44, Benjamin Fishbein schreef: Thanks. I'm trying to automatically post text to a web page from Python and retrieve the resultant page. It's not just name and password, though; I need to do it over and over again with chunks of info from a list. The page seems to be using POST. form method='POST' is written all throughout the code. The links you recommended use modules like Client Cookie, mechanize, etc. I guess Python didn't come standard with a module that could do what I wanted... Which is the best module to get for this? I had successful results with the mechanize package in the past. Timo Ben On Jun 13, 2012, at 8:27 AM, Walter Prins wrote: Hi, On 13 June 2012 13:35, Benjamin Fishbein <mailto:bfishbei...@gmail.com>> wrote: Hello. I have been teaching myself Python and have been stuck on this problem for a week--I scoured the web for an answer and even asked a couple computer programmer friends. I managed to write a simple program with urllib that downloads the content from web pages; but I want to put text in a text box on the webpage, have it entered into the website, and then get the results. Is there a way to do this with Python? Please clarify, are you: a) Trying to automatically post some text to a web page from Python and then retrieve the resultant page? (for example, username and password and retrieve resultant logon page.) b) Trying to use Python to present a webpage that a user then puts text in a box which the Python program then captures when the user submits the page? I'm assuming a.) If so, then I should ask, does this page use POST or GET style submission? In any case, here's a stackeroverflow question regarding using POST and cookies etc: http://stackoverflow.com/questions/2954381/python-form-post-using-urllib2-also-question-on-saving-using-cookies .. with the default Python documentation doing a decent job of explaining GET: http://docs.python.org/howto/urllib2.html This also seems useful/relevant: http://stackoverflow.com/questions/10916745/scraping-data-from-simple-website-change-post-to-get Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why begin a function name with an underscore
Op 28-08-12 10:06, Richard D. Moores schreef: On Tue, Aug 28, 2012 at 12:13 AM, Jerry Zhang wrote: 2012/8/28 Richard D. Moores On Mon, Aug 27, 2012 at 6:33 PM, Japhy Bartlett wrote: something like: def _validate_int(obj): """Raise an exception if obj is not an integer.""" m = int(obj + 0) # May raise TypeError. if obj != m: raise ValueError('expected an integer but got %r' % obj) is a really awkward way to test if something's an integer, and checking types in general is usually a sign of larger flaws in laying out useful code. What the best way to test if something's an integer? a = 4 isinstance(a, int) True isinstance(3., int) False What if I wanted 3., 1234., etc. to be considered ints, as they are by _validate_int() ? >>> isinstance(3., (int, float)) True Because 3. is a float, not int. Timo Dick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing name value with function return
Op 30-10-12 17:56, richard kappler schreef: If I have a variable and send it's value to a function to be modified and returned, how do I get the function return to replace the original value of the variable? Example: import random x = 50 def rndDelta(x): d = random.uniform(-10, 10) x = x + d return x When I call rndDelta, it functions as intended, I get a return that is x adjusted by some random value. This, however, I know does not actually change x. Let's say I call randDelta(x) and it returns 42.098734087, if I then type x, I still get 50. I want x to now be 42.098734087. What about declaring the return value as x again? x = randDelta(x) Timo regards, Richard -- sic gorgiamus allos subjectatos nunc ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Spongebob Pythonpants
Op 24-04-15 om 04:37 schreef Jim Mooney: I was depressed at the thought of learning unicode, then discovered Python was fun again since I can easily print any ascii art from http://www.chris.com/ascii/ with a multiline print, so long as I replace any backslash with two of them. You can save yourself some time and use a raw string: print(r""" """) Timo Spongebob Squarepants was, of course, the obvious first choice. The heck with Tkinter. (Bob is coming out a bit thin in my gmail but looks fine in the REPL.) print(''' .--..--..--..--..--..--. .' \\ (`._ (_) _ \\ .'| '._) (_) | \\ _.')\\ ...---. / |(_.' |/.-\\-. \\ | \\ 0|| ( O| O) | o| | _ | .--..'._.-. | \\ (_) | o -` .-` | |\\ |`-._ _ _ _ _\\ / \\| | `. |_||_| | | o |\\_ \\ | -. .-. |.-. \\ `--..-' O | `.`-' .' _.' .' | `-.-' /-.__ ' .-' .' `-.` '.|='=.='=.='=.='=|._/_ `-'.' `-._ `. |/\\_|`-.' .' ).| '=' '='\\/ '=' | `._.` '---' //___\\ //___\\ || || LGB ||_.-. ||_.-. (_.--__) (_.--__)''') *** Remote Interpreter Reinitialized *** .--..--..--..--..--..--. .' \ (`._ (_) _ \ .'| '._) (_) | \ _.')\ ...---. / |(_.' |/.-\-. \ | \ 0|| ( O| O) | o| | _ | .--..'._.-. | \ (_) | o -` .-` | |\ |`-._ _ _ _ _\ / \| | `. |_||_| | | o |\_ \ | -. .-. |.-. \ `--..-' O | `.`-' .' _.' .' | `-.-' /-.__ ' .-' .' `-.` '.|='=.='=.='=.='=|._/_ `-'.' `-._ `. |/\_|`-.' .' ).| '=' '='\/ '=' | `._.` '---' //___\ //___\ || || LGB ||_.-. ||_.-. (_.--__) (_.--__) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python and Beautiful soup question
Op 21-06-15 om 22:04 schreef Joshua Valdez: I'm having trouble making this script work to scrape information from a series of Wikipedia articles. What I'm trying to do is iterate over a series of wiki URLs and pull out the page links on a wiki portal category (e.g. https://en.wikipedia.org/wiki/Category:Electronic_design). Instead of scraping the webpage, I'd have a look at the API. This might give much better and more reliable results than to rely on parsing HTML. https://www.mediawiki.org/wiki/API:Main_page You can try out the huge amount of different options (with small descriptions) on the sandbox page: https://en.wikipedia.org/wiki/Special:ApiSandbox Timo *Joshua Valdez* *Computational Linguist : Cognitive Scientist * (440)-231-0479 jd...@case.edu | j...@uw.edu | jo...@armsandanchors.com <http://www.linkedin.com/in/valdezjoshua/> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to extract variables from GUI objects
Op 19-08-15 om 01:08 schreef Eric Kelly: I am a beginner with Python and would like to write a program that includes a GUI to run it. I've been through a tutorial on using Python but I'm trying to also use Gtk and Glade to make the GUI. I've tried to use the docs and other tutorials but alas I'm still stuck. The problem is simply to get the text from a combotext object. I simplified the program by only including the combo object and a "Run" button. The user should be able to choose a value from the list or enter a different value manually. When I click the "Run" button to print the combo text, I think I get the memory address. Here is the message that appears when I click Run: "" You are printing the actual Gtk.ComboBoxText class. Take this simple pure Python example: >>> class Foo: pass ... >>> f = Foo() >>> print(f) <__main__.Foo object at 0x7f3f32e31630> See the similarity? You will have to call the get_active_text() method on the Gtk.ComboBoxText class to get the selected text. API docs: http://lazka.github.io/pgi-docs/Gtk-3.0/classes/ComboBoxText.html#Gtk.ComboBoxText.get_active_text Tutorial: http://learngtk.org/tutorials/python_gtk3_tutorial/html/comboboxtext.html So your code becomes: def on_buttonRun_clicked(self,widget): comboText = self.builder.get_object('comboboxtext1') print(comboText.get_active_text()) Here are the full Gtk API docs: http://lazka.github.io/pgi-docs/index.html#Gtk-3.0 And here the tutorial: http://learngtk.org/tutorials/python_gtk3_tutorial/html/ Timo I realize that the program does not know what part of the object to get, but I am unclear about how to tell it where the text is. I've tried assigning variable names to what I think are the appropriate user data values, but of course none worked. I'm using Glade 3, Gtk+ 3, and Python 34. Thanks in advance for any help and suggestions (I'm sure there are other mistakes here too). Eric The Python code is here: #!C:\Python34 from gi.repository import Gtk # Make a window to control the program class MyGI(Gtk.Window): def __init__(self): Gtk.Window.__init__(self,title='Title') self.builder = Gtk.Builder() self.builder.add_from_file('GI_test.glade') # Define handlers for signals from window handlersDict = { 'on_applicationwindow1_destroy':Gtk.main_quit, 'on_buttonRun_clicked':self.on_buttonRun_clicked } # Get the objects from the window self.window = self.builder.get_object('applicationwindow1') self.buttonRun = self.builder.get_object('buttonRun') # Connect the signals with their handlers self.builder.connect_signals(handlersDict) def on_buttonRun_clicked(self,widget): comboText = self.builder.get_object('comboboxtext1') print(comboText) def main(): win = MyGI() Gtk.main() if __name__ == '__main__': main() The XML code is here: --- True False True False vertical True False 5 0 100 200 False True 0 Run True True True False True 1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with code
Op 20-08-15 om 16:49 schreef Aravind Jaya: time = input("How long on average do you spend on the computer per day?") if time <= 2: print "Message1" else: print "Message2" This will raise 2 errors: - time will be a string. So time <= 2 is invalid. - print is a function. Updated code: time = int(input("How long on average do you spend on the computer per day?")) if time <= 2: print("Message1") else: print("Message2") Also the question is ambiguous. There is no time unit. What is "long"? Timo On Thu, Aug 20, 2015 at 3:20 PM, Nathan Clark <26110...@gmail.com> wrote: I have written a basic program out of python and it is not functioning, please could you proof read my code and tell me how to fix it.It is in python 3.3 time=int(input("How long on average do you spend on the computer per day?") (print("that seems reasonable")) if time<=2 else print ("get a life") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help error 504
Op 25-08-15 om 02:08 schreef Gonzalo V: how can simulate or emulate an error 504? I think using a site like http://httpbin.org/ is a bit easier than mock or your own server. Just change your request url to: http://httpbin.org/status/504 Timo i am new in python and its very intuitive! but i am in problems with that code. i wrote this code and it cant handle 504 error: import urllib.request import urllib.error from bs4 import BeautifulSoup import re, csv from FuncionCsv import LlenarCsv fhand=open('isbn.txt') #csvfile=open('ResultadoScrapping.csv', 'w', newline='') for line in fhand: req=urllib.request.urlopen(''+line) resp=req.read() soup=BeautifulSoup(resp,'html.parser') try: origen=soup.find(string=re.compile("Origen: ")).find_next().get_text() nombre=soup.find(name="h1",itemprop="name").get_text() precioAhora=soup.find(name="p",class_="precioAhora").get_text() d=soup.find(name="p",class_="stock").get_text() disp=d.split() except AttributeError: disp="no encontrado" nombre='' origen='' precioAhora='' except urllib.error.HTTPError as e: if e.getcode()==504: disp = "sin respuesta del servidor" print (e.getcode(),disp) csvfile.close() print(line,nombre,origen,precioAhora,disp) line1=line.split() LlenarCsv('Resultado.csv',line1,nombre,origen,precioAhora,disp) please help! Saludos, Gonzalo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More Pythonic?
Op 09-09-15 om 15:41 schreef Steven D'Aprano: On Wed, Sep 09, 2015 at 09:05:23AM -0400, richard kappler wrote: Would either or both of these work, if both, which is the better or more Pythonic way to do it, and why? The first works, but isn't really the best way to do it: ### import whatIsNeeded writefile = open("writefile", 'a') with open(readfile, 'r') as f: for line in f: if keyword in line: do stuff f1.write(line) else: f1.write(line) writefile.close() ## Better would be this: with open("writefile", 'a') as outfile: with open("readfile", 'r') as infile: for line in infile: if keyword in line: do stuff outfile.write(line) It's also possible to use multiple with statements on the same line. Can someone with more expert Python knowledge than me comment on whether it's different from using them separate as mentioned by Steven? This is what I had in mind: with open("writefile", 'a') as outfile, open("readfile", 'r') as infile: pass # Rest of the code here Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Adding items from a cursor to a dict?
Op 12-11-12 09:29, Khalid Al-Ghamdi schreef: Hi all, How would you go about adding items from a cursor to a dictionary? There is a nice buitin way, with example here: http://docs.python.org/2/library/sqlite3.html#sqlite3.Row It's not a real dictionary though, but it can act like it. Also, the docs say the following: """ If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution. """ Timo i tried this but to no avail: >>> cur.execute('select * from schedule limit 10') >>> for i in range(len(cur.fetchall())): d[i]=cur.fetchall()[i] Traceback (most recent call last): File "", line 2, in d[i]=cur.fetchall()[i] IndexError: list index out of range Thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating a torrent file & associated tracker through a django web app
Op 21-11-12 08:54, ashish makani schreef: Hi Tutor folks I am trying to achieve the following : The user should log into a web app, select a file & the web app should generate a .torrent file & a private tracker(http://IP_ADDRESS:PORT_NUMBER/announce) for that .torrent file. Basically, i want to programmatically create a .torrent file, on the server side. I found two libraries mktorrent[1] & py3createtorrent [2], but i need help with how to create a torrent from a django web app. Any suggestions for django modules or libraries which can do this ? You don't need Django specific modules, just use the ones you linked and install them on your server. It doesn't matter if you call it from a script on your desktop or a Django webapp. Looking at the example on Wikipedia [1], it's not hard to create it manually. It even looks like a JSON file, you'll just need a way to bencode the data. Timo [1] http://en.wikipedia.org/wiki/Torrent_file#Single_file Any suggestions/pointers/ideas/links will be greatly appreciated Thanks a ton, cheers, ashish 1. http://mktorrent.sourceforge.net/ 2. http://www.robertnitsch.de/projects/py3createtorrent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Parsing and evaluating user input
I'm having trouble finding a safe way to parse and evaluate user input in my program. In my app, I'm using a calculation like this: (a / b) * 100 The user should be able to override this and their preference is stored in a configuration file for later use. So I now have a string with the user defined calculation template, for example: >>> config.get('custom-calc') '(a * b) / 10' I could tell the user the values should be entered like %(a)s and %(b)s which makes parsing easier I think, because I can do this: >>> custom_calc = config.get('custom-calc') >>> custom_calc '(%(a)s * %(b)s) / 10' >>> calc_str = custom_calc % {'a': get_value_a(), 'b': get_value_b()} I should parse this, fill in the values which the program has at that point and calculate the outcome. What is the safest way? Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] If a method has no return type?
Op 07-02-13 10:09, Sunil Tech schreef: Thank you Wesley, Kal & tutor In the future, the Python interpreter comes in handy for quick checks. >>> def spam(): ... pass ... >>> s = spam() >>> s, repr(s), type(s) (None, 'None', ) Timo On Thu, Feb 7, 2013 at 12:07 PM, Kal Sze <mailto:swordan...@gmail.com>> wrote: Dear Sunil, No method or function in Python has a *static* return type. That's because Python is by nature a dynamic language, with duck typing and dynamic dispatch. In fact, any method or function may well return any of a number of different types: def crazy_function(return_int) if return_int: return 1 else: return 'foo' It's probably bad design, but there is nothing in the Python grammar and semantics that stops you from doing that. So your question is better phrased as: if I don't explicitly return anything, what is returned? The answer to that would be: the None object Cheers, Kal On 7 February 2013 14:09, Sunil Tech mailto:sunil.tech...@gmail.com>> wrote: > If a method has no return type? > what will it return? > > ___ > Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which pip for Ubuntu 12.04
Op 10-02-13 17:01, Jim Byrnes schreef: On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote: - Original Message - From: Jim Byrnes To: tutor@python.org Cc: Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip for Ubuntu 12.04 How important is it to have the latest pip installed? Initially I want to use it to install the latest pymongo driver for mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. I see on http://www.pip-installer.org/en/latest/ the version is 1.2.1. It certainly would be easier to install from the repositories but will that version work to install the latest python packages? Thanks, Jim You could just try it? And downloading it and then doing sudo tar -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is it? I usually install from the repositories or maybe a ppa so I don't believe I have ever done an install from a tar. If necessary I will familiarize myself with the command you gave (yes I saw your followup changing -xvr to -xvf) and install that way. However, I still wonder if using the outdated pip from the repository will allow me to install the latest python packages? Will trying to use an outdated pip cause me problems? I doubt it will. Have a look at the pip changelog to see what has been changed. Timo But you're right, I also nnoticed that the Canonical repositories are a little outdated sometimes. Would be nice if it's possible to add pypi.org, so updating would be easier. Albert-Jan Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Use __str__ method for int values
Op 10-03-13 09:57, Vincent Balmori schreef: I am trying to use a __str__ method to display the values of attribute mood = self.hunger + self. boredom. When I try to execute I get this error: Traceback (most recent call last): File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for the Absolute Beginner - Project Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in main() File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for the Absolute Beginner - Project Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main print(crit) TypeError: __str__ returned non-string (type int) Then return a str instead of int. This is the code: # Critter Caretaker # A virtual pet to care for import random class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom def __pass_time(self): self.hunger += 1 self.boredom += 1 def __str__(self): mood = self.boredom + self.hunger return mood Change to: return str(mood) Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Socket Programming
Op 08-04-13 09:06, Mousumi Basu schreef: I want to perform binding between two computers having ip addresses 172.18.2.11 and 172.18.2.95.So <http://172.18.2.95.So> i wrote the following code(on the computer having IP address 172.18.2.95):- import socket import sys s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) try: s=s.bind(('172.18.2.11',2213)) print 'socket bind is complete' except socket.error,msg: print 'bind failed' sys.exit() You are hiding the error message here. Just print msg and see why it fails. Timo The output is :- bind failed but when i am writting;- s=s.bind(('localhost',2213)) the output is;- socket bind is complete Can you please tell me where i am making the error? (The computers are connected as the ping operation is executing properly in command prompt) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
Op 11-04-13 12:41, w qj schreef: I found this under Windows Python3 l="http://f/"; l[-1] is not '/' False and this under Linux Python3 l = "http://ff.f/"; l[-1] '/' l[-1] is not '/' True It's Looks like a python bug? This looks like a "is not" versus "!=" thing. Someone (I think Steven Apprano) posted a couple of days ago on this mailing list to only use "is" and "is not" when comparing to None. It works fine with regular operators. $ python3 Python 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l = "http://ff.f/"; >>> l[-1] '/' >>> l[-1] is not '/' True >>> l[-1] != '/' False Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor